Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions common/include/common_defs.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
#include <random>
#include <chrono>
#include <thread>
#include <type_traits>
#include <utility>

/// DataSketches namespace
namespace datasketches {
Expand Down Expand Up @@ -54,6 +56,54 @@ namespace random_utils {
}
}

template<typename... Ts> struct make_void { using type = void; };

/**
* C++11 version of the UniformRandomBitGenerator requirements of the standard library,
* which C++20 expresses as std::uniform_random_bit_generator plus G::result_type:
* G::result_type is an unsigned integer type, G::min() and G::max() are constant expressions of that type
* with G::min() < G::max(), and invoking a non-const G returns G::result_type.
* The standard engines, such as std::mt19937_64, meet these requirements.
*/
template<typename G, typename = void>
struct is_uniform_random_bit_generator: std::false_type {};

template<typename G>
struct is_uniform_random_bit_generator<G, typename make_void<
typename G::result_type,
decltype(std::declval<G&>()()),
std::integral_constant<typename G::result_type, G::min()>, // fails unless G::min() is a constant expression
std::integral_constant<typename G::result_type, G::max()>
>::type>: std::integral_constant<bool,
std::is_unsigned<typename G::result_type>::value
&& !std::is_same<typename std::remove_cv<typename G::result_type>::type, bool>::value
&& std::is_same<decltype(std::declval<G&>()()), typename G::result_type>::value
&& std::is_same<decltype(G::min()), typename G::result_type>::value
&& std::is_same<decltype(G::max()), typename G::result_type>::value
&& (G::min() < G::max())
> {};

/**
* Returns a fair random bit from a uniform random bit generator.
* The bit depends only on the generator output, unlike std::bernoulli_distribution,
* so a given generator state gives the same bits with any standard library.
* The bit tells whether the output is in the upper half of the range, since the high bits
* of some engines are better than the low bits. If the range has an odd number of values,
* the largest value is skipped, so the generator can be invoked more than once.
* With a range of {0, 1}, the bit is the output.
*/
template<typename G>
bool random_bit_from(G& generator) {
static_assert(is_uniform_random_bit_generator<G>::value, "G must be a uniform random bit generator");
using U = typename G::result_type;
const U span = static_cast<U>(G::max() - G::min()); // number of values - 1
const U last = static_cast<U>(span - 1 + span % 2); // largest accepted offset: an even number of values from 0
for (;;) {
const U offset = static_cast<U>(generator() - G::min());
if (offset <= last) return offset > last / 2;
}
}

// utility function to hide unused compiler warning
// usually has no additional cost
template<typename T> void unused(T&&...) {}
Expand Down
1 change: 1 addition & 0 deletions common/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ target_sources(common_test
hash_test.cpp
serde_test.cpp
inv_pow2_test.cpp
random_bit_test.cpp
)

# now the integration test part
Expand Down
175 changes: 175 additions & 0 deletions common/test/random_bit_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

#include <catch2/catch.hpp>

#include <cstdint>
#include <functional>
#include <random>
#include <utility>
#include <vector>

#include "common_defs.hpp"

