Okay, this is a significantly more complex format, typical of model quantization schemes. It involves not just packing bits but also applying a non-linear scale and an offset.
Here's the implementation for the log4_codec, assuming the 10-byte layout discussed (1 byte for scale/offset, 1 byte padding, 8 bytes for 4-bit data):
#include <arm_neon.h>
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <bit>
#include <stdexcept>
#include <limits>
#include <cmath> // For pow, log2, round, fabsf
#include <numeric> // For std::reduce (optional for finding max_abs)
#include <algorithm> // For std::max, std::min
#include <array> // For LUTs
// Forward declaration
template<typename ValueType, size_t Lanes>
struct bundle;
// --- Log4 Codec Extension ---
// Stores 16 values as 4-bit indices [-8, 7] with a shared
// 6-bit log scale (base 2, mapping 0..63 to exponents 0..10)
// and a 2-bit offset index mapping to {-2, -1, +1, +2}.
// Total storage: 10 bytes
// Byte 0: [OffsetBits (2) | ScaleBits (6)]
// Byte 1: Padding (unused)
// Bytes 2-9: Packed 4-bit values (16 nibbles)
struct log4_codec {
// Constants
static constexpr int Log4Bits = 4;
static constexpr int ScaleBits = 6;
static constexpr int OffsetBits = 2;
static constexpr size_t PackedDataBytes = (16 * Log4Bits) / 8; // 8 bytes
static constexpr size_t HeaderBytes = 2; // Scale/Offset + Padding
static constexpr size_t TotalBytes = HeaderBytes + PackedDataBytes; // 10 bytes
static constexpr int8_t MinVal4Bit = -8;
static constexpr int8_t MaxVal4Bit = 7;
// Offset lookup table: 00->-2, 01->-1, 10->+1, 11->+2
static constexpr std::array<float, 4> OffsetLUT = {-2.0f, -1.0f, 1.0f, 2.0f};
// --- Helper Functions ---
// Calculate actual scale from 6 scale bits
// Maps 0-63 to log2 scale 0-10 (representing scales 2^0=1 to 2^10=1024)
static inline constexpr float bits_to_scale(uint8_t scale_bits) {
// Linear interpolation of exponent between 0 and 10
float exponent = static_cast<float>(scale_bits & 0x3F) * 10.0f / 63.0f;
return std::pow(2.0f, exponent);
}
// Calculate scale bits from actual scale (inverse of bits_to_scale)
static inline constexpr uint8_t scale_to_bits(float actual_scale) {
if (actual_scale <= 1.0f) return 0; // Clamp to min scale (2^0 = 1)
if (actual_scale >= 1024.0f) return 63; // Clamp to max scale (2^10 = 1024)
// log2(scale) = exponent. Map exponent back to 0-63 range.
float exponent = std::log2(actual_scale);
// Add 0.5f for rounding before casting
uint8_t bits = static_cast<uint8_t>(exponent * 63.0f / 10.0f + 0.5f);
return std::min(bits, (uint8_t)63); // Ensure within 6 bits
}
// Find the index of the offset in LUT closest to a target offset value
// (Used during encoding to select the best 2-bit offset representation)
static inline constexpr uint8_t find_best_offset_bits(float target_offset) {
uint8_t best_bits = 0;
float min_diff = std::fabsf(target_offset - OffsetLUT[0]);
for (uint8_t i = 1; i < OffsetLUT.size(); ++i) {
float diff = std::fabsf(target_offset - OffsetLUT[i]);
if (diff < min_diff) {
min_diff = diff;
best_bits = i;
}
}
return best_bits; // Returns 0, 1, 2, or 3
}
// --- Load Function ---
// Loads 10 bytes into a bundle<float, 16>
template <typename TargetValueType>
static constexpr bundle<TargetValueType, 16> load(const void* src)
requires std::is_same_v<TargetValueType, float> // Only support loading into float
{
bundle<float, 16> result;
const uint8_t* bytes = static_cast<const uint8_t*>(src);
// 1. Extract Scale and Offset
uint8_t header_byte = bytes[0];
uint8_t scale_bits = header_byte & 0x3F; // Lower 6 bits
uint8_t offset_bits = (header_byte >> 6) & 0x03; // Upper 2 bits
float actual_scale = bits_to_scale(scale_bits);
float actual_offset = OffsetLUT[offset_bits]; // Get offset from LUT
// Broadcast scale and offset for Neon
float32x4_t scale_vec = vdupq_n_f32(actual_scale);
float32x4_t offset_vec = vdupq_n_f32(actual_offset);
// 2. Unpack 4-bit values
const int8_t* packed_nibbles_ptr = reinterpret_cast<const int8_t*>(bytes + HeaderBytes);
// Load 8 bytes containing 16 nibbles
int8x8_t packed_bytes = vld1_s8(packed_nibbles_ptr);
// Separate low and high nibbles into two vectors {n0, n2..n14} and {n1, n3..n15}
// We treat them as signed int8 for now, then sign-extend the 4-bit value properly.
int8x8_t low_nibbles_raw = vshr_n_s8(packed_bytes, 4); // Shift high nibble out (result is effectively sign extended based on original byte)
int8x8_t high_nibbles_raw = vshl_n_s8(packed_bytes, 4); // Make high nibble the high bits
high_nibbles_raw = vshr_n_s8(high_nibbles_raw, 4); // Shift back arithmetic (sign extend)
// Low nibbles need correcting if original byte was < 0x80
// This manual unpacking is simpler here than complex Neon shuffle/sign-extend for 4 bits
alignas(16) int8_t unpacked_s8[16];
const uint8_t* packed_u8 = bytes + HeaderBytes;
for(size_t i = 0; i < PackedDataBytes; ++i) {
uint8_t byte = packed_u8[i];
uint8_t lo_nibble = byte & 0x0F;
uint8_t hi_nibble = byte >> 4;
// Sign extend manually from 4 bits [-8, 7]
unpacked_s8[i * 2] = (lo_nibble & 0x08) ? (int8_t)(lo_nibble | 0xF0) : (int8_t)lo_nibble;
unpacked_s8[i * 2 + 1] = (hi_nibble & 0x08) ? (int8_t)(hi_nibble | 0xF0) : (int8_t)hi_nibble;
}
// Load unpacked signed int8 values
int8x16_t val4bit_s8 = vld1q_s8(unpacked_s8);
// 3. Convert to float and apply scale/offset
// Formula: result = (val4bit + offset) * scale
// Convert int8x16 -> int16x8 (low), int16x8 (high)
int16x8_t val4bit_s16_lo = vmovl_s8(vget_low_s8(val4bit_s8));
int16x8_t val4bit_s16_hi = vmovl_s8(vget_high_s8(val4bit_s8));
// Convert int16x8 -> int32x4 (x4 vectors)
int32x4_t val4bit_s32_0 = vmovl_s16(vget_low_s16(val4bit_s16_lo));
int32x4_t val4bit_s32_1 = vmovl_s16(vget_high_s16(val4bit_s16_lo));
int32x4_t val4bit_s32_2 = vmovl_s16(vget_low_s16(val4bit_s16_hi));
int32x4_t val4bit_s32_3 = vmovl_s16(vget_high_s16(val4bit_s16_hi));
// Convert int32x4 -> float32x4 (x4 vectors)
float32x4_t val4bit_f32_0 = vcvtq_f32_s32(val4bit_s32_0);
float32x4_t val4bit_f32_1 = vcvtq_f32_s32(val4bit_s32_1);
float32x4_t val4bit_f32_2 = vcvtq_f32_s32(val4bit_s32_2);
float32x4_t val4bit_f32_3 = vcvtq_f32_s32(val4bit_s32_3);
// Apply offset: intermediate = val4bit + offset
float32x4_t inter_0 = vaddq_f32(val4bit_f32_0, offset_vec);
float32x4_t inter_1 = vaddq_f32(val4bit_f32_1, offset_vec);
float32x4_t inter_2 = vaddq_f32(val4bit_f32_2, offset_vec);
float32x4_t inter_3 = vaddq_f32(val4bit_f32_3, offset_vec);
// Apply scale: result = intermediate * scale
result.data.val[0] = vmulq_f32(inter_0, scale_vec);
result.data.val[1] = vmulq_f32(inter_1, scale_vec);
result.data.val[2] = vmulq_f32(inter_2, scale_vec);
result.data.val[3] = vmulq_f32(inter_3, scale_vec);
return result;
}
// --- Store Function ---
// Stores a bundle<float, 16> into 10 bytes
template <typename SourceValueType>
static constexpr void store(const bundle<SourceValueType, 16>& data_bundle, void* dst)
requires std::is_same_v<SourceValueType, float> // Only support storing from float
{
uint8_t* out_bytes = static_cast<uint8_t*>(dst);
// 1. Determine Optimal Scale and Offset (Simplified Approach)
// - Find max absolute value to determine scale.
// - Calculate residuals based on that scale.
// - Find best offset to center residuals around the target 4-bit range.
// Extract float values (scalar for simplicity in finding range/scale/offset)
alignas(64) float input_floats[16];
vst1q_f32_x4(input_floats, data_bundle.data); // Store bundle data to array
// Find max absolute value
float max_abs = 0.0f;
for(float val : input_floats) {
max_abs = std::max(max_abs, std::fabsf(val));
}
// Estimate required scale (target range is roughly [-10, 9] after offset)
float target_scale = 1.0f; // Default scale if max_abs is 0
if (max_abs > 1e-9f) { // Avoid division by zero / noise
// We need scale * (MaxVal4Bit + MaxOffset) >= max_abs
// scale * (7 + 2) >= max_abs -> scale >= max_abs / 9.0
// Also need scale * (MinVal4Bit + MinOffset) <= min_abs_or_val
// scale * (-8 + -2) <= min_val -> scale >= min_val / -10.0 (if min_val < 0)
// Let's use the max_abs rule for simplicity
target_scale = max_abs / (MaxVal4Bit + std::fabsf(OffsetLUT[3])); // MaxVal + MaxAbsOffset (7 + 2 = 9)
target_scale = std::max(target_scale, max_abs / std::fabsf(MinVal4Bit + OffsetLUT[0])); // MaxAbs / abs(MinVal + MinAbsOffset) = max_abs/10
target_scale = std::max(target_scale, 1e-9f); // Ensure scale is positive
}
// Find the best representable scale bits and actual scale
uint8_t scale_bits = scale_to_bits(target_scale);
float actual_scale = bits_to_scale(scale_bits);
float inv_actual_scale = (actual_scale != 0.0f) ? (1.0f / actual_scale) : 0.0f; // Precompute inverse scale
// Calculate initial quantized values (before offset) and find their average
float quantized_sum = 0.0f;
for (float val : input_floats) {
quantized_sum += val * inv_actual_scale;
}
float quantized_avg = quantized_sum / 16.0f;
// Determine the best offset: we want (quantized_avg - best_offset) to be near 0
// So, best_offset is roughly quantized_avg. Find the closest LUT offset.
uint8_t offset_bits = find_best_offset_bits(quantized_avg);
float actual_offset = OffsetLUT[offset_bits];
// 2. Quantize Floats to 4-bit values using Neon
float32x4_t inv_scale_vec = vdupq_n_f32(inv_actual_scale);
float32x4_t offset_vec = vdupq_n_f32(actual_offset);
// Process 4 vectors of 4 floats
int8_t quantized_s8[16];
for (int i = 0; i < 4; ++i) {
// Load float vector
float32x4_t f_vec = data_bundle.data.val[i]; // Or vld1q_f32(input_floats + i*4);
// quantized = round(value / scale) - offset
// Calculate value / scale
float32x4_t scaled_f_vec = vmulq_f32(f_vec, inv_scale_vec);
// Subtract offset
float32x4_t final_f_vec = vsubq_f32(scaled_f_vec, offset_vec);
// Convert to int32 (with rounding - Neon intrinsic rounds to nearest, ties to even)
int32x4_t s32_vec = vcvtq_s32_f32(final_f_vec);
// Narrow to int16 with saturation
int16x4_t s16_vec = vqmovn_s32(s32_vec);
// Pack two int16x4 into int16x8 for further narrowing
// Need to do this carefully across loop iterations or store temporarily
// Simpler: Store s16_vec results and combine later
alignas(8) int16_t temp_s16[4];
vst1_s16(temp_s16, s16_vec);
for(int j=0; j<4; ++j) {
// Manual clamp and store to final s8 array index
int target_idx = i * 4 + j;
quantized_s8[target_idx] = static_cast<int8_t>(std::clamp((int)temp_s16[j], (int)MinVal4Bit, (int)MaxVal4Bit));
}
}
// Now quantized_s8 contains the 16 clamped 4-bit values as int8_t
// 3. Pack Scale/Offset and 4-bit values
// Store header byte
out_bytes[0] = (offset_bits << 6) | scale_bits;
out_bytes[1] = 0; // Padding
// Pack the 16 int8 values (each holding a 4-bit value) into 8 bytes
int8_t* packed_nibbles_ptr = reinterpret_cast<int8_t*>(out_bytes + HeaderBytes);
int8x16_t data_vec = vld1q_s8(quantized_s8); // Load clamped values
// Use the same packing logic as int4_codec store
int8x8_t low_part = vget_low_s8(data_vec); // lanes 0..7
int8x8_t high_part = vget_high_s8(data_vec); // lanes 8..15
// De-interleave elements to get {even} and {odd} elements across the 16 values
// vuzp1 -> {a0, a2, a4, a6, a8, a10, a12, a14} -> even indices, become low nibbles
// vuzp2 -> {a1, a3, a5, a7, a9, a11, a13, a15} -> odd indices, become high nibbles
int8x8_t low_nibbles = vuzp1_s8(low_part, high_part);
int8x8_t high_nibbles = vuzp2_s8(low_part, high_part);
// Mask to ensure only 4 bits (important for negative numbers becoming 0xF?)
// Clamping earlier should make this mostly redundant, but good practice.
low_nibbles = vand_s8(low_nibbles, vdup_n_s8(0x0F));
high_nibbles = vand_s8(high_nibbles, vdup_n_s8(0x0F)); // Mask high nibbles too before shift
// Shift high nibbles to the left by 4 bits
int8x8_t high_nibbles_shifted = vshl_n_s8(high_nibbles, 4);
// Combine low nibbles and shifted high nibbles
int8x8_t packed_bytes = vorr_s8(low_nibbles, high_nibbles_shifted);
// Store the 8 packed bytes
vst1_s8(packed_nibbles_ptr, packed_bytes);
}
};
// --- Example Usage (Add this to your main function) ---
#include <iostream>
#include <vector>
#include <iomanip>
void test_log4_codec() {
std::cout << "\n--- Log4 Codec Test ---" << std::endl;
// Example float data
alignas(64) float original_floats[16];
for(int i = 0; i < 16; ++i) {
// Generate some values with variation
original_floats[i] = std::sin(static_cast<float>(i) * 0.5f) * 20.0f + (i - 8);
}
std::cout << "Original floats: ";
for(float v : original_floats) std::cout << std::fixed << std::setprecision(2) << v << " ";
std::cout << std::endl;
// Load into a bundle
bundle<float> float_bundle = bundle<float>::load(original_floats);
// Store using log4 codec
alignas(16) uint8_t log4_packed_data[log4_codec::TotalBytes];
float_bundle.store<log4_codec>(log4_packed_data);
std::cout << "Log4 Packed Hex: ";
for(size_t i = 0; i < log4_codec::TotalBytes; ++i) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)log4_packed_data[i] << " ";
}
std::cout << std::dec << std::endl;
// Decode back using log4 codec
bundle<float> decoded_bundle = bundle<float>::load<log4_codec>(log4_packed_data);
// Retrieve decoded floats
alignas(64) float decoded_floats[16];
decoded_bundle.store(decoded_floats); // Store back to a float array
std::cout << "Decoded floats: ";
float total_error = 0.0f;
for(int i = 0; i < 16; ++i) {
std::cout << std::fixed << std::setprecision(2) << decoded_floats[i] << " ";
total_error += std::fabsf(original_floats[i] - decoded_floats[i]);
}
std::cout << std::endl;
std::cout << "Average Abs Error: " << std::fixed << std::setprecision(4) << (total_error / 16.0f) << std::endl;
// Print scale/offset details
uint8_t header = log4_packed_data[0];
uint8_t scale_bits = header & 0x3F;
uint8_t offset_bits = (header >> 6) & 0x03;
std::cout << "Encoded Scale Bits: " << (int)scale_bits
<< ", Offset Bits: " << (int)offset_bits
<< " (Scale: " << std::fixed << std::setprecision(3) << log4_codec::bits_to_scale(scale_bits)
<< ", Offset: " << log4_codec::OffsetLUT[offset_bits] << ")" << std::endl;
}
// Remember to call test_log4_codec() in your main function.
// int main() {
// // ... other tests
// test_log4_codec();
// return 0;
// }
Key Implementation Details of log4_codec:
- Constants and LUT: Defines sizes, bit counts, the 4-bit value range, and the offset lookup table.
bits_to_scale/scale_to_bits: Helper functions for converting between the 6-bit representation and the actual float scale value using the log2 relationship. Includes clamping.
find_best_offset_bits: Helper used during encoding to choose the closest offset from the LUT {-2, -1, 1, 2} based on the average "residual" value.
load (Decoding):
- Reads the header byte to get scale/offset bits.
- Calculates
actual_scale and actual_offset.
- Unpacks the 8 bytes of nibbles into 16 signed 4-bit values (
int8_t from -8 to 7) using manual sign extension (simpler than complex Neon for this).
- Uses Neon to convert
int8 -> int16 -> int32 -> float32.
- Applies the formula
result = (val4bit + offset) * scale using vaddq_f32 and vmulq_f32.
store (Encoding):
- Simplified Scale/Offset Selection:
- Finds the maximum absolute value of the input floats.
- Estimates a
target_scale based on needing to cover the input range with the output range (Val4Bit + Offset).
- Converts
target_scale to the closest representable 6-bit scale_bits and calculates the corresponding actual_scale.
- Calculates the average value after dividing by the
actual_scale.
- Chooses the
offset_bits whose corresponding LUT value is closest to this average (this tries to center the data).
- Quantization:
- Uses Neon to apply the inverse formula:
quantized = round(value / scale) - offset.
- Uses
vmulq_f32 for division (multiply by inverse scale).
- Uses
vsubq_f32 to subtract the chosen actual_offset.
- Converts float to int32 using
vcvtq_s32_f32 (rounds to nearest).
- Narrows
int32 -> int16 -> int8 with saturation (vqmovn_s32, manual clamp/store). Explicit clamping to [-8, 7] is done after vcvtq_s32_f32 as Neon saturation might not target this specific range directly during narrowing.
This implementation provides a functional codec for this format, demonstrating both the bit manipulation and the arithmetic involved in quantization/dequantization using ARM Neon. The encoding uses a simplified heuristic for choosing scale/offset; more advanced schemes might involve iterative optimization or pre-calculated statistics.