astcenc_weight_align.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. // SPDX-License-Identifier: Apache-2.0
  2. // ----------------------------------------------------------------------------
  3. // Copyright 2011-2024 Arm Limited
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not
  6. // use this file except in compliance with the License. You may obtain a copy
  7. // of the License at:
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. // License for the specific language governing permissions and limitations
  15. // under the License.
  16. // ----------------------------------------------------------------------------
  17. #if !defined(ASTCENC_DECOMPRESS_ONLY)
  18. /**
  19. * @brief Functions for angular-sum algorithm for weight alignment.
  20. *
  21. * This algorithm works as follows:
  22. * - we compute a complex number P as (cos s*i, sin s*i) for each weight,
  23. * where i is the input value and s is a scaling factor based on the spacing between the weights.
  24. * - we then add together complex numbers for all the weights.
  25. * - we then compute the length and angle of the resulting sum.
  26. *
  27. * This should produce the following results:
  28. * - perfect alignment results in a vector whose length is equal to the sum of lengths of all inputs
  29. * - even distribution results in a vector of length 0.
  30. * - all samples identical results in perfect alignment for every scaling.
  31. *
  32. * For each scaling factor within a given set, we compute an alignment factor from 0 to 1. This
  33. * should then result in some scalings standing out as having particularly good alignment factors;
  34. * we can use this to produce a set of candidate scale/shift values for various quantization levels;
  35. * we should then actually try them and see what happens.
  36. */
  37. #include "astcenc_internal.h"
  38. #include "astcenc_vecmathlib.h"
  39. #include <stdio.h>
  40. #include <cassert>
  41. #include <cstring>
  42. #include <cfloat>
  43. static constexpr unsigned int ANGULAR_STEPS { 32 };
  44. static_assert((ANGULAR_STEPS % ASTCENC_SIMD_WIDTH) == 0,
  45. "ANGULAR_STEPS must be multiple of ASTCENC_SIMD_WIDTH");
  46. static_assert(ANGULAR_STEPS >= 32,
  47. "ANGULAR_STEPS must be at least max(steps_for_quant_level)");
  48. // Store a reduced sin/cos table for 64 possible weight values; this causes
  49. // slight quality loss compared to using sin() and cos() directly. Must be 2^N.
  50. static constexpr unsigned int SINCOS_STEPS { 64 };
  51. static const uint8_t steps_for_quant_level[12] {
  52. 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32
  53. };
  54. ASTCENC_ALIGNAS static float sin_table[SINCOS_STEPS][ANGULAR_STEPS];
  55. ASTCENC_ALIGNAS static float cos_table[SINCOS_STEPS][ANGULAR_STEPS];
  56. #if defined(ASTCENC_DIAGNOSTICS)
  57. static bool print_once { true };
  58. #endif
  59. /* See header for documentation. */
  60. void prepare_angular_tables()
  61. {
  62. for (unsigned int i = 0; i < ANGULAR_STEPS; i++)
  63. {
  64. float angle_step = static_cast<float>(i + 1);
  65. for (unsigned int j = 0; j < SINCOS_STEPS; j++)
  66. {
  67. sin_table[j][i] = static_cast<float>(sinf((2.0f * astc::PI / (SINCOS_STEPS - 1.0f)) * angle_step * static_cast<float>(j)));
  68. cos_table[j][i] = static_cast<float>(cosf((2.0f * astc::PI / (SINCOS_STEPS - 1.0f)) * angle_step * static_cast<float>(j)));
  69. }
  70. }
  71. }
  72. /**
  73. * @brief Compute the angular alignment factors and offsets.
  74. *
  75. * @param weight_count The number of (decimated) weights.
  76. * @param dec_weight_ideal_value The ideal decimated unquantized weight values.
  77. * @param max_angular_steps The maximum number of steps to be tested.
  78. * @param[out] offsets The output angular offsets array.
  79. */
  80. static void compute_angular_offsets(
  81. unsigned int weight_count,
  82. const float* dec_weight_ideal_value,
  83. unsigned int max_angular_steps,
  84. float* offsets
  85. ) {
  86. promise(weight_count > 0);
  87. promise(max_angular_steps > 0);
  88. ASTCENC_ALIGNAS int isamplev[BLOCK_MAX_WEIGHTS];
  89. // Precompute isample; arrays are always allocated 64 elements long
  90. for (unsigned int i = 0; i < weight_count; i += ASTCENC_SIMD_WIDTH)
  91. {
  92. // Ideal weight can be outside [0, 1] range, so clamp to fit table
  93. vfloat ideal_weight = clampzo(loada(dec_weight_ideal_value + i));
  94. // Convert a weight to a sincos table index
  95. vfloat sample = ideal_weight * (SINCOS_STEPS - 1.0f);
  96. vint isample = float_to_int_rtn(sample);
  97. storea(isample, isamplev + i);
  98. }
  99. // Arrays are multiple of SIMD width (ANGULAR_STEPS), safe to overshoot max
  100. vfloat mult(1.0f / (2.0f * astc::PI));
  101. for (unsigned int i = 0; i < max_angular_steps; i += ASTCENC_SIMD_WIDTH)
  102. {
  103. vfloat anglesum_x = vfloat::zero();
  104. vfloat anglesum_y = vfloat::zero();
  105. for (unsigned int j = 0; j < weight_count; j++)
  106. {
  107. int isample = isamplev[j];
  108. anglesum_x += loada(cos_table[isample] + i);
  109. anglesum_y += loada(sin_table[isample] + i);
  110. }
  111. vfloat angle = atan2(anglesum_y, anglesum_x);
  112. vfloat ofs = angle * mult;
  113. storea(ofs, offsets + i);
  114. }
  115. }
  116. /**
  117. * @brief For a given step size compute the lowest and highest weight.
  118. *
  119. * Compute the lowest and highest weight that results from quantizing using the given stepsize and
  120. * offset, and then compute the resulting error. The cut errors indicate the error that results from
  121. * forcing samples that should have had one weight value one step up or down.
  122. *
  123. * @param weight_count The number of (decimated) weights.
  124. * @param dec_weight_ideal_value The ideal decimated unquantized weight values.
  125. * @param max_angular_steps The maximum number of steps to be tested.
  126. * @param max_quant_steps The maximum quantization level to be tested.
  127. * @param offsets The angular offsets array.
  128. * @param[out] lowest_weight Per angular step, the lowest weight.
  129. * @param[out] weight_span Per angular step, the span between lowest and highest weight.
  130. * @param[out] error Per angular step, the error.
  131. * @param[out] cut_low_weight_error Per angular step, the low weight cut error.
  132. * @param[out] cut_high_weight_error Per angular step, the high weight cut error.
  133. */
  134. static void compute_lowest_and_highest_weight(
  135. unsigned int weight_count,
  136. const float* dec_weight_ideal_value,
  137. unsigned int max_angular_steps,
  138. unsigned int max_quant_steps,
  139. const float* offsets,
  140. float* lowest_weight,
  141. int* weight_span,
  142. float* error,
  143. float* cut_low_weight_error,
  144. float* cut_high_weight_error
  145. ) {
  146. promise(weight_count > 0);
  147. promise(max_angular_steps > 0);
  148. vfloat rcp_stepsize = int_to_float(vint::lane_id()) + vfloat(1.0f);
  149. // Compute minimum/maximum weights in the weight array. Our remapping
  150. // is monotonic, so the min/max rounded weights relate to the min/max
  151. // unrounded weights in a straightforward way.
  152. vfloat min_weight(FLT_MAX);
  153. vfloat max_weight(-FLT_MAX);
  154. vint lane_id = vint::lane_id();
  155. for (unsigned int i = 0; i < weight_count; i += ASTCENC_SIMD_WIDTH)
  156. {
  157. vmask active = lane_id < vint(weight_count);
  158. lane_id += vint(ASTCENC_SIMD_WIDTH);
  159. vfloat weights = loada(dec_weight_ideal_value + i);
  160. min_weight = min(min_weight, select(min_weight, weights, active));
  161. max_weight = max(max_weight, select(max_weight, weights, active));
  162. }
  163. min_weight = hmin(min_weight);
  164. max_weight = hmax(max_weight);
  165. // Arrays are ANGULAR_STEPS long, so always safe to run full vectors
  166. for (unsigned int sp = 0; sp < max_angular_steps; sp += ASTCENC_SIMD_WIDTH)
  167. {
  168. vfloat errval = vfloat::zero();
  169. vfloat cut_low_weight_err = vfloat::zero();
  170. vfloat cut_high_weight_err = vfloat::zero();
  171. vfloat offset = loada(offsets + sp);
  172. // We know the min and max weight values, so we can figure out
  173. // the corresponding indices before we enter the loop.
  174. vfloat minidx = round(min_weight * rcp_stepsize - offset);
  175. vfloat maxidx = round(max_weight * rcp_stepsize - offset);
  176. for (unsigned int j = 0; j < weight_count; j++)
  177. {
  178. vfloat sval = load1(dec_weight_ideal_value + j) * rcp_stepsize - offset;
  179. vfloat svalrte = round(sval);
  180. vfloat diff = sval - svalrte;
  181. errval += diff * diff;
  182. // Accumulate errors for minimum index
  183. vmask mask = svalrte == minidx;
  184. vfloat accum = cut_low_weight_err + vfloat(1.0f) - vfloat(2.0f) * diff;
  185. cut_low_weight_err = select(cut_low_weight_err, accum, mask);
  186. // Accumulate errors for maximum index
  187. mask = svalrte == maxidx;
  188. accum = cut_high_weight_err + vfloat(1.0f) + vfloat(2.0f) * diff;
  189. cut_high_weight_err = select(cut_high_weight_err, accum, mask);
  190. }
  191. // Write out min weight and weight span; clamp span to a usable range
  192. vint span = float_to_int(maxidx - minidx + vfloat(1));
  193. span = min(span, vint(max_quant_steps + 3));
  194. span = max(span, vint(2));
  195. storea(minidx, lowest_weight + sp);
  196. storea(span, weight_span + sp);
  197. // The cut_(lowest/highest)_weight_error indicate the error that results from forcing
  198. // samples that should have had the weight value one step (up/down).
  199. vfloat ssize = 1.0f / rcp_stepsize;
  200. vfloat errscale = ssize * ssize;
  201. storea(errval * errscale, error + sp);
  202. storea(cut_low_weight_err * errscale, cut_low_weight_error + sp);
  203. storea(cut_high_weight_err * errscale, cut_high_weight_error + sp);
  204. rcp_stepsize = rcp_stepsize + vfloat(ASTCENC_SIMD_WIDTH);
  205. }
  206. }
  207. /**
  208. * @brief The main function for the angular algorithm.
  209. *
  210. * @param weight_count The number of (decimated) weights.
  211. * @param dec_weight_ideal_value The ideal decimated unquantized weight values.
  212. * @param max_quant_level The maximum quantization level to be tested.
  213. * @param[out] low_value Per angular step, the lowest weight value.
  214. * @param[out] high_value Per angular step, the highest weight value.
  215. */
  216. static void compute_angular_endpoints_for_quant_levels(
  217. unsigned int weight_count,
  218. const float* dec_weight_ideal_value,
  219. unsigned int max_quant_level,
  220. float low_value[TUNE_MAX_ANGULAR_QUANT + 1],
  221. float high_value[TUNE_MAX_ANGULAR_QUANT + 1]
  222. ) {
  223. unsigned int max_quant_steps = steps_for_quant_level[max_quant_level];
  224. unsigned int max_angular_steps = steps_for_quant_level[max_quant_level];
  225. ASTCENC_ALIGNAS float angular_offsets[ANGULAR_STEPS];
  226. compute_angular_offsets(weight_count, dec_weight_ideal_value,
  227. max_angular_steps, angular_offsets);
  228. ASTCENC_ALIGNAS float lowest_weight[ANGULAR_STEPS];
  229. ASTCENC_ALIGNAS int32_t weight_span[ANGULAR_STEPS];
  230. ASTCENC_ALIGNAS float error[ANGULAR_STEPS];
  231. ASTCENC_ALIGNAS float cut_low_weight_error[ANGULAR_STEPS];
  232. ASTCENC_ALIGNAS float cut_high_weight_error[ANGULAR_STEPS];
  233. compute_lowest_and_highest_weight(weight_count, dec_weight_ideal_value,
  234. max_angular_steps, max_quant_steps,
  235. angular_offsets, lowest_weight, weight_span, error,
  236. cut_low_weight_error, cut_high_weight_error);
  237. // For each quantization level, find the best error terms. Use packed vectors so data-dependent
  238. // branches can become selects. This involves some integer to float casts, but the values are
  239. // small enough so they never round the wrong way.
  240. vfloat4 best_results[36];
  241. // Initialize the array to some safe defaults
  242. promise(max_quant_steps > 0);
  243. for (unsigned int i = 0; i < (max_quant_steps + 4); i++)
  244. {
  245. // Lane<0> = Best error
  246. // Lane<1> = Best scale; -1 indicates no solution found
  247. // Lane<2> = Cut low weight
  248. best_results[i] = vfloat4(ERROR_CALC_DEFAULT, -1.0f, 0.0f, 0.0f);
  249. }
  250. promise(max_angular_steps > 0);
  251. for (unsigned int i = 0; i < max_angular_steps; i++)
  252. {
  253. float i_flt = static_cast<float>(i);
  254. int idx_span = weight_span[i];
  255. float error_cut_low = error[i] + cut_low_weight_error[i];
  256. float error_cut_high = error[i] + cut_high_weight_error[i];
  257. float error_cut_low_high = error[i] + cut_low_weight_error[i] + cut_high_weight_error[i];
  258. // Check best error against record N
  259. vfloat4 best_result = best_results[idx_span];
  260. vfloat4 new_result = vfloat4(error[i], i_flt, 0.0f, 0.0f);
  261. vmask4 mask = vfloat4(best_result.lane<0>()) > vfloat4(error[i]);
  262. best_results[idx_span] = select(best_result, new_result, mask);
  263. // Check best error against record N-1 with either cut low or cut high
  264. best_result = best_results[idx_span - 1];
  265. new_result = vfloat4(error_cut_low, i_flt, 1.0f, 0.0f);
  266. mask = vfloat4(best_result.lane<0>()) > vfloat4(error_cut_low);
  267. best_result = select(best_result, new_result, mask);
  268. new_result = vfloat4(error_cut_high, i_flt, 0.0f, 0.0f);
  269. mask = vfloat4(best_result.lane<0>()) > vfloat4(error_cut_high);
  270. best_results[idx_span - 1] = select(best_result, new_result, mask);
  271. // Check best error against record N-2 with both cut low and high
  272. best_result = best_results[idx_span - 2];
  273. new_result = vfloat4(error_cut_low_high, i_flt, 1.0f, 0.0f);
  274. mask = vfloat4(best_result.lane<0>()) > vfloat4(error_cut_low_high);
  275. best_results[idx_span - 2] = select(best_result, new_result, mask);
  276. }
  277. for (unsigned int i = 0; i <= max_quant_level; i++)
  278. {
  279. unsigned int q = steps_for_quant_level[i];
  280. int bsi = static_cast<int>(best_results[q].lane<1>());
  281. // Did we find anything?
  282. #if defined(ASTCENC_DIAGNOSTICS)
  283. if ((bsi < 0) && print_once)
  284. {
  285. print_once = false;
  286. printf("INFO: Unable to find full encoding within search error limit.\n\n");
  287. }
  288. #endif
  289. bsi = astc::max(0, bsi);
  290. float lwi = lowest_weight[bsi] + best_results[q].lane<2>();
  291. float hwi = lwi + static_cast<float>(q) - 1.0f;
  292. float stepsize = 1.0f / (1.0f + static_cast<float>(bsi));
  293. low_value[i] = (angular_offsets[bsi] + lwi) * stepsize;
  294. high_value[i] = (angular_offsets[bsi] + hwi) * stepsize;
  295. }
  296. }
  297. /* See header for documentation. */
  298. void compute_angular_endpoints_1plane(
  299. bool only_always,
  300. const block_size_descriptor& bsd,
  301. const float* dec_weight_ideal_value,
  302. unsigned int max_weight_quant,
  303. compression_working_buffers& tmpbuf
  304. ) {
  305. float (&low_value)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_low_value1;
  306. float (&high_value)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_high_value1;
  307. float (&low_values)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_low_values1;
  308. float (&high_values)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_high_values1;
  309. unsigned int max_decimation_modes = only_always ? bsd.decimation_mode_count_always
  310. : bsd.decimation_mode_count_selected;
  311. promise(max_decimation_modes > 0);
  312. for (unsigned int i = 0; i < max_decimation_modes; i++)
  313. {
  314. const decimation_mode& dm = bsd.decimation_modes[i];
  315. if (!dm.is_ref_1plane(static_cast<quant_method>(max_weight_quant)))
  316. {
  317. continue;
  318. }
  319. unsigned int weight_count = bsd.get_decimation_info(i).weight_count;
  320. unsigned int max_precision = dm.maxprec_1plane;
  321. if (max_precision > TUNE_MAX_ANGULAR_QUANT)
  322. {
  323. max_precision = TUNE_MAX_ANGULAR_QUANT;
  324. }
  325. if (max_precision > max_weight_quant)
  326. {
  327. max_precision = max_weight_quant;
  328. }
  329. compute_angular_endpoints_for_quant_levels(
  330. weight_count,
  331. dec_weight_ideal_value + i * BLOCK_MAX_WEIGHTS,
  332. max_precision, low_values[i], high_values[i]);
  333. }
  334. unsigned int max_block_modes = only_always ? bsd.block_mode_count_1plane_always
  335. : bsd.block_mode_count_1plane_selected;
  336. promise(max_block_modes > 0);
  337. for (unsigned int i = 0; i < max_block_modes; i++)
  338. {
  339. const block_mode& bm = bsd.block_modes[i];
  340. assert(!bm.is_dual_plane);
  341. unsigned int quant_mode = bm.quant_mode;
  342. unsigned int decim_mode = bm.decimation_mode;
  343. if (quant_mode <= TUNE_MAX_ANGULAR_QUANT)
  344. {
  345. low_value[i] = low_values[decim_mode][quant_mode];
  346. high_value[i] = high_values[decim_mode][quant_mode];
  347. }
  348. else
  349. {
  350. low_value[i] = 0.0f;
  351. high_value[i] = 1.0f;
  352. }
  353. }
  354. }
  355. /* See header for documentation. */
  356. void compute_angular_endpoints_2planes(
  357. const block_size_descriptor& bsd,
  358. const float* dec_weight_ideal_value,
  359. unsigned int max_weight_quant,
  360. compression_working_buffers& tmpbuf
  361. ) {
  362. float (&low_value1)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_low_value1;
  363. float (&high_value1)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_high_value1;
  364. float (&low_value2)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_low_value2;
  365. float (&high_value2)[WEIGHTS_MAX_BLOCK_MODES] = tmpbuf.weight_high_value2;
  366. float (&low_values1)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_low_values1;
  367. float (&high_values1)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_high_values1;
  368. float (&low_values2)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_low_values2;
  369. float (&high_values2)[WEIGHTS_MAX_DECIMATION_MODES][TUNE_MAX_ANGULAR_QUANT + 1] = tmpbuf.weight_high_values2;
  370. promise(bsd.decimation_mode_count_selected > 0);
  371. for (unsigned int i = 0; i < bsd.decimation_mode_count_selected; i++)
  372. {
  373. const decimation_mode& dm = bsd.decimation_modes[i];
  374. if (!dm.is_ref_2plane(static_cast<quant_method>(max_weight_quant)))
  375. {
  376. continue;
  377. }
  378. unsigned int weight_count = bsd.get_decimation_info(i).weight_count;
  379. unsigned int max_precision = dm.maxprec_2planes;
  380. if (max_precision > TUNE_MAX_ANGULAR_QUANT)
  381. {
  382. max_precision = TUNE_MAX_ANGULAR_QUANT;
  383. }
  384. if (max_precision > max_weight_quant)
  385. {
  386. max_precision = max_weight_quant;
  387. }
  388. compute_angular_endpoints_for_quant_levels(
  389. weight_count,
  390. dec_weight_ideal_value + i * BLOCK_MAX_WEIGHTS,
  391. max_precision, low_values1[i], high_values1[i]);
  392. compute_angular_endpoints_for_quant_levels(
  393. weight_count,
  394. dec_weight_ideal_value + i * BLOCK_MAX_WEIGHTS + WEIGHTS_PLANE2_OFFSET,
  395. max_precision, low_values2[i], high_values2[i]);
  396. }
  397. unsigned int start = bsd.block_mode_count_1plane_selected;
  398. unsigned int end = bsd.block_mode_count_1plane_2plane_selected;
  399. for (unsigned int i = start; i < end; i++)
  400. {
  401. const block_mode& bm = bsd.block_modes[i];
  402. unsigned int quant_mode = bm.quant_mode;
  403. unsigned int decim_mode = bm.decimation_mode;
  404. if (quant_mode <= TUNE_MAX_ANGULAR_QUANT)
  405. {
  406. low_value1[i] = low_values1[decim_mode][quant_mode];
  407. high_value1[i] = high_values1[decim_mode][quant_mode];
  408. low_value2[i] = low_values2[decim_mode][quant_mode];
  409. high_value2[i] = high_values2[decim_mode][quant_mode];
  410. }
  411. else
  412. {
  413. low_value1[i] = 0.0f;
  414. high_value1[i] = 1.0f;
  415. low_value2[i] = 0.0f;
  416. high_value2[i] = 1.0f;
  417. }
  418. }
  419. }
  420. #endif