rng.cpp 14.9 KB
Newer Older
1 2 3 4
/**
 * \file dnn/test/common/rng.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11 12
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */
#include "test/common/rng.h"

M
Megvii Engine Team 已提交
13
#include <gtest/gtest.h>
14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include "test/common/random_state.h"
#include "test/common/tensor.h"

using namespace megdnn;
using namespace test;

/*!
 * \brief xorshift+ RNG, which is very fast
 *
 * see https://en.wikipedia.org/wiki/Xorshift#xorshift.2B
 */
class RNG::RNGxorshf {
    uint64_t s[2];

M
Megvii Engine Team 已提交
28 29
public:
    using result_type = uint64_t;
30 31

#ifdef WIN32
M
Megvii Engine Team 已提交
32 33
    static uint64_t min() { return 0; }
    static uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
34
#else
M
Megvii Engine Team 已提交
35 36
    static constexpr uint64_t min() { return 0; }
    static constexpr uint64_t max() { return std::numeric_limits<uint64_t>::max(); }
37 38
#endif

M
Megvii Engine Team 已提交
39 40 41 42 43
    template <typename T>
    explicit RNGxorshf(T&& gen) {
        s[0] = gen();
        s[1] = gen();
    }
44

M
Megvii Engine Team 已提交
45 46 47 48 49 50 51 52
    uint64_t operator()() {
        uint64_t x = s[0];
        uint64_t const y = s[1];
        s[0] = y;
        x ^= x << 23;                          // a
        s[1] = x ^ y ^ (x >> 17) ^ (y >> 26);  // b, c
        return s[1] + y;
    }
53 54 55
};

Float16PeriodicalRNG::Float16PeriodicalRNG() : m_offset(0) {
M
Megvii Engine Team 已提交
56
    for (size_t x = 0; x < (1u << 16); ++x) {
57 58 59 60 61 62
        size_t exponent = (x >> 10) & 0x1F;
        if (exponent == 0x1F) {
            // +inf, -inf, NaN
            continue;
        }
        union U {
M
Megvii Engine Team 已提交
63
            U() {}
64 65 66 67 68 69
            uint16_t i;
            dt_float16 f;
        } i2f;
        i2f.i = static_cast<uint16_t>(x);
        m_sequence.push_back(i2f.f);
    }
70
    COMPAT_RANDOM(m_sequence.begin(), m_sequence.end());
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
}

Float16PeriodicalRNG::Float16PeriodicalRNG(size_t range) : m_offset(0) {
    union U {
        U() {}
        uint16_t i;
        dt_float16 f;
    } i2f;
    size_t x = 0;
    i2f.i = static_cast<uint16_t>(x);
    for (size_t i = 0; i < range; i++) {
        x += 1;
        i2f.i = static_cast<uint16_t>(x);
        m_sequence.push_back(i2f.f);
    }
    x = 1u << 15;
    i2f.i = static_cast<uint16_t>(x);
    for (size_t i = 0; i < range; i++) {
        x += 1;
        i2f.i = static_cast<uint16_t>(x);
        m_sequence.push_back(i2f.f);
    }

94
    COMPAT_RANDOM(m_sequence.begin(), m_sequence.end());
95 96 97 98 99 100 101
}

void Float16PeriodicalRNG::gen(const TensorND& tensor) {
    megdnn_assert(tensor.layout.dtype == dtype::Float16());
    size_t nr_elems = tensor.layout.span().dist_elem();
    auto offset = tensor.layout.span().low_elem;
    for (size_t i = 0; i < nr_elems; ++i) {
M
Megvii Engine Team 已提交
102
        tensor.ptr<dt_float16>()[offset + i] = get_single_val();
103 104 105 106 107 108 109 110 111 112 113 114 115
    }
}

dt_float16 Float16PeriodicalRNG::get_single_val() {
    if (m_offset >= m_sequence.size()) {
        m_offset = 0;
    }
    return m_sequence[m_offset++];
}

