@img/sharp-libvips-dev 1.2.1 → 1.2.2-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/include/ffi.h +3 -3
  2. package/include/harfbuzz/hb-version.h +3 -3
  3. package/include/hwy/abort.h +2 -19
  4. package/include/hwy/aligned_allocator.h +11 -7
  5. package/include/hwy/auto_tune.h +504 -0
  6. package/include/hwy/base.h +425 -104
  7. package/include/hwy/cache_control.h +16 -0
  8. package/include/hwy/detect_compiler_arch.h +32 -1
  9. package/include/hwy/detect_targets.h +251 -67
  10. package/include/hwy/foreach_target.h +35 -0
  11. package/include/hwy/highway.h +185 -76
  12. package/include/hwy/nanobenchmark.h +1 -19
  13. package/include/hwy/ops/arm_neon-inl.h +969 -458
  14. package/include/hwy/ops/arm_sve-inl.h +1137 -359
  15. package/include/hwy/ops/emu128-inl.h +97 -11
  16. package/include/hwy/ops/generic_ops-inl.h +1222 -34
  17. package/include/hwy/ops/loongarch_lasx-inl.h +4664 -0
  18. package/include/hwy/ops/loongarch_lsx-inl.h +5933 -0
  19. package/include/hwy/ops/ppc_vsx-inl.h +306 -126
  20. package/include/hwy/ops/rvv-inl.h +546 -51
  21. package/include/hwy/ops/scalar-inl.h +77 -22
  22. package/include/hwy/ops/set_macros-inl.h +138 -17
  23. package/include/hwy/ops/shared-inl.h +50 -10
  24. package/include/hwy/ops/wasm_128-inl.h +137 -92
  25. package/include/hwy/ops/x86_128-inl.h +773 -214
  26. package/include/hwy/ops/x86_256-inl.h +712 -255
  27. package/include/hwy/ops/x86_512-inl.h +429 -753
  28. package/include/hwy/ops/x86_avx3-inl.h +501 -0
  29. package/include/hwy/per_target.h +2 -1
  30. package/include/hwy/profiler.h +622 -486
  31. package/include/hwy/targets.h +62 -20
  32. package/include/hwy/timer-inl.h +8 -160
  33. package/include/hwy/timer.h +170 -3
  34. package/include/hwy/x86_cpuid.h +81 -0
  35. package/include/libheif/heif_cxx.h +25 -5
  36. package/include/libheif/heif_regions.h +5 -5
  37. package/include/libheif/heif_version.h +2 -2
  38. package/include/librsvg-2.0/librsvg/rsvg-version.h +2 -2
  39. package/include/pango-1.0/pango/pango-enum-types.h +3 -0
  40. package/include/pango-1.0/pango/pango-features.h +3 -3
  41. package/include/pango-1.0/pango/pango-font.h +30 -0
  42. package/include/pango-1.0/pango/pango-version-macros.h +26 -0
  43. package/include/zlib.h +3 -3
  44. package/package.json +1 -1
  45. package/versions.json +8 -8
package/include/ffi.h CHANGED
@@ -1,5 +1,5 @@
1
1
  /* -----------------------------------------------------------------*-C-*-
2
- libffi 3.5.1
2
+ libffi 3.5.2
3
3
  - Copyright (c) 2011, 2014, 2019, 2021, 2022, 2024, 2025 Anthony Green
4
4
  - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
5
5
 
@@ -316,8 +316,8 @@ size_t ffi_java_raw_size (ffi_cif *cif) __attribute__((deprecated));
316
316
 
317
317
  /* ---- Version API ------------------------------------------------------ */
318
318
 
319
- #define FFI_VERSION_STRING "3.5.1"
320
- #define FFI_VERSION_NUMBER 30501
319
+ #define FFI_VERSION_STRING "3.5.2"
320
+ #define FFI_VERSION_NUMBER 30502
321
321
 
322
322
  #ifndef LIBFFI_ASM
323
323
  /* Return a version string. */
@@ -47,20 +47,20 @@ HB_BEGIN_DECLS
47
47
  *
48
48
  * The minor component of the library version available at compile-time.
49
49
  */