namespace datasketches {

// returns the given values in a loop
template<typename UInt, UInt Min, UInt Max>
class sequence_generator {
public:
using result_type = UInt;
static constexpr result_type min() { return Min; }
static constexpr result_type max() { return Max; }

explicit sequence_generator(std::vector<UInt> values): values_(std::move(values)), calls_(0) {}
result_type operator()() { return values_[calls_++ % values_.size()]; }
size_t calls() const { return calls_; }

private:
std::vector<UInt> values_;
size_t calls_;
};

struct signed_result {
using result_type = int32_t;
static constexpr result_type min() { return 0; }
static constexpr result_type max() { return 1; }
result_type operator()() { return 0; }
};

struct bool_result {
using result_type = bool;
static constexpr result_type min() { return false; }
static constexpr result_type max() { return true; }
result_type operator()() { return false; }
};

struct mismatched_result {
using result_type = uint32_t;
static constexpr result_type min() { return 0; }
static constexpr result_type max() { return 1; }
uint64_t operator()() { return 0; }
};

struct no_result_type {
static constexpr uint32_t min() { return 0; }
static constexpr uint32_t max() { return 1; }
uint32_t operator()() { return 0; }
};

struct runtime_range {
using result_type = uint32_t;
static result_type min() { return 0; }
static result_type max() { return 1; }
result_type operator()() { return 0; }
};

struct empty_range {
using result_type = uint32_t;
static constexpr result_type min() { return 1; }
static constexpr result_type max() { return 1; }
result_type operator()() { return 1; }
};

using default_random_bit_generator = decltype(random_utils::random_bit);

static_assert(is_uniform_random_bit_generator<default_random_bit_generator>::value, "");
static_assert(is_uniform_random_bit_generator<std::mt19937>::value, "");
static_assert(is_uniform_random_bit_generator<std::mt19937_64>::value, "");
static_assert(is_uniform_random_bit_generator<std::minstd_rand>::value, "");
static_assert(is_uniform_random_bit_generator<std::random_device>::value, "");
static_assert(is_uniform_random_bit_generator<sequence_generator<uint8_t, 5, 8>>::value, "");

// integers must not be taken for generators, such as a weight passed to kll_sketch::update()
static_assert(!is_uniform_random_bit_generator<uint32_t>::value, "");
static_assert(!is_uniform_random_bit_generator<int>::value, "");
static_assert(!is_uniform_random_bit_generator<const uint64_t>::value, "");
// the range is needed to derive a fair bit, so callables without it are rejected
static_assert(!is_uniform_random_bit_generator<bool()>::value, "");
static_assert(!is_uniform_random_bit_generator<std::function<bool()>>::value, "");
static_assert(!is_uniform_random_bit_generator<no_result_type>::value, "");
static_assert(!is_uniform_random_bit_generator<runtime_range>::value, "");
static_assert(!is_uniform_random_bit_generator<empty_range>::value, "");
static_assert(!is_uniform_random_bit_generator<signed_result>::value, "");
static_assert(!is_uniform_random_bit_generator<bool_result>::value, "");
static_assert(!is_uniform_random_bit_generator<mismatched_result>::value, "");
static_assert(!is_uniform_random_bit_generator<const std::mt19937>::value, "a const generator cannot be invoked");

TEST_CASE("is uniform random bit generator: lambda", "[random_bit]") {
auto lambda = [] { return true; };
static_assert(!is_uniform_random_bit_generator<decltype(lambda)>::value, "");
unused(lambda);
}

TEST_CASE("random bit from: range {0, 1} gives the output", "[random_bit]") {
sequence_generator<uint32_t, 0, 1> generator({0, 1, 1, 0});
REQUIRE_FALSE(random_bit_from(generator));
REQUIRE(random_bit_from(generator));
REQUIRE(random_bit_from(generator));
REQUIRE_FALSE(random_bit_from(generator));
REQUIRE(generator.calls() == 4);
}

TEST_CASE("random bit from: default generator gives its output", "[random_bit]") {
default_random_bit_generator generator(7);
default_random_bit_generator copy(generator);
for (int i = 0; i < 1000; ++i) REQUIRE(random_bit_from(generator) == (copy() == 1));
}

TEST_CASE("random bit from: upper half of the range", "[random_bit]") {
sequence_generator<uint8_t, 5, 8> small({5, 6, 7, 8});
REQUIRE_FALSE(random_bit_from(small));
REQUIRE_FALSE(random_bit_from(small));
REQUIRE(random_bit_from(small));
REQUIRE(random_bit_from(small));

const uint64_t top_bit = UINT64_C(1) << 63;
sequence_generator<uint64_t, 0, UINT64_MAX> full({0, top_bit - 1, top_bit, UINT64_MAX});
REQUIRE_FALSE(random_bit_from(full));
REQUIRE_FALSE(random_bit_from(full));
REQUIRE(random_bit_from(full));
REQUIRE(random_bit_from(full));
REQUIRE(full.calls() == 4);
}

TEST_CASE("random bit from: odd number of values skips the largest", "[random_bit]") {
sequence_generator<uint16_t, 10, 12> generator({12, 10, 12, 12, 11});
REQUIRE_FALSE(random_bit_from(generator));
REQUIRE(generator.calls() == 2);
REQUIRE(random_bit_from(generator));
REQUIRE(generator.calls() == 5);
}

template<typename Engine>
static unsigned count_ones(Engine engine, unsigned num_bits) {
unsigned ones = 0;
for (unsigned i = 0; i < num_bits; ++i) ones += random_bit_from(engine) ? 1 : 0;
return ones;
}

TEST_CASE("random bit from: standard engines are fair", "[random_bit]") {
// the standard deviation of the count is about 158, and the engines are seeded, so the result is fixed
REQUIRE(count_ones(std::mt19937(1), 100000) == Approx(50000).margin(1000));
REQUIRE(count_ones(std::minstd_rand(1), 100000) == Approx(50000).margin(1000));
// an odd number of values: 0 to 2^31 - 2
REQUIRE(count_ones(std::linear_congruential_engine<uint32_t, 48271, 1, 2147483647>(1), 100000)
== Approx(50000).margin(1000));
}

} /* namespace datasketches */
23 changes: 7 additions & 16 deletions kll/include/kll_helper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@

