Skip to content

Commit

Permalink
Adjust linear quantizer (#573)
Browse files Browse the repository at this point in the history
  • Loading branch information
elshize authored Jan 27, 2024
1 parent d0efb61 commit ef68dab
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
12 changes: 8 additions & 4 deletions include/pisa/linear_quantizer.hpp
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
#pragma once
#include "spdlog/spdlog.h"

#include <cmath>
#include <cstdint>

#include <fmt/format.h>
#include <gsl/gsl_assert>

namespace pisa {

struct LinearQuantizer {
explicit LinearQuantizer(float max, uint8_t bits)
: m_max(max), m_scale(static_cast<float>(1U << (bits)) / max) {
explicit LinearQuantizer(float max, std::uint8_t bits)
: m_max(max), m_scale(static_cast<float>((1U << bits) - 1U) / max) {
if (bits > 32 or bits == 0) {
throw std::runtime_error(fmt::format(
"Linear quantizer must take a number of bits between 1 and 32 but {} passed", bits
));
}
}

[[nodiscard]] auto operator()(float value) const -> std::uint32_t {
Expects(value <= m_max);
return std::ceil(value * m_scale);
Expand All @@ -24,4 +28,4 @@ struct LinearQuantizer {
float m_scale;
};

} // namespace pisa
} // namespace pisa
24 changes: 24 additions & 0 deletions test/test_linear_quantizer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"

#include <limits>

#include "linear_quantizer.hpp"

TEST_CASE("LinearQuantizer", "[scoring][unit]") {
SECTION("construct") {
WHEN("number of bits is 0 or 33") {
std::uint8_t bits = GENERATE(0, 33);
THEN("constructor fails") {
REQUIRE_THROWS(pisa::LinearQuantizer(10.0, bits));
}
}
}
SECTION("scores") {
std::uint8_t bits = GENERATE(3, 8, 12, 16, 19, 32);
float max = GENERATE(1.0, 100.0, std::numeric_limits<float>::max());
pisa::LinearQuantizer quantizer(max, bits);
REQUIRE(quantizer(0) == 0);
REQUIRE(quantizer(max) == (1 << bits) - 1);
}
}

0 comments on commit ef68dab

Please sign in to comment.