50
- #define HB_VERSION_MINOR 3
50
+ #define HB_VERSION_MINOR 4
51
51
  /**
52
52
  * HB_VERSION_MICRO:
53
53
  *
54
54
  * The micro component of the library version available at compile-time.
55
55
  */
56
- #define HB_VERSION_MICRO 2
56
+ #define HB_VERSION_MICRO 5
57
57
 
58
58
  /**
59
59
  * HB_VERSION_STRING:
60
60
  *
61
61
  * A string literal containing the library version available at compile-time.
62
62
  */
63
- #define HB_VERSION_STRING "11.3.2"
63
+ #define HB_VERSION_STRING "11.4.5"
64
64
 
65
65
  /**
66
66
  * HB_VERSION_ATLEAST:
@@ -5,24 +5,7 @@
5
5
  #ifndef HIGHWAY_HWY_ABORT_H_
6
6
  #define HIGHWAY_HWY_ABORT_H_
7
7
 
8
- #include "hwy/highway_export.h"
9
-
10
- namespace hwy {
11
-
12
- // Interface for custom abort handler
13
- typedef void (*AbortFunc)(const char* file, int line,
14
- const char* formatted_err);
15
-
16
- // Retrieve current abort handler
17
- // Returns null if no abort handler registered, indicating Highway should print and abort
18
- HWY_DLLEXPORT AbortFunc& GetAbortFunc();
19
-
20
- // Sets a new abort handler and returns the previous abort handler
21
- // If this handler does not do the aborting itself Highway will use its own abort mechanism
22
- // which allows this to be used to customize the handling of the error itself.
23
- // Returns null if no previous abort handler registered
24
- HWY_DLLEXPORT AbortFunc SetAbortFunc(AbortFunc func);
25
-
26
- } // namespace hwy
8
+ // Empty header for compatibility.
9
+ // All Abort/Warn functionalities are in base.h.
27
10
 
28
11
  #endif // HIGHWAY_HWY_ABORT_H_
@@ -40,6 +40,7 @@ namespace hwy {
40
40
  // access pairs of lines, and M1 L2 and POWER8 lines are also 128 bytes.
41
41
  #define HWY_ALIGNMENT 128
42
42
 
43
+ // `align` is in bytes.
43
44
  template <typename T>
44
45
  HWY_API constexpr bool IsAligned(T* ptr, size_t align = HWY_ALIGNMENT) {
45
46
  return reinterpret_cast<uintptr_t>(ptr) % align == 0;
@@ -181,14 +182,14 @@ static inline constexpr size_t ShiftCount(size_t n) {
181
182
 
182
183
  template <typename T>
183
184
  T* AllocateAlignedItems(size_t items, AllocPtr alloc_ptr, void* opaque_ptr) {
184
- constexpr size_t size = sizeof(T);
185
+ constexpr size_t kSize = sizeof(T);
185
186
 
186
- constexpr bool is_pow2 = (size & (size - 1)) == 0;
187
- constexpr size_t bits = ShiftCount(size);
188
- static_assert(!is_pow2 || (1ull << bits) == size, "ShiftCount is incorrect");
187
+ constexpr bool kIsPow2 = (kSize & (kSize - 1)) == 0;
188
+ constexpr size_t kBits = ShiftCount(kSize);
189
+ static_assert(!kIsPow2 || (1ull << kBits) == kSize, "ShiftCount has a bug");
189
190
 
190
- const size_t bytes = is_pow2 ? items << bits : items * size;
191
- const size_t check = is_pow2 ? bytes >> bits : bytes / size;
191
+ const size_t bytes = kIsPow2 ? items << kBits : items * kSize;
192
+ const size_t check = kIsPow2 ? bytes >> kBits : bytes / kSize;
192
193
  if (check != items) {
193
194
  return nullptr; // overflowed
194
195
  }
@@ -232,7 +233,6 @@ class AlignedFreer {
232
233
 
233
234
  template <typename T>
234
235
  void operator()(T* aligned_pointer) const {
235
- // TODO(deymo): assert that we are using a POD type T.
236
236
  FreeAlignedBytes(aligned_pointer, free_, opaque_ptr_);
237
237
  }
238
238
 
@@ -251,6 +251,10 @@ using AlignedFreeUniquePtr = std::unique_ptr<T, AlignedFreer>;
251
251
  template <typename T>
252
252
  AlignedFreeUniquePtr<T[]> AllocateAligned(const size_t items, AllocPtr alloc,
253
253
  FreePtr free, void* opaque) {
254
+ static_assert(std::is_trivially_copyable<T>::value,
255
+ "AllocateAligned: requires trivially copyable T");
256
+ static_assert(std::is_trivially_destructible<T>::value,
257
+ "AllocateAligned: requires trivially destructible T");
254
258
  return AlignedFreeUniquePtr<T[]>(
255
259
  detail::AllocateAlignedItems<T>(items, alloc, opaque),
256
260
  AlignedFreer(free, opaque));
@@ -0,0 +1,504 @@
1
+ // Copyright 2025 Google LLC
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+
16
+ #ifndef HIGHWAY_HWY_AUTO_TUNE_H_
17
+ #define HIGHWAY_HWY_AUTO_TUNE_H_
18
+
19
+ #include <stddef.h>
20
+ #include <stdint.h>
21
+ #include <string.h> // memmove
22
+
23
+ #include <cmath>
24
+ #include <vector>
25
+
26
+ #include "hwy/aligned_allocator.h" // Span
27
+ #include "hwy/base.h" // HWY_MIN
28
+ #include "hwy/contrib/sort/vqsort.h"
29
+
30
+ // Infrastructure for auto-tuning (choosing optimal parameters at runtime).
31
+
32
+ namespace hwy {
33
+
34
+ // O(1) storage to estimate the central tendency of hundreds of independent
35
+ // distributions (one per configuration). The number of samples per distribution
36
+ // (`kMinSamples`) varies from few to dozens. We support both by first storing
37
+ // values in a buffer, and when full, switching to online variance estimation.
38
+ // Modified from `hwy/stats.h`.
39
+ class CostDistribution {
40
+ public:
41
+ static constexpr size_t kMaxValues = 14; // for total size of 128 bytes
42
+
43
+ void Notify(const double x) {
44
+ if (HWY_UNLIKELY(x < 0.0)) {
45
+ HWY_WARN("Ignoring negative cost %f.", x);
46
+ return;
47
+ }
48
+
49
+ // Online phase after filling and warm-up.
50
+ if (HWY_LIKELY(IsOnline())) return OnlineNotify(x);
51
+
52
+ // Fill phase: store up to `kMaxValues` values.
53
+ values_[num_values_++] = x;
54
+ HWY_DASSERT(num_values_ <= kMaxValues);
55
+ if (HWY_UNLIKELY(num_values_ == kMaxValues)) {
56
+ WarmUpOnline();
57
+ HWY_DASSERT(IsOnline());
58
+ }
59
+ }
60
+
61
+ // Returns an estimate of the true cost, mitigating the impact of noise.
62
+ //
63
+ // Background and observations from time measurements in `thread_pool.h`:
64
+ // - We aim for O(1) storage because there may be hundreds of instances.
65
+ // - The mean is biased upwards by mostly additive noise: particularly
66
+ // interruptions such as context switches, but also contention.
67
+ // - The minimum is not a robust estimator because there are also "lucky
68
+ // shots" (1.2-1.6x lower values) where interruptions or contention happen
69
+ // to be low.
70
+ // - We want to preserve information about contention and a configuration's
71
+ // sensitivity to it. Otherwise, we are optimizing for the best-case, not
72
+ // the common case.
73
+ // - It is still important to minimize the influence of outliers, such as page
74
+ // faults, which can cause multiple times larger measurements.
75
+ // - Detecting outliers based only on the initial variance is too brittle. If
76
+ // the sample is narrow, measurements will fluctuate across runs because
77
+ // too many measurements are considered outliers. This would cause the
78
+ // 'best' configuration to vary.
79
+ //
80
+ // Approach:
81
+ // - Use Winsorization to reduce the impact of outliers, while preserving
82
+ // information on the central tendency.
83
+ // - Continually update the thresholds based on the online variance, with
84
+ // exponential smoothing for stability.
85
+ // - Trim the initial sample via MAD or skewness for a robust estimate of the
86
+ // variance.
87
+ double EstimateCost() {
88
+ if (!IsOnline()) {
89
+ WarmUpOnline();
90
+ HWY_DASSERT(IsOnline());
91
+ }
92
+ return Mean();
93
+ }
94
+
95
+ // Multiplex online state into values_ to allow higher `kMaxValues`.
96
+ // Public for inspection in tests. Do not use directly.
97
+ double& M1() { return values_[0]; } // Moments for variance.
98
+ double& M2() { return values_[1]; }
99
+ double& Mean() { return values_[2]; } // Exponential smoothing.
100
+ double& Stddev() { return values_[3]; }
101
+ double& Lower() { return values_[4]; }
102
+ double& Upper() { return values_[5]; }
103
+
104
+ private:
105
+ static double Median(double* to_sort, size_t n) {
106
+ HWY_DASSERT(n >= 2);
107
+ // F64 is supported everywhere except Armv7.
108
+ #if !HWY_ARCH_ARM_V7
109
+ VQSort(to_sort, n, SortAscending());
110
+ #else
111
+ // Values are known to be finite and non-negative, hence sorting as U64 is
112
+ // equivalent.
113
+ VQSort(reinterpret_cast<uint64_t*>(to_sort), n, SortAscending());
114
+ #endif
115
+ if (n & 1) return to_sort[n / 2];
116
+ // Even length: average of two middle elements.
117
+ return (to_sort[n / 2] + to_sort[n / 2 - 1]) * 0.5;
118
+ }
119
+
120
+ static double MAD(const double* values, size_t n, const double median) {
121
+ double abs_dev[kMaxValues];
122
+ for (size_t i = 0; i < n; ++i) {
123
+ abs_dev[i] = ScalarAbs(values[i] - median);
124
+ }
125
+ return Median(abs_dev, n);
126
+ }
127
+
128
+ // If `num_values_` is large enough, sorts and discards outliers: either via
129
+ // MAD, or if too many values are equal, by trimming according to skewness.
130
+ void RemoveOutliers() {
131
+ if (num_values_ < 3) return; // Not enough to discard two.
132
+ HWY_DASSERT(num_values_ <= kMaxValues);
133
+
134
+ // Given the noise level in `auto_tune_test`, it can happen that 1/4 of the
135
+ // sample is an outlier *in either direction*. Use median absolute
136
+ // deviation, which is robust to almost half of the sample being outliers.
137
+ const double median = Median(values_, num_values_); // sorts in-place.
138
+ const double mad = MAD(values_, num_values_, median);
139
+ // At least half the sample is equal.
140
+ if (mad == 0.0) {
141
+ // Estimate skewness to decide which side to trim more.
142
+ const double skewness =
143
+ (values_[num_values_ - 1] - median) - (median - values_[0]);
144
+
145
+ const size_t trim = HWY_MAX(num_values_ / 2, size_t{2});
146
+ const size_t left =
147
+ HWY_MAX(skewness < 0.0 ? trim * 3 / 4 : trim / 4, size_t{1});
148
+ num_values_ -= trim;
149
+ HWY_DASSERT(num_values_ >= 1);
150
+ memmove(values_, values_ + left, num_values_ * sizeof(values_[0]));
151
+ return;
152
+ }
153
+
154
+ const double upper = median + 5.0 * mad;
155
+ const double lower = median - 5.0 * mad;
156
+ size_t right = num_values_ - 1;
157
+ while (values_[right] > upper) --right;
158
+ // Nonzero MAD implies no more than half are equal, so we did not advance
159
+ // beyond the median.
160
+ HWY_DASSERT(right >= num_values_ / 2);
161
+
162
+ size_t left = 0;
163
+ while (left < right && values_[left] < lower) ++left;
164
+ HWY_DASSERT(left <= num_values_ / 2);
165
+ num_values_ = right - left + 1;
166
+ memmove(values_, values_ + left, num_values_ * sizeof(values_[0]));
167
+ }
168
+
169
+ double SampleMean() const {
170
+ // Only called in non-online phase, but buffer might not be full.
171
+ HWY_DASSERT(!IsOnline() && 0 != num_values_ && num_values_ <= kMaxValues);
172
+ double sum = 0.0;
173
+ for (size_t i = 0; i < num_values_; ++i) {
174
+ sum += values_[i];
175
+ }
176
+ return sum / static_cast<double>(num_values_);
177
+ }
178
+
179
+ // Unbiased estimator for population variance even for small `num_values_`.
180
+ double SampleVariance(double sample_mean) const {
181
+ HWY_DASSERT(sample_mean >= 0.0); // we checked costs are non-negative.
182
+ // Only called in non-online phase, but buffer might not be full.
183
+ HWY_DASSERT(!IsOnline() && 0 != num_values_ && num_values_ <= kMaxValues);
184
+ if (HWY_UNLIKELY(num_values_ == 1)) return 0.0; // prevent divide-by-zero.
185
+ double sum2 = 0.0;
186
+ for (size_t i = 0; i < num_values_; ++i) {
187
+ const double d = values_[i] - sample_mean;
188
+ sum2 += d * d;
189
+ }
190
+ return sum2 / static_cast<double>(num_values_ - 1);
191
+ }
192
+
193
+ bool IsOnline() const { return online_n_ > 0.0; }
194
+
195
+ void OnlineNotify(double x) {
196
+ // Winsorize.
197
+ x = HWY_MIN(HWY_MAX(Lower(), x), Upper());
198
+
199
+ // Welford's online variance estimator.
200
+ // https://media.thinkbrg.com/wp-content/uploads/2020/06/19094655/720_720_McCrary_ImplementingAlgorithms_Whitepaper_20151119_WEB.pdf#page=7.09
201
+ const double n_minus_1 = online_n_;
202
+ online_n_ += 1.0;
203
+ const double d = x - M1();
204
+ const double d_div_n = d / online_n_;
205
+ M1() += d_div_n;
206
+ HWY_DASSERT(M1() >= Lower());
207
+ M2() += d * n_minus_1 * d_div_n; // d^2 * (N-1)/N
208
+ // HWY_MAX avoids divide-by-zero.
209
+ const double stddev = std::sqrt(M2() / HWY_MAX(1.0, n_minus_1));
210
+
211
+ // Exponential smoothing.
212
+ constexpr double kNew = 0.2; // relatively fast update
213
+ constexpr double kOld = 1.0 - kNew;
214
+ Mean() = M1() * kNew + Mean() * kOld;
215
+ Stddev() = stddev * kNew + Stddev() * kOld;
216
+
217
+ // Update thresholds from smoothed mean and stddev to enable recovering from
218
+ // a too narrow initial range due to excessive trimming.
219
+ Lower() = Mean() - 3.5 * Stddev();
220
+ Upper() = Mean() + 3.5 * Stddev();
221
+ }
222
+
223
+ void WarmUpOnline() {
224
+ RemoveOutliers();
225
+
226
+ // Compute and copy before writing to `M1`, which overwrites `values_`!
227
+ const double sample_mean = SampleMean();
228
+ const double sample_variance = SampleVariance(sample_mean);
229
+ double copy[kMaxValues];
230
+ hwy::CopyBytes(values_, copy, num_values_ * sizeof(values_[0]));
231
+
232
+ M1() = M2() = 0.0;
233
+ Mean() = sample_mean;
234
+ Stddev() = std::sqrt(sample_variance);
235
+ // For single-value or all-equal sample, widen the range, else we will only
236
+ // accept the same value.
237
+ if (Stddev() == 0.0) Stddev() = Mean() / 2;
238
+
239
+ // High tolerance because the distribution is not actually Gaussian, and
240
+ // we trimmed up to *half*, and do not want to reject too many values in
241
+ // the online phase.
242
+ Lower() = Mean() - 4.0 * Stddev();
243
+ Upper() = Mean() + 4.0 * Stddev();
244
+ // Feed copied values into online estimator.
245
+ for (size_t i = 0; i < num_values_; ++i) {
246
+ OnlineNotify(copy[i]);
247
+ }
248
+ HWY_DASSERT(IsOnline());
249
+
250
+ #if SIZE_MAX == 0xFFFFFFFFu
251
+ (void)padding_;
252
+ #endif
253
+ }
254
+
255
+ size_t num_values_ = 0; // size of `values_` <= `kMaxValues`
256
+ #if SIZE_MAX == 0xFFFFFFFFu
257
+ uint32_t padding_ = 0;
258
+ #endif
259
+
260
+ double online_n_ = 0.0; // number of calls to `OnlineNotify`.
261
+
262
+ double values_[kMaxValues];
263
+ };
264
+ static_assert(sizeof(CostDistribution) == 128, "");
265
+
266
+ // Implements a counter with wrap-around, plus the ability to skip values.
267
+ // O(1) time, O(N) space via doubly-linked list of indices.
268
+ class NextWithSkip {
269
+ public:
270
+ NextWithSkip() {}
271
+ explicit NextWithSkip(size_t num) {
272
+ links_.reserve(num);
273
+ for (size_t i = 0; i < num; ++i) {
274
+ links_.emplace_back(i, num);
275
+ }
276
+ }
277
+
278
+ size_t Next(size_t pos) {
279
+ HWY_DASSERT(pos < links_.size());
280
+ HWY_DASSERT(!links_[pos].IsRemoved());
281
+ return links_[pos].Next();
282
+ }
283
+
284
+ // Must not be called for an already skipped position. Ignores an attempt to
285
+ // skip the last remaining position.
286
+ void Skip(size_t pos) {
287
+ HWY_DASSERT(!links_[pos].IsRemoved()); // not already skipped.
288
+ const size_t prev = links_[pos].Prev();
289
+ const size_t next = links_[pos].Next();
290
+ if (prev == pos || next == pos) return; // last remaining position.
291
+ links_[next].SetPrev(prev);
292
+ links_[prev].SetNext(next);
293
+ links_[pos].Remove();
294
+ }
295
+
296
+ private:
297
+ // Combine prev/next into one array to improve locality/reduce allocations.
298
+ class Link {
299
+ // Bit-shifts avoid potentially expensive 16-bit loads. Store `next` at the
300
+ // top and `prev` at the bottom for extraction with a single shift/AND.
301
+ // There may be hundreds of configurations, so 8 bits are not enough.
302
+ static constexpr size_t kBits = 14;
303
+ static constexpr size_t kShift = 32 - kBits;
304
+ static constexpr uint32_t kMaxNum = 1u << kBits;
305
+
306
+ public:
307
+ Link(size_t pos, size_t num) {
308
+ HWY_DASSERT(num < kMaxNum);
309
+ const size_t prev = pos == 0 ? num - 1 : pos - 1;
310
+ const size_t next = pos == num - 1 ? 0 : pos + 1;
311
+ bits_ =
312
+ (static_cast<uint32_t>(next) << kShift) | static_cast<uint32_t>(prev);
313
+ HWY_DASSERT(Next() == next && Prev() == prev);
314
+ HWY_DASSERT(!IsRemoved());
315
+ }
316
+
317
+ bool IsRemoved() const { return (bits_ & kMaxNum) != 0; }
318
+ void Remove() { bits_ |= kMaxNum; }
319
+
320
+ size_t Next() const { return bits_ >> kShift; }
321
+ size_t Prev() const { return bits_ & (kMaxNum - 1); }
322
+
323
+ void SetNext(size_t next) {
324
+ HWY_DASSERT(next < kMaxNum);
325
+ bits_ &= (~0u >> kBits); // clear old next
326
+ bits_ |= static_cast<uint32_t>(next) << kShift;
327
+ HWY_DASSERT(Next() == next);
328
+ HWY_DASSERT(!IsRemoved());
329
+ }
330
+ void SetPrev(size_t prev) {
331
+ HWY_DASSERT(prev < kMaxNum);
332
+ bits_ &= ~(kMaxNum - 1); // clear old prev
333
+ bits_ |= static_cast<uint32_t>(prev);
334
+ HWY_DASSERT(Prev() == prev);
335
+ HWY_DASSERT(!IsRemoved());
336
+ }
337
+
338
+ private:
339
+ uint32_t bits_;
340
+ };
341
+ std::vector<Link> links_;
342
+ };
343
+
344
+ // State machine for choosing at runtime the lowest-cost `Config`, which is
345
+ // typically a struct containing multiple parameters. For an introduction, see
346
+ // "Auto-Tuning and Performance Portability on Heterogeneous Hardware".
347
+ //
348
+ // **Which parameters**
349
+ // Note that simple parameters such as the L2 cache size can be directly queried
350
+ // via `hwy/contrib/thread_pool/topology.h`. Difficult to predict parameters
351
+ // such as task granularity are more appropriate for auto-tuning. We also
352
+ // suggest that at least some parameters should also be 'algorithm variants'
353
+ // such as parallel vs. serial, or 2D tiling vs. 1D striping.
354
+ //
355
+ // **Search strategy**
356
+ // To guarantee the optimal result, we use exhaustive search, which is suitable
357
+ // for around 10 parameters and a few hundred combinations of 'candidate'
358
+ // configurations.
359
+ //
360
+ // **How to generate candidates**
361
+ // To keep this framework simple and generic, applications enumerate the search
362
+ // space and pass the list of all feasible candidates to `SetCandidates` before
363
+ // the first call to `NextConfig`. Applications should prune the space as much
364
+ // as possible, e.g. by upper-bounding parameters based on the known cache
365
+ // sizes, and applying constraints such as one being a multiple of another.
366
+ //
367
+ // **Usage**
368
+ // Applications typically conditionally branch to the code implementing the
369
+ // configuration returned by `NextConfig`. They measure the cost of running it
370
+ // and pass that to `NotifyCost`. Branching avoids the complexity and
371
+ // opaqueness of a JIT. The number of branches can be reduced (at the cost of
372
+ // code size) by inlining low-level decisions into larger code regions, e.g. by
373
+ // hoisting them outside hot loops.
374
+ //
375
+ // **What is cost**
376
+ // Cost is an arbitrary `uint64_t`, with lower values being better. Most
377
+ // applications will use the elapsed time. If the tasks being tuned are short,
378
+ // it is important to use a high-resolution timer such as `hwy/timer.h`. Energy
379
+ // may also be useful [https://www.osti.gov/servlets/purl/1361296].
380
+ //
381
+ // **Online vs. offline**
382
+ // Although applications can auto-tune once, offline, it may be difficult to
383
+ // ensure the stored configuration still applies to the current circumstances.
384
+ // Thus we recommend online auto-tuning, re-discovering the configuration on
385
+ // each run. We assume the overhead of bookkeeping and measuring cost is
386
+ // negligible relative to the actual work. The cost of auto-tuning is then that
387
+ // of running sub-optimal configurations. Assuming the best configuration is
388
+ // better than baseline, and the work is performed many thousands of times, the
389
+ // cost is outweighed by the benefits.
390
+ //
391
+ // **kMinSamples**
392
+ // To further reduce overhead, after `kMinSamples` rounds (= measurements of
393
+ // each configuration) we start excluding configurations from further
394
+ // measurements if they are sufficiently worse than the current best.
395
+ // `kMinSamples` can be several dozen when the tasks being tuned take a few
396
+ // microseconds. Even for longer tasks, it should be at least 2 for some noise
397
+ // tolerance. After this, there are another `kMinSamples / 2 + 1` rounds before
398
+ // declaring the winner.
399
+ template <typename Config, size_t kMinSamples = 2>
400
+ class AutoTune {
401
+ public:
402
+ // Returns non-null best configuration if auto-tuning has already finished.
403
+ // Otherwise, callers continue calling `NextConfig` and `NotifyCost`.
404
+ // Points into `Candidates()`.
405
+ const Config* Best() const { return best_; }
406
+
407
+ // If false, caller must call `SetCandidates` before `NextConfig`.
408
+ bool HasCandidates() const {
409
+ HWY_DASSERT(!Best());
410
+ return !candidates_.empty();
411
+ }
412
+ // WARNING: invalidates `Best()`, do not call if that is non-null.
413
+ void SetCandidates(std::vector<Config> candidates) {
414
+ HWY_DASSERT(!Best() && !HasCandidates());
415
+ candidates_.swap(candidates);
416
+ HWY_DASSERT(HasCandidates());
417
+ costs_.resize(candidates_.size());
418
+ list_ = NextWithSkip(candidates_.size());
419
+ }
420
+
421
+ // Typically called after Best() is non-null to compare all candidates' costs.
422
+ Span<const Config> Candidates() const {
423
+ HWY_DASSERT(HasCandidates());
424
+ return Span<const Config>(candidates_.data(), candidates_.size());
425
+ }
426
+ Span<CostDistribution> Costs() {
427
+ return Span<CostDistribution>(costs_.data(), costs_.size());
428
+ }
429
+
430
+ // Returns the current `Config` to measure.
431
+ const Config& NextConfig() const {
432
+ HWY_DASSERT(!Best() && HasCandidates());
433
+ return candidates_[config_idx_];
434
+ }
435
+
436
+ // O(1) except at the end of each round, which is O(N).
437
+ void NotifyCost(uint64_t cost) {
438
+ HWY_DASSERT(!Best() && HasCandidates());
439
+
440
+ costs_[config_idx_].Notify(static_cast<double>(cost));
441
+ // Save now before we update `config_idx_`.
442
+ const size_t my_idx = config_idx_;
443
+ // Only retrieve once we have enough samples, otherwise, we switch to
444
+ // online variance before the buffer is populated.
445
+ const double my_cost = rounds_complete_ >= kMinSamples
446
+ ? costs_[config_idx_].EstimateCost()
447
+ : 0.0;
448
+
449
+ // Advance to next non-skipped config with wrap-around. This decorrelates
450
+ // measurements by not immediately re-measuring the same config.
451
+ config_idx_ = list_.Next(config_idx_);
452
+ // Might still equal `my_idx` if this is the only non-skipped config.
453
+
454
+ // Disqualify from future `NextConfig` if cost was too far beyond the
455
+ // current best. This reduces the number of measurements, while tolerating
456
+ // noise in the first few measurements. Must happen after advancing.
457
+ if (my_cost > skip_if_above_) {
458
+ list_.Skip(my_idx);
459
+ }
460
+
461
+ // Wrap-around indicates the round is complete.
462
+ if (HWY_UNLIKELY(config_idx_ <= my_idx)) {
463
+ ++rounds_complete_;
464
+
465
+ // Enough samples for stable estimates: update the thresholds.
466
+ if (rounds_complete_ >= kMinSamples) {
467
+ double best_cost = HighestValue<double>();
468
+ size_t idx_min = 0;
469
+ for (size_t i = 0; i < candidates_.size(); ++i) {
470
+ const double estimate = costs_[i].EstimateCost();
471
+ if (estimate < best_cost) {
472
+ best_cost = estimate;
473
+ idx_min = i;
474
+ }
475
+ }
476
+ skip_if_above_ = best_cost * 1.25;
477
+
478
+ // After sufficient rounds, declare the winner.
479
+ if (HWY_UNLIKELY(rounds_complete_ == 3 * kMinSamples / 2 + 1)) {
480
+ best_ = &candidates_[idx_min];
481
+ HWY_DASSERT(Best());
482
+ }
483
+ }
484
+ }
485
+ }
486
+
487
+ // Avoid printing during the first few rounds, because those might be noisy
488
+ // and not yet skipped.
489
+ bool ShouldPrint() { return rounds_complete_ > kMinSamples; }
490
+
491
+ private:
492
+ const Config* best_ = nullptr;
493
+ std::vector<Config> candidates_;
494
+ std::vector<CostDistribution> costs_; // one per candidate
495
+ size_t config_idx_ = 0; // [0, candidates_.size())
496
+ NextWithSkip list_;
497
+ size_t rounds_complete_ = 0;
498
+
499
+ double skip_if_above_ = 0.0;
500
+ };
501
+
502
+ } // namespace hwy
503
+
504
+ #endif // HIGHWAY_HWY_AUTO_TUNE_H_