Path: blob/master/thirdparty/astcenc/astcenc_weight_align.cpp
9905 views
// SPDX-License-Identifier: Apache-2.01// ----------------------------------------------------------------------------2// Copyright 2011-2024 Arm Limited3//4// Licensed under the Apache License, Version 2.0 (the "License"); you may not5// use this file except in compliance with the License. You may obtain a copy6// of the License at:7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13// License for the specific language governing permissions and limitations14// under the License.15// ----------------------------------------------------------------------------1617#if !defined(ASTCENC_DECOMPRESS_ONLY)1819/**20* @brief Functions for angular-sum algorithm for weight alignment.21*22* This algorithm works as follows:23* - we compute a complex number P as (cos s*i, sin s*i) for each weight,24* where i is the input value and s is a scaling factor based on the spacing between the weights.25* - we then add together complex numbers for all the weights.26* - we then compute the length and angle of the resulting sum.27*28* This should produce the following results:29* - perfect alignment results in a vector whose length is equal to the sum of lengths of all inputs30* - even distribution results in a vector of length 0.31* - all samples identical results in perfect alignment for every scaling.32*33* For each scaling factor within a given set, we compute an alignment factor from 0 to 1. This34* should then result in some scalings standing out as having particularly good alignment factors;35* we can use this to produce a set of candidate scale/shift values for various quantization levels;36* we should then actually try them and see what happens.37*/3839#include "astcenc_internal.h"40#include "astcenc_vecmathlib.h"4142#include <stdio.h>43#include <cassert>44#include <cstring>45#include <cfloat>4647static constexpr unsigned int ANGULAR_STEPS { 32 };4849static_assert((ANGULAR_STEPS % ASTCENC_SIMD_WIDTH) == 0,50"ANGULAR_STEPS must be multiple of ASTCENC_SIMD_WIDTH");5152static_assert(ANGULAR_STEPS >= 32,53"ANGULAR_STEPS must be at least max(steps_for_quant_level)");5455// Store a reduced sin/cos table for 64 possible weight values; this causes56// slight quality loss compared to using sin() and cos() directly. Must be 2^N.57static constexpr unsigned int SINCOS_STEPS { 64 };5859static const uint8_t steps_for_quant_level[12] {602, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 3261};6263ASTCENC_ALIGNAS static float sin_table[SINCOS_STEPS][ANGULAR_STEPS];64ASTCENC_ALIGNAS static float cos_table[SINCOS_STEPS][ANGULAR_STEPS];6566#if defined(ASTCENC_DIAGNOSTICS)67static bool print_once { true };68#endif6970/* See header for documentation. */71void prepare_angular_tables()72{73for (unsigned int i = 0; i < ANGULAR_STEPS; i++)74{75float angle_step = static_cast<float>(i + 1);7677for (unsigned int j = 0; j < SINCOS_STEPS; j++)78{79sin_table[j][i] = static_cast<float>(sinf((2.0f * astc::PI / (SINCOS_STEPS - 1.0f)) * angle_step * static_cast<float>(j)));80cos_table[j][i] = static_cast<float>(cosf((2.0f * astc::PI / (SINCOS_STEPS - 1.0f)) * angle_step * static_cast<float>(j)));81}82}83}8485/**86* @brief Compute the angular alignment factors and offsets.87*88* @param weight_count The number of (decimated) weights.89* @param dec_weight_ideal_value The ideal decimated unquantized weight values.90* @param max_angular_steps The maximum number of steps to be tested.91* @param[out] offsets The output angular offsets array.92*/93static void compute_angular_offsets(94unsigned int weight_count,95const float* dec_weight_ideal_value,96unsigned int max_angular_steps,97float* offsets98) {99promise(weight_count > 0);100promise(max_angular_steps > 0);101102ASTCENC_ALIGNAS int isamplev[BLOCK_MAX_WEIGHTS];103104// Precompute isample; arrays are always allocated 64 elements long105for (unsigned int i = 0; i < weight_count; i += ASTCENC_SIMD_WIDTH)106{107// Ideal weight can be outside [0, 1] range, so clamp to fit table108vfloat ideal_weight = clampzo(loada(dec_weight_ideal_value + i));109110// Convert a weight to a sincos table index111vfloat sample = ideal_weight * (SINCOS_STEPS - 1.0f);112vint isample = float_to_int_rtn(sample);113storea(isample, isamplev + i);114}115116// Arrays are multiple of SIMD width (ANGULAR_STEPS), safe to overshoot max117vfloat mult(1.0f / (2.0f * astc::PI));118119for (unsigned int i = 0; i < max_angular_steps; i += ASTCENC_SIMD_WIDTH)120{121vfloat anglesum_x = vfloat::zero();122vfloat anglesum_y = vfloat::zero();123124for (unsigned int j = 0; j < weight_count; j++)125{126int isample = isamplev[j];127anglesum_x += loada(cos_table[isample] + i);128anglesum_y += loada(sin_table[isample] + i);129}130131vfloat angle = atan2(anglesum_y, anglesum_x);132vfloat ofs = angle * mult;133storea(ofs, offsets + i);134}135}136137/**138* @brief For a given step size compute the lowest and highest weight.139*140* Compute the lowest and highest weight that results from quantizing using the given stepsize and141* offset, and then compute the resulting error. The cut errors indicate the error that results from142* forcing samples that should have had one weight value one step up or down.143*144* @param weight_count The number of (decimated) weights.145* @param dec_weight_ideal_value The ideal decimated unquantized weight values.146* @param max_angular_steps The maximum number of steps to be tested.147* @param max_quant_steps The maximum quantization level to be tested.148* @param offsets The angular offsets array.149* @param[out] lowest_weight Per angular step, the lowest weight.150* @param[out] weight_span Per angular step, the span between lowest and highest weight.151* @param[out] error Per angular step, the error.152* @param[out] cut_low_weight_error Per angular step, the low weight cut error.153* @param[out] cut_high_weight_error Per angular step, the high weight cut error.154*/155static void compute_lowest_and_highest_weight(156unsigned int weight_count,157const float* dec_weight_ideal_value,158unsigned int max_angular_steps,159unsigned int max_quant_steps,160const float* offsets,161float* lowest_weight,162int* weight_span,163float* error,164float* cut_low_weight_error,165float* cut_high_weight_error166) {167promise(weight_count > 0);168promise(max_angular_steps > 0);169170vfloat rcp_stepsize = int_to_float(vint::lane_id()) + vfloat(1.0f);171172// Compute minimum/maximum weights in the weight array. Our remapping173// is monotonic, so the min/max rounded weights relate to the min/max174// unrounded weights in a straightforward way.175vfloat min_weight(FLT_MAX);176vfloat max_weight(-FLT_MAX);177178vint lane_id = vint::lane_id();179for (unsigned int i = 0; i < weight_count; i += ASTCENC_SIMD_WIDTH)180{181vmask active = lane_id < vint(weight_count);182lane_id += vint(ASTCENC_SIMD_WIDTH);183184vfloat weights = loada(dec_weight_ideal_value + i);185min_weight = min(min_weight, select(min_weight, weights, active));186max_weight = max(max_weight, select(max_weight, weights, active));187}188189min_weight = hmin(min_weight);190max_weight = hmax(max_weight);191192// Arrays are ANGULAR_STEPS long, so always safe to run full vectors193for (unsigned int sp = 0; sp < max_angular_steps; sp += ASTCENC_SIMD_WIDTH)194{195vfloat errval = vfloat::zero();196vfloat cut_low_weight_err = vfloat::zero();197vfloat cut_high_weight_err = vfloat::zero();198vfloat offset = loada(offsets + sp);199200// We know the min and max weight values, so we can figure out201// the corresponding indices before we enter the loop.202vfloat minidx = round(min_weight * rcp_stepsize - offset);203vfloat maxidx = round(max_weight * rcp_stepsize - offset);204205for (unsigned int j = 0; j < weight_count; j++)206{207vfloat sval = load1(dec_weight_ideal_value + j) * rcp_stepsize - offset;208vfloat svalrte = round(sval);209vfloat diff = sval - svalrte;210errval += diff * diff;211212// Accumulate errors for minimum index213vmask mask = svalrte == minidx;214vfloat accum = cut_low_weight_err + vfloat(1.0f) - vfloat(2.0f) * diff;215cut_low_weight_err = select(cut_low_weight_err, accum, mask);216217// Accumulate errors for maximum index218mask = svalrte == maxidx;219accum = cut_high_weight_err + vfloat(1.0f) + vfloat(2.0f) * diff;220cut_high_weight_err = select(cut_high_weight_err, accum, mask);221}222223// Write out min weight and weight span; clamp span to a usable range224vint span = float_to_int(maxidx - minidx + vfloat(1));225span = min(span, vint(max_quant_steps + 3));226span = max(span, vint(2));227storea(minidx, lowest_weight + sp);228storea(span, weight_span + sp);229230// The cut_(lowest/highest)_weight_error indicate the error that results from forcing231// samples that should have had the weight value one step (up/down).232vfloat ssize = 1.0f / rcp_stepsize;233vfloat errscale = ssize * ssize;234storea(errval * errscale, error + sp);235storea(cut_low_weight_err * errscale, cut_low_weight_error + sp);236storea(cut_high_weight_err * errscale, cut_high_weight_error + sp);237238rcp_stepsize = rcp_stepsize + vfloat(ASTCENC_SIMD_WIDTH);239}240}241242/**243* @brief The main function for the angular algorithm.244*245* @param weight_count The number of (decimated) weights.246* @param dec_weight_ideal_value The ideal decimated unquantized weight values.247* @param max_quant_level The maximum quantization level to be tested.248* @param[out] low_value Per angular step, the lowest weight value.249* @param[out] high_value Per angular step, the highest weight value.250*/251static void compute_angular_endpoints_for_quant_levels(252unsigned int weight_count,253const float* dec_weight_ideal_value,254unsigned int max_quant_level,255float low_value[TUNE_MAX_ANGULAR_QUANT + 1],256float high_value[TUNE_MAX_ANGULAR_QUANT + 1]257) {258unsigned int max_quant_steps = steps_for_quant_level[max_quant_level];259unsigned int max_angular_steps = steps_for_quant_level[max_quant_level];260261ASTCENC_ALIGNAS float angular_offsets[ANGULAR_STEPS];262263compute_angular_offsets(weight_count, dec_weight_ideal_value,264max_angular_steps, angular_offsets);265266ASTCENC_ALIGNAS float lowest_weight[ANGULAR_STEPS];267ASTCENC_ALIGNAS int32_t weight_span[ANGULAR_STEPS];268ASTCENC_ALIGNAS float error[ANGULAR_STEPS];269ASTCENC_ALIGNAS float cut_low_weight_error[ANGULAR_STEPS];270ASTCENC_ALIGNAS float cut_high_weight_error[ANGULAR_STEPS];271272compute_lowest_and_highest_weight(weight_count, dec_weight_ideal_value,273max_angular_steps, max_quant_steps,274angular_offsets, lowest_weight, weight_span, error,275cut_low_weight_error, cut_high_weight_error);276277// For each quantization level, find the best error terms. Use packed vectors so data-dependent278// branches can become selects. This involves some integer to float casts, but the values are279// small enough so they never round the wrong way.280vfloat4 best_results[36];281282// Initialize the array to some safe defaults283promise(max_quant_steps > 0);284for (unsigned int i = 0; i < (max_quant_steps + 4); i++)285{286// Lane<0> = Best error287// Lane<1> = Best scale; -1 indicates no solution found288// Lane<2> = Cut low weight289best_results[i] = vfloat4(ERROR_CALC_DEFAULT, -1.0f, 0.0f, 0.0f);290}291292promise(max_angular_steps > 0);293for (unsigned int i = 0; i < max_angular_steps; i++)294{295float i_flt = static_cast<float>(i);296297int idx_span = weight_span[i];298299float error_cut_low = error[i] + cut_low_weight_error[i];300float error_cut_high = error[i] + cut_high_weight_error[i];301float error_cut_low_high = error[i] + cut_low_weight_error[i] + cut_high_weight_error[i];302303// Check best error against record N304vfloat4 best_result = best_results[idx_span];305vfloat4 new_result = vfloat4(error[i], i_flt, 0.0f, 0.0f);306vmask4 mask = vfloat4(best_result.lane<0>()) > vfloat4(error[i]);307best_results[idx_span] = select(best_result, new_result, mask);308309// Check best error against record N-1 with either cut low or cut high310best_result = best_results[idx_span - 1];311312new_result = vfloat4(error_cut_low, i_flt, 1.0f, 0.0f);313mask = vfloat4(best_result.lane<0>()) > vfloat4(error_cut_low);314best_result = select(best_result, new_result, mask);315316new_result = vfloat4(error_cut_high, i_flt, 0.0f, 0.0f);317mask = vfloat4(best_result.lane<0>()) > vfloat4(error_cut_high);318best_results[idx_span - 1] = select(best_result, new_result, mask);319320// Check best error against record N-2 with both cut low and high321best_result = best_results[idx_span - 2];322new_result = vfloat4(error_cut_low_high, i_flt, 1.0f, 0.0f);323mask = vfloat4(best_result.lane<0>()) > vfloat4(error_cut_low_high);324best_results[idx_span - 2] = select(best_result, new_result, mask);325}326327for (unsigned int i = 0; i <= max_quant_level; i++)328{329unsigned int q = steps_for_quant_level[i];330int bsi = static_cast<int>(best_results[q].lane<1>());331332// Did we find anything?333#if defined(ASTCENC_DIAGNOSTICS)334if ((bsi < 0) && print_once)335{336print_once = false;337printf("INFO: Unable to find full encoding within search error limit.\n\n");338}339#endif340341bsi = astc::max(0, bsi);342343float lwi = lowest_weight[bsi] + best_results[q].lane<2>();344float hwi = lwi + static_cast<float>(q) - 1.0f;345346float stepsize = 1.0f / (1.0f + static_cast<float>(bsi));347low_value[i] = (angular_offsets[bsi] + lwi) * stepsize;348high_value[i] = (angular_offsets[bsi] + hwi) * stepsize;349}350}351352/* See header for documentation. */353void compute_angular_endpoints_1plane(354bool only_always,355const block_size_descriptor& bsd,356const float* dec_weight_ideal_value,357unsigned int max_weight_quant,358compression_working_buffers& tmpbuf359) {360float (&low_value)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_low_value1;361float (&high_value)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_high_value1;362363float (&low_values)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_low_values1;364float (&high_values)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_high_values1;365366unsigned int max_decimation_modes = only_always ? bsd.decimation_mode_count_always367: bsd.decimation_mode_count_selected;368promise(max_decimation_modes > 0);369for (unsigned int i = 0; i < max_decimation_modes; i++)370{371const decimation_mode& dm = bsd.decimation_modes[i];372if (!dm.is_ref_1plane(static_cast<quant_method>(max_weight_quant)))373{374continue;375}376377unsigned int weight_count = bsd.get_decimation_info(i).weight_count;378379unsigned int max_precision = dm.maxprec_1plane;380if (max_precision > TUNE_MAX_ANGULAR_QUANT)381{382max_precision = TUNE_MAX_ANGULAR_QUANT;383}384385if (max_precision > max_weight_quant)386{387max_precision = max_weight_quant;388}389390compute_angular_endpoints_for_quant_levels(391weight_count,392dec_weight_ideal_value + i * BLOCK_MAX_WEIGHTS,393max_precision, low_values[i], high_values[i]);394}395396unsigned int max_block_modes = only_always ? bsd.block_mode_count_1plane_always397: bsd.block_mode_count_1plane_selected;398promise(max_block_modes > 0);399for (unsigned int i = 0; i < max_block_modes; i++)400{401const block_mode& bm = bsd.block_modes[i];402assert(!bm.is_dual_plane);403404unsigned int quant_mode = bm.quant_mode;405unsigned int decim_mode = bm.decimation_mode;406407if (quant_mode <= TUNE_MAX_ANGULAR_QUANT)408{409low_value[i] = low_values[decim_mode][quant_mode];410high_value[i] = high_values[decim_mode][quant_mode];411}412else413{414low_value[i] = 0.0f;415high_value[i] = 1.0f;416}417}418}419420/* See header for documentation. */421void compute_angular_endpoints_2planes(422const block_size_descriptor& bsd,423const float* dec_weight_ideal_value,424unsigned int max_weight_quant,425compression_working_buffers& tmpbuf426) {427float (&low_value1)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_low_value1;428float (&high_value1)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_high_value1;429float (&low_value2)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_low_value2;430float (&high_value2)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_high_value2;431432float (&low_values1)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_low_values1;433float (&high_values1)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_high_values1;434float (&low_values2)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_low_values2;435float (&high_values2)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_high_values2;436437promise(bsd.decimation_mode_count_selected > 0);438for (unsigned int i = 0; i < bsd.decimation_mode_count_selected; i++)439{440const decimation_mode& dm = bsd.decimation_modes[i];441if (!dm.is_ref_2plane(static_cast<quant_method>(max_weight_quant)))442{443continue;444}445446unsigned int weight_count = bsd.get_decimation_info(i).weight_count;447448unsigned int max_precision = dm.maxprec_2planes;449if (max_precision > TUNE_MAX_ANGULAR_QUANT)450{451max_precision = TUNE_MAX_ANGULAR_QUANT;452}453454if (max_precision > max_weight_quant)455{456max_precision = max_weight_quant;457}458459compute_angular_endpoints_for_quant_levels(460weight_count,461dec_weight_ideal_value + i * BLOCK_MAX_WEIGHTS,462max_precision, low_values1[i], high_values1[i]);463464compute_angular_endpoints_for_quant_levels(465weight_count,466dec_weight_ideal_value + i * BLOCK_MAX_WEIGHTS + WEIGHTS_PLANE2_OFFSET,467max_precision, low_values2[i], high_values2[i]);468}469470unsigned int start = bsd.block_mode_count_1plane_selected;471unsigned int end = bsd.block_mode_count_1plane_2plane_selected;472for (unsigned int i = start; i < end; i++)473{474const block_mode& bm = bsd.block_modes[i];475unsigned int quant_mode = bm.quant_mode;476unsigned int decim_mode = bm.decimation_mode;477478if (quant_mode <= TUNE_MAX_ANGULAR_QUANT)479{480low_value1[i] = low_values1[decim_mode][quant_mode];481high_value1[i] = high_values1[decim_mode][quant_mode];482low_value2[i] = low_values2[decim_mode][quant_mode];483high_value2[i] = high_values2[decim_mode][quant_mode];484}485else486{487low_value1[i] = 0.0f;488high_value1[i] = 1.0f;489low_value2[i] = 0.0f;490high_value2[i] = 1.0f;491}492}493}494495#endif496497498