void IIDRNG::gen(const TensorND& tensor) {
    if (tensor.layout.dtype == dtype::Float32() && has_fast_float32() &&
        tensor.layout.is_physical_contiguous()) {
M
Megvii Engine Team 已提交
116
        fill_fast_float32(tensor.ptr<dt_float32>(), tensor.layout.total_nr_elems());
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        return;
    }

    auto offset = tensor.layout.span().low_elem;
    auto nr_elems = tensor.layout.span().dist_elem();
#define cb(DType)                                                   \
    if (tensor.layout.dtype == DType()) {                           \
        using ctype = typename DTypeTrait<DType>::ctype;            \
        auto ptr = tensor.ptr<ctype>();                             \
        for (size_t i = 0; i < nr_elems; ++i) {                     \
            ptr[offset + i] = static_cast<ctype>(gen_single_val()); \
        }                                                           \
        return;                                                     \
    }
    MEGDNN_FOREACH_COMPUTING_DTYPE(cb);
#undef cb
#define cb(DType)                                                              \
    if (tensor.layout.dtype.enumv() == DTypeTrait<DType>::enumv) {             \
        using ctype = typename DTypeTrait<DType>::ctype;                       \
        auto ptr = tensor.ptr<ctype>();                                        \
        if (output_is_float()) {                                               \
            for (size_t i = 0; i < nr_elems; ++i) {                            \
                ptr[offset + i] = tensor.layout.dtype.param<DType>().quantize( \
                        static_cast<float>(gen_single_val()));                 \
            }                                                                  \
        } else {                                                               \
            for (size_t i = 0; i < nr_elems; ++i) {                            \
                ptr[offset + i] = static_cast<ctype>(gen_single_val());        \
            }                                                                  \
        }                                                                      \
        return;                                                                \
    }
    MEGDNN_FOREACH_QUANTIZED_DTYPE(cb)
    //! In order to avoid an unnecessary increase in binary size, we just
    //! use QuantizedS16 dtype in winograd_filter_preprocess now.
    cb(::megdnn::dtype::QuantizedS16)
#undef cb
M
Megvii Engine Team 已提交
154
            if (tensor.layout.dtype.enumv() == DTypeEnum::Quantized4Asymm) {
155 156 157
        auto ptr = static_cast<uint8_t*>(tensor.raw_ptr);
        if (output_is_float()) {
            for (size_t i = 0; i < nr_elems; i += 2) {
M
Megvii Engine Team 已提交
158 159 160 161 162 163
                uint8_t val0 = tensor.layout.dtype.param<dt_quint4>()
                                       .quantize(static_cast<float>(gen_single_val()))
                                       .as_uint8();
                uint8_t val1 = tensor.layout.dtype.param<dt_quint4>()
                                       .quantize(static_cast<float>(gen_single_val()))
                                       .as_uint8();
164 165 166 167 168 169 170 171 172 173 174
                ptr[(offset + i) / 2] = (val1 << 4) | val0;
            }
        } else {
            for (size_t i = 0; i < nr_elems; i += 2) {
                uint8_t val0 = static_cast<uint8_t>(gen_single_val());
                uint8_t val1 = static_cast<uint8_t>(gen_single_val());
                ptr[(offset + i) / 2] = (val1 << 4) | val0;
            }
        }
        return;
    }
175 176 177 178
    if (tensor.layout.dtype.enumv() == DTypeEnum::QuantizedS4) {
        auto ptr = static_cast<int8_t*>(tensor.raw_ptr);
        if (output_is_float()) {
            for (size_t i = 0; i < nr_elems; i += 2) {
M
Megvii Engine Team 已提交
179 180 181 182 183 184
                int8_t val0 = tensor.layout.dtype.param<dt_qint4>()
                                      .quantize(static_cast<float>(gen_single_val()))
                                      .as_int8();
                int8_t val1 = tensor.layout.dtype.param<dt_qint4>()
                                      .quantize(static_cast<float>(gen_single_val()))
                                      .as_int8();
185 186 187 188 189 190 191
                ptr[(offset + i) / 2] = (val0 & 0xF) | (val1 << 4);
            }
        } else {
            for (size_t i = 0; i < nr_elems; i += 2) {
                int8_t val0 = static_cast<int8_t>(gen_single_val());
                int8_t val1 = static_cast<int8_t>(gen_single_val());

M
Megvii Engine Team 已提交
192 193 194 195
                val0 = std::min(val0, DTypeTrait<dtype::QuantizedS4>::max());
                val0 = std::max(val0, DTypeTrait<dtype::QuantizedS4>::min());
                val1 = std::min(val1, DTypeTrait<dtype::QuantizedS4>::max());
                val1 = std::max(val1, DTypeTrait<dtype::QuantizedS4>::min());
196 197 198 199 200
                ptr[(offset + i) / 2] = (val0 & 0xF) | (val1 << 4);
            }
        }
        return;
    }
201 202 203 204
    if (tensor.layout.dtype.enumv() == DTypeEnum::Byte) {
        memset(tensor.raw_ptr, 0, tensor.layout.access_bytes());
        return;
    }
M
Megvii Engine Team 已提交
205 206 207
    megdnn_assert(
            0, "IIDRNG does not know how to generate value for DType %s",
            tensor.layout.dtype.name());
208 209 210 211 212 213
}

bool IIDRNG::has_fast_float32() {
    return false;
}

M
Megvii Engine Team 已提交
214
void IIDRNG::fill_fast_float32(dt_float32*, size_t) {
215 216 217
    megdnn_assert(0);
}