namespace datasketches {

#ifdef KLL_VALIDATION
extern uint32_t kll_next_offset;
#endif

// 0 <= power <= 30
static const uint64_t powers_of_three[] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441,
1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467,
Expand All @@ -47,11 +43,11 @@ class kll_helper {
static inline uint16_t int_cap_aux_aux(uint16_t k, uint8_t depth);
static inline uint64_t sum_the_sample_weights(uint8_t num_levels, const uint32_t* levels);

template <typename T>
static void randomly_halve_down(T* buf, uint32_t start, uint32_t length);
template <typename T, typename RandomBitGenerator>
static void randomly_halve_down(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator);

template <typename T>
static void randomly_halve_up(T* buf, uint32_t start, uint32_t length);
template <typename T, typename RandomBitGenerator>
static void randomly_halve_up(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator);

// this version moves objects within the same buffer
// assumes that destination has initialized objects
Expand Down Expand Up @@ -101,22 +97,17 @@ class kll_helper {
static inline compress_result predict_compress(uint16_t k, uint8_t m, uint8_t num_levels_in,
const uint32_t* in_levels, uint32_t* level_sizes);

template <typename T, typename C>
template <typename T, typename C, typename RandomBitGenerator>
static compress_result general_compress(uint16_t k, uint8_t m, uint8_t num_levels_in, T* items,
uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator);
uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator,
RandomBitGenerator& random_bit_generator);

template<typename T>
static void copy_construct(const T* src, size_t src_first, size_t src_last, T* dst, size_t dst_first);

template<typename T>
static void move_construct(T* src, size_t src_first, size_t src_last, T* dst, size_t dst_first, bool destroy);

#ifdef KLL_VALIDATION
private:

static inline uint32_t deterministic_offset();
#endif

};

} /* namespace datasketches */
Expand Down
37 changes: 11 additions & 26 deletions kll/include/kll_helper_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,31 +93,23 @@ uint64_t kll_helper::sum_the_sample_weights(uint8_t num_levels, const uint32_t*
return total;
}

template <typename T>
void kll_helper::randomly_halve_down(T* buf, uint32_t start, uint32_t length) {
template <typename T, typename RandomBitGenerator>
void kll_helper::randomly_halve_down(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator) {
if (!is_even(length)) { throw std::invalid_argument("length must be even"); }
const uint32_t half_length = length / 2;
#ifdef KLL_VALIDATION
const uint32_t offset = deterministic_offset();
#else
const uint32_t offset = random_utils::random_bit();
#endif
const uint32_t offset = random_bit_from(random_bit_generator) ? 1 : 0;
uint32_t j = start + offset;
for (uint32_t i = start; i < (start + half_length); i++) {
if (i != j) buf[i] = std::move(buf[j]);
j += 2;
}
}

template <typename T>
void kll_helper::randomly_halve_up(T* buf, uint32_t start, uint32_t length) {
template <typename T, typename RandomBitGenerator>
void kll_helper::randomly_halve_up(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator) {
if (!is_even(length)) { throw std::invalid_argument("length must be even"); }
const uint32_t half_length = length / 2;
#ifdef KLL_VALIDATION
const uint32_t offset = deterministic_offset();
#else
const uint32_t offset = random_utils::random_bit();
#endif
const uint32_t offset = random_bit_from(random_bit_generator) ? 1 : 0;
uint32_t j = (start + length) - 1 - offset;
for (uint32_t i = (start + length) - 1; i >= (start + half_length); i--) {
if (i != j) buf[i] = std::move(buf[j]);
Expand Down Expand Up @@ -231,9 +223,10 @@ kll_helper::compress_result kll_helper::predict_compress(uint16_t k, uint8_t m,
* sorted afterwards.
* Level zero is not required to be sorted before, and may not be sorted afterwards.
*/
template <typename T, typename C>
template <typename T, typename C, typename RandomBitGenerator>
kll_helper::compress_result kll_helper::general_compress(uint16_t k, uint8_t m, uint8_t num_levels_in, T* items,
uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator)
uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator,
RandomBitGenerator& random_bit_generator)
{
if (num_levels_in == 0) { throw std::invalid_argument("num_levels_in == 0"); } // things are too weird if zero levels are allowed
const uint32_t starting_item_count = in_levels[num_levels_in] - in_levels[0];
Expand Down Expand Up @@ -286,9 +279,9 @@ kll_helper::compress_result kll_helper::general_compress(uint16_t k, uint8_t m,
}

if (pop_above == 0) { // Level above is empty, so halve up
randomly_halve_up(items, adj_beg, adj_pop);
randomly_halve_up(items, adj_beg, adj_pop, random_bit_generator);
} else { // Level above is nonempty, so halve down, then merge up
randomly_halve_down(items, adj_beg, adj_pop);
randomly_halve_down(items, adj_beg, adj_pop, random_bit_generator);
merge_sorted_arrays<T, C>(items, adj_beg, half_adj_pop, raw_lim, pop_above, adj_beg + half_adj_pop, comparator);
}

Expand Down Expand Up @@ -340,14 +333,6 @@ void kll_helper::move_construct(T* src, size_t src_first, size_t src_last, T* ds
}
}

#ifdef KLL_VALIDATION
uint32_t kll_helper::deterministic_offset() {
const uint32_t result(kll_next_offset);
kll_next_offset = 1 - kll_next_offset;
return result;
}
#endif

} /* namespace datasketches */

#endif // KLL_HELPER_IMPL_HPP_
Loading