Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clamp before downcasting in float to i8 conversions #422

Merged
Merged
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
10 changes: 7 additions & 3 deletions include/usearch/index_plugins.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -331,10 +331,13 @@ class f16_bits_t {
inline explicit operator bool() const noexcept { return f16_to_f32(uint16_) > 0.5f; }

inline f16_bits_t(i8_converted_t) noexcept;
inline f16_bits_t(std::int8_t v) noexcept : uint16_(v) {}
inline f16_bits_t(bool v) noexcept : uint16_(f32_to_f16(v)) {}
inline f16_bits_t(float v) noexcept : uint16_(f32_to_f16(v)) {}
inline f16_bits_t(double v) noexcept : uint16_(f32_to_f16(static_cast<float>(v))) {}

inline bool operator<(const f16_bits_t& other) const noexcept { return float(*this) < float(other); }

inline f16_bits_t operator+(f16_bits_t other) const noexcept { return {float(*this) + float(other)}; }
inline f16_bits_t operator-(f16_bits_t other) const noexcept { return {float(*this) - float(other)}; }
inline f16_bits_t operator*(f16_bits_t other) const noexcept { return {float(*this) * float(other)}; }
Expand Down Expand Up @@ -960,12 +963,13 @@ class i8_converted_t {
inline explicit operator std::int32_t() const noexcept { return int8_; }
inline explicit operator std::int64_t() const noexcept { return int8_; }

// Even with `f16_t` arguments we may want to use `f32_t` for clamping and comparions.
inline i8_converted_t(f16_t v)
: int8_(usearch::clamp<std::int8_t>(static_cast<std::int8_t>(v * divisor_k), min_k, max_k)) {}
: int8_(static_cast<std::int8_t>(usearch::clamp<f32_t>(v * divisor_k, min_k, max_k))) {}
inline i8_converted_t(f32_t v)
: int8_(usearch::clamp<std::int8_t>(static_cast<std::int8_t>(v * divisor_k), min_k, max_k)) {}
: int8_(static_cast<std::int8_t>(usearch::clamp<f32_t>(v * divisor_k, min_k, max_k))) {}
inline i8_converted_t(f64_t v)
: int8_(usearch::clamp<std::int8_t>(static_cast<std::int8_t>(v * divisor_k), min_k, max_k)) {}
: int8_(static_cast<std::int8_t>(usearch::clamp<f64_t>(v * divisor_k, min_k, max_k))) {}
};

f16_bits_t::f16_bits_t(i8_converted_t v) noexcept : uint16_(f32_to_f16(v)) {}
Expand Down
Loading