M
Megvii Engine Team 已提交
218 219
dt_float32 NormalRNG::gen_single_val() {
    auto&& gen = RandomState::generator();
220 221 222 223 224 225 226
    return m_dist(gen);
}

bool NormalRNG::has_fast_float32() {
    return true;
}

M
Megvii Engine Team 已提交
227
void NormalRNG::fill_fast_float32(dt_float32* dest, size_t size) {
228
    RNGxorshf gen{RandomState::generator()};
M
Megvii Engine Team 已提交
229
    for (size_t i = 0; i < size; ++i) {
230 231 232 233
        dest[i] = m_dist(gen);
    }
}

M
Megvii Engine Team 已提交
234 235
void ConstValue::fill_fast_float32(dt_float32* dest, size_t size) {
    for (size_t i = 0; i < size; ++i)
236 237 238
        dest[i] = value_;
}

M
Megvii Engine Team 已提交
239 240
dt_float32 UniformIntRNG::gen_single_val() {
    auto&& gen = RandomState::generator();
241 242 243 244 245 246 247 248 249 250 251 252 253
    return static_cast<dt_float32>(m_dist(gen));
}

dt_float32 UniformIntNonZeroRNG::gen_single_val() {
    auto&& gen = RandomState::generator();
    auto ret = UniformIntRNG::gen_single_val();
    if (m_dist_flip(gen)) {
        ret = -ret;
    }
    megdnn_assert(ret != 0);
    return ret;
}

M
Megvii Engine Team 已提交
254 255
dt_float32 UniformFloatRNG::gen_single_val() {
    auto&& gen = RandomState::generator();
256 257 258 259 260 261 262
    return m_dist(gen);
}

bool UniformFloatRNG::has_fast_float32() {
    return true;
}

M
Megvii Engine Team 已提交
263
void UniformFloatRNG::fill_fast_float32(dt_float32* dest, size_t size) {
264 265
    RNGxorshf gen{RandomState::generator()};
    auto k = double(m_dist.b() - m_dist.a()) /
M
Megvii Engine Team 已提交
266
             double(RNGxorshf::max() - RNGxorshf::min() + 1.0);
267
    auto b = m_dist.a() - RNGxorshf::min() * k;
M
Megvii Engine Team 已提交
268
    for (size_t i = 0; i < size; ++i) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        dest[i] = gen() * k + b;
    }
}

dt_float32 UniformFloatNonZeroRNG::gen_single_val() {
    auto&& gen = RandomState::generator();
    auto ret = UniformFloatRNG::gen_single_val();
    if (m_dist_flip(gen)) {
        ret = -ret;
    }
    megdnn_assert(ret != 0);
    return ret;
}

void UniformFloatNonZeroRNG::fill_fast_float32(dt_float32* dest, size_t size) {
    RNGxorshf gen{RandomState::generator()};
    UniformFloatRNG::fill_fast_float32(dest, size);
    for (size_t i = 0; i < size; ++i) {
        if (m_dist_flip(gen)) {
            dest[i] = -dest[i];
        }
    }
}

M
Megvii Engine Team 已提交
293
void UniformFloatWithValueRNG::fill_fast_float32(dt_float32* dest, size_t size) {
294 295
    RNGxorshf gen{RandomState::generator()};
    auto k = double(m_dist.b() - m_dist.a()) /
M
Megvii Engine Team 已提交
296
             double(RNGxorshf::max() - RNGxorshf::min() + 1.0);
297 298 299 300
    auto b = m_dist.a() - RNGxorshf::min() * k;

    auto p = 1.0 / double(RNGxorshf::max() - RNGxorshf::min() + 1.0);
    auto pb = 0.f - RNGxorshf::min() * p;
M
Megvii Engine Team 已提交
301
    for (size_t i = 0; i < size; ++i) {
302
        float rnd = gen() * p + pb;
M
Megvii Engine Team 已提交
303
        if (rnd < val_proportion_) {
304
            dest[i] = val_;
305 306 307 308 309 310
        } else {
            dest[i] = gen() * k + b;
        }
    }
}

M
Megvii Engine Team 已提交
311
BernoulliRNG::BernoulliRNG(float probability_) : m_dist(0, 1) {
312 313 314 315
    megdnn_assert(0.0f <= probability_ && probability_ < 1.0f);
    m_probability = probability_;
}

M
Megvii Engine Team 已提交
316 317
dt_float32 BernoulliRNG::gen_single_val() {
    auto&& gen = RandomState::generator();
318 319 320
    return m_dist(gen) < m_probability ? 1.0 : 0.0;
}

M
Megvii Engine Team 已提交
321
void NoReplacementRNG::gen(const TensorND& tensor) {
322 323
    auto offset = tensor.layout.span().low_elem;
    auto nr_elems = tensor.layout.span().dist_elem();
M
Megvii Engine Team 已提交
324 325 326 327 328 329 330 331
#define cb(DType)                                                      \
    if (tensor.layout.dtype == DType()) {                              \
        using ctype = typename DTypeTrait<DType>::ctype;               \
        std::set<ctype> values;                                        \
        auto ptr = tensor.ptr<ctype>();                                \
        for (size_t i = 0; i < nr_elems; ++i) {                        \
            ctype val;                                                 \
            do {                                                       \
332
                val = static_cast<ctype>(m_iid_rng->gen_single_val()); \
M
Megvii Engine Team 已提交
333 334 335
            } while (!values.insert(val).second);                      \
            ptr[offset + i] = val;                                     \
        }                                                              \
336 337 338 339 340
    }
    MEGDNN_FOREACH_COMPUTING_DTYPE(cb);
#undef cb
}

M
Megvii Engine Team 已提交
341 342
InvertibleMatrixRNG::InvertibleMatrixRNG()
        : m_rng{new RNGxorshf{RandomState::generator()}} {}
343 344 345

InvertibleMatrixRNG::~InvertibleMatrixRNG() noexcept = default;

M
Megvii Engine Team 已提交
346 347
template <typename ctype>
void InvertibleMatrixRNG::do_gen(ctype* ptr, size_t batch, size_t n) {
348 349
    auto&& gen = *m_rng;
    std::vector<size_t> perm(n);
M
Megvii Engine Team 已提交
350
    for (size_t i = 0; i < n; ++i) {
351 352
        perm[i] = i;
    }
M
Megvii Engine Team 已提交
353 354 355 356 357
    for (size_t i = 0; i < batch; ++i, ptr += n * n) {
        for (size_t j = 0; j < n; ++j) {
            for (size_t k = 0; k < n; ++k) {
                ptr[j * n + k] =
                        static_cast<ctype>(gen() / (RNGxorshf::max() + 1.0) * 2 - 0.5);
358 359
            }
        }
M
Megvii Engine Team 已提交
360
        for (size_t i = 0; i < n; ++i) {
361 362 363 364 365 366 367 368 369
            auto idx = gen() % (n - i) + i;
            ptr[i * n + perm[idx]] +=
                    static_cast<ctype>(gen() / (RNGxorshf::max() + 1.0) + 3);
            std::swap(perm[idx], perm[i]);
        }
    }
}

void InvertibleMatrixRNG::gen(const TensorND& tensor) {
M
Megvii Engine Team 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383
#define cb(DType)                                                                   \
    if (tensor.layout.dtype == DType()) {                                           \
        using ctype = typename DTypeTrait<DType>::ctype;                            \
        auto ptr = tensor.ptr<ctype>();                                             \
        megdnn_assert(                                                              \
                tensor.layout.ndim >= 2 && tensor.layout.is_physical_contiguous()); \
        size_t batch = 1;                                                           \
        for (size_t i = 0; i < tensor.layout.ndim - 2; ++i) {                       \
            batch *= tensor.layout[i];                                              \
        }                                                                           \
        size_t n = tensor.layout[tensor.layout.ndim - 1];                           \
        megdnn_assert(n == tensor.layout[tensor.layout.ndim - 2]);                  \
        do_gen<ctype>(ptr, batch, n);                                               \
        return;                                                                     \
384 385 386 387 388
    }
    MEGDNN_FOREACH_COMPUTING_DTYPE_FLOAT(cb)
#undef cb
}
void ConsecutiveRNG::fill_fast_float32(dt_float32* dest, size_t size) {
M
Megvii Engine Team 已提交
389
    for (size_t i = 0; i < size; ++i)
390 391 392
        dest[i] = value_ + i * delta_;
}

M
Megvii Engine Team 已提交
393
TEST(RNG, NO_REPLACEMENT_RNG) {
394
    static const size_t N = 10, TIMES = 100;
M
Megvii Engine Team 已提交
395
    UniformIntRNG base_rng(0, N - 1);
396 397 398 399 400 401 402
    NoReplacementRNG rng(&base_rng);
    auto handle = create_cpu_handle(2, false);
    for (size_t t = 0; t < TIMES; ++t) {
        TensorLayout layout({N}, dtype::Float32());
        Tensor<> tensor(handle.get(), layout);
        rng.gen(tensor.tensornd());
        std::vector<float> vals;
M
Megvii Engine Team 已提交
403 404
        for (size_t i = 0; i < N; ++i)
            vals.push_back(tensor.ptr()[i]);
405
        std::sort(vals.begin(), vals.end());
M
Megvii Engine Team 已提交
406 407
        for (size_t i = 0; i < N; ++i)
            ASSERT_EQ(static_cast<float>(i), vals[i]);
408 409 410
    }
}
// vim: syntax=cpp.doxygen