Coverage Report

Created: 2025-11-14 07:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/modular/encoding/enc_ma.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/modular/encoding/enc_ma.h"
7
8
#include <algorithm>
9
#include <cstdint>
10
#include <cstdlib>
11
#include <cstring>
12
#include <limits>
13
#include <numeric>
14
#include <queue>
15
#include <vector>
16
17
#include "lib/jxl/ans_params.h"
18
#include "lib/jxl/base/bits.h"
19
#include "lib/jxl/base/common.h"
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/status.h"
22
#include "lib/jxl/dec_ans.h"
23
#include "lib/jxl/modular/encoding/dec_ma.h"
24
#include "lib/jxl/modular/encoding/ma_common.h"
25
#include "lib/jxl/modular/modular_image.h"
26
27
#undef HWY_TARGET_INCLUDE
28
#define HWY_TARGET_INCLUDE "lib/jxl/modular/encoding/enc_ma.cc"
29
#include <hwy/foreach_target.h>
30
#include <hwy/highway.h>
31
32
#include "lib/jxl/base/fast_math-inl.h"
33
#include "lib/jxl/base/random.h"
34
#include "lib/jxl/enc_ans.h"
35
#include "lib/jxl/modular/encoding/context_predict.h"
36
#include "lib/jxl/modular/options.h"
37
#include "lib/jxl/pack_signed.h"
38
HWY_BEFORE_NAMESPACE();
39
namespace jxl {
40
namespace HWY_NAMESPACE {
41
42
// These templates are not found via ADL.
43
using hwy::HWY_NAMESPACE::Eq;
44
using hwy::HWY_NAMESPACE::IfThenElse;
45
using hwy::HWY_NAMESPACE::Lt;
46
using hwy::HWY_NAMESPACE::Max;
47
48
const HWY_FULL(float) df;
49
const HWY_FULL(int32_t) di;
50
338k
size_t Padded(size_t x) { return RoundUpTo(x, Lanes(df)); }
Unexecuted instantiation: jxl::N_SSE4::Padded(unsigned long)
jxl::N_AVX2::Padded(unsigned long)
Line
Count
Source
50
338k
size_t Padded(size_t x) { return RoundUpTo(x, Lanes(df)); }
Unexecuted instantiation: jxl::N_SSE2::Padded(unsigned long)
51
52
// Compute entropy of the histogram, taking into account the minimum probability
53
// for symbols with non-zero counts.
54
16.7M
float EstimateBits(const int32_t *counts, size_t num_symbols) {
55
16.7M
  int32_t total = std::accumulate(counts, counts + num_symbols, 0);
56
16.7M
  const auto zero = Zero(df);
57
16.7M
  const auto minprob = Set(df, 1.0f / ANS_TAB_SIZE);
58
16.7M
  const auto inv_total = Set(df, 1.0f / total);
59
16.7M
  auto bits_lanes = Zero(df);
60
16.7M
  auto total_v = Set(di, total);
61
116M
  for (size_t i = 0; i < num_symbols; i += Lanes(df)) {
62
99.9M
    const auto counts_iv = LoadU(di, &counts[i]);
63
99.9M
    const auto counts_fv = ConvertTo(df, counts_iv);
64
99.9M
    const auto probs = Mul(counts_fv, inv_total);
65
99.9M
    const auto mprobs = Max(probs, minprob);
66
99.9M
    const auto nbps = IfThenElse(Eq(counts_iv, total_v), BitCast(di, zero),
67
99.9M
                                 BitCast(di, FastLog2f(df, mprobs)));
68
99.9M
    bits_lanes = Sub(bits_lanes, Mul(counts_fv, BitCast(df, nbps)));
69
99.9M
  }
70
16.7M
  return GetLane(SumOfLanes(df, bits_lanes));
71
16.7M
}
Unexecuted instantiation: jxl::N_SSE4::EstimateBits(int const*, unsigned long)
jxl::N_AVX2::EstimateBits(int const*, unsigned long)
Line
Count
Source
54
16.7M
float EstimateBits(const int32_t *counts, size_t num_symbols) {
55
16.7M
  int32_t total = std::accumulate(counts, counts + num_symbols, 0);
56
16.7M
  const auto zero = Zero(df);
57
16.7M
  const auto minprob = Set(df, 1.0f / ANS_TAB_SIZE);
58
16.7M
  const auto inv_total = Set(df, 1.0f / total);
59
16.7M
  auto bits_lanes = Zero(df);
60
16.7M
  auto total_v = Set(di, total);
61
116M
  for (size_t i = 0; i < num_symbols; i += Lanes(df)) {
62
99.9M
    const auto counts_iv = LoadU(di, &counts[i]);
63
99.9M
    const auto counts_fv = ConvertTo(df, counts_iv);
64
99.9M
    const auto probs = Mul(counts_fv, inv_total);
65
99.9M
    const auto mprobs = Max(probs, minprob);
66
99.9M
    const auto nbps = IfThenElse(Eq(counts_iv, total_v), BitCast(di, zero),
67
99.9M
                                 BitCast(di, FastLog2f(df, mprobs)));
68
99.9M
    bits_lanes = Sub(bits_lanes, Mul(counts_fv, BitCast(df, nbps)));
69
99.9M
  }
70
16.7M
  return GetLane(SumOfLanes(df, bits_lanes));
71
16.7M
}
Unexecuted instantiation: jxl::N_SSE2::EstimateBits(int const*, unsigned long)
72
73
void MakeSplitNode(size_t pos, int property, int splitval, Predictor lpred,
74
168k
                   int64_t loff, Predictor rpred, int64_t roff, Tree *tree) {
75
  // Note that the tree splits on *strictly greater*.
76
168k
  (*tree)[pos].lchild = tree->size();
77
168k
  (*tree)[pos].rchild = tree->size() + 1;
78
168k
  (*tree)[pos].splitval = splitval;
79
168k
  (*tree)[pos].property = property;
80
168k
  tree->emplace_back();
81
168k
  tree->back().property = -1;
82
168k
  tree->back().predictor = rpred;
83
168k
  tree->back().predictor_offset = roff;
84
168k
  tree->back().multiplier = 1;
85
168k
  tree->emplace_back();
86
168k
  tree->back().property = -1;
87
168k
  tree->back().predictor = lpred;
88
168k
  tree->back().predictor_offset = loff;
89
168k
  tree->back().multiplier = 1;
90
168k
}
Unexecuted instantiation: jxl::N_SSE4::MakeSplitNode(unsigned long, int, int, jxl::Predictor, long, jxl::Predictor, long, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
jxl::N_AVX2::MakeSplitNode(unsigned long, int, int, jxl::Predictor, long, jxl::Predictor, long, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
Line
Count
Source
74
168k
                   int64_t loff, Predictor rpred, int64_t roff, Tree *tree) {
75
  // Note that the tree splits on *strictly greater*.
76
168k
  (*tree)[pos].lchild = tree->size();
77
168k
  (*tree)[pos].rchild = tree->size() + 1;
78
168k
  (*tree)[pos].splitval = splitval;
79
168k
  (*tree)[pos].property = property;
80
168k
  tree->emplace_back();
81
168k
  tree->back().property = -1;
82
168k
  tree->back().predictor = rpred;
83
168k
  tree->back().predictor_offset = roff;
84
168k
  tree->back().multiplier = 1;
85
168k
  tree->emplace_back();
86
168k
  tree->back().property = -1;
87
168k
  tree->back().predictor = lpred;
88
168k
  tree->back().predictor_offset = loff;
89
168k
  tree->back().multiplier = 1;
90
168k
}
Unexecuted instantiation: jxl::N_SSE2::MakeSplitNode(unsigned long, int, int, jxl::Predictor, long, jxl::Predictor, long, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
91
92
enum class IntersectionType { kNone, kPartial, kInside };
93
IntersectionType BoxIntersects(StaticPropRange needle, StaticPropRange haystack,
94
102k
                               uint32_t &partial_axis, uint32_t &partial_val) {
95
102k
  bool partial = false;
96
308k
  for (size_t i = 0; i < kNumStaticProperties; i++) {
97
205k
    if (haystack[i][0] >= needle[i][1]) {
98
0
      return IntersectionType::kNone;
99
0
    }
100
205k
    if (haystack[i][1] <= needle[i][0]) {
101
0
      return IntersectionType::kNone;
102
0
    }
103
205k
    if (haystack[i][0] <= needle[i][0] && haystack[i][1] >= needle[i][1]) {
104
205k
      continue;
105
205k
    }
106
0
    partial = true;
107
0
    partial_axis = i;
108
0
    if (haystack[i][0] > needle[i][0] && haystack[i][0] < needle[i][1]) {
109
0
      partial_val = haystack[i][0] - 1;
110
0
    } else {
111
0
      JXL_DASSERT(haystack[i][1] > needle[i][0] &&
112
0
                  haystack[i][1] < needle[i][1]);
113
0
      partial_val = haystack[i][1] - 1;
114
0
    }
115
0
  }
116
102k
  return partial ? IntersectionType::kPartial : IntersectionType::kInside;
117
102k
}
Unexecuted instantiation: jxl::N_SSE4::BoxIntersects(std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, unsigned int&, unsigned int&)
jxl::N_AVX2::BoxIntersects(std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, unsigned int&, unsigned int&)
Line
Count
Source
94
102k
                               uint32_t &partial_axis, uint32_t &partial_val) {
95
102k
  bool partial = false;
96
308k
  for (size_t i = 0; i < kNumStaticProperties; i++) {
97
205k
    if (haystack[i][0] >= needle[i][1]) {
98
0
      return IntersectionType::kNone;
99
0
    }
100
205k
    if (haystack[i][1] <= needle[i][0]) {
101
0
      return IntersectionType::kNone;
102
0
    }
103
205k
    if (haystack[i][0] <= needle[i][0] && haystack[i][1] >= needle[i][1]) {
104
205k
      continue;
105
205k
    }
106
0
    partial = true;
107
0
    partial_axis = i;
108
0
    if (haystack[i][0] > needle[i][0] && haystack[i][0] < needle[i][1]) {
109
0
      partial_val = haystack[i][0] - 1;
110
0
    } else {
111
0
      JXL_DASSERT(haystack[i][1] > needle[i][0] &&
112
0
                  haystack[i][1] < needle[i][1]);
113
0
      partial_val = haystack[i][1] - 1;
114
0
    }
115
0
  }
116
102k
  return partial ? IntersectionType::kPartial : IntersectionType::kInside;
117
102k
}
Unexecuted instantiation: jxl::N_SSE2::BoxIntersects(std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, unsigned int&, unsigned int&)
118
119
template<bool S>
120
void SplitTreeSamples(TreeSamples &tree_samples, size_t begin, size_t pos,
121
168k
                      size_t end, size_t prop, uint32_t val) {
122
168k
  size_t begin_pos = begin;
123
168k
  size_t end_pos = pos;
124
8.27M
  do {
125
20.8M
    while (begin_pos < pos &&
126
20.7M
           tree_samples.Property<S>(prop, begin_pos) <= val) {
127
12.5M
      ++begin_pos;
128
12.5M
    }
129
21.9M
    while (end_pos < end && tree_samples.Property<S>(prop, end_pos) > val) {
130
13.6M
      ++end_pos;
131
13.6M
    }
132
8.27M
    if (begin_pos < pos && end_pos < end) {
133
8.23M
      tree_samples.Swap(begin_pos, end_pos);
134
8.23M
    }
135
8.27M
    ++begin_pos;
136
8.27M
    ++end_pos;
137
8.27M
  } while (begin_pos < pos && end_pos < end);
138
168k
}
Unexecuted instantiation: void jxl::N_SSE4::SplitTreeSamples<true>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Unexecuted instantiation: void jxl::N_SSE4::SplitTreeSamples<false>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
void jxl::N_AVX2::SplitTreeSamples<true>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Line
Count
Source
121
4.21k
                      size_t end, size_t prop, uint32_t val) {
122
4.21k
  size_t begin_pos = begin;
123
4.21k
  size_t end_pos = pos;
124
507k
  do {
125
2.85M
    while (begin_pos < pos &&
126
2.85M
           tree_samples.Property<S>(prop, begin_pos) <= val) {
127
2.34M
      ++begin_pos;
128
2.34M
    }
129
1.83M
    while (end_pos < end && tree_samples.Property<S>(prop, end_pos) > val) {
130
1.32M
      ++end_pos;
131
1.32M
    }
132
507k
    if (begin_pos < pos && end_pos < end) {
133
505k
      tree_samples.Swap(begin_pos, end_pos);
134
505k
    }
135
507k
    ++begin_pos;
136
507k
    ++end_pos;
137
507k
  } while (begin_pos < pos && end_pos < end);
138
4.21k
}
void jxl::N_AVX2::SplitTreeSamples<false>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Line
Count
Source
121
163k
                      size_t end, size_t prop, uint32_t val) {
122
163k
  size_t begin_pos = begin;
123
163k
  size_t end_pos = pos;
124
7.76M
  do {
125
17.9M
    while (begin_pos < pos &&
126
17.9M
           tree_samples.Property<S>(prop, begin_pos) <= val) {
127
10.2M
      ++begin_pos;
128
10.2M
    }
129
20.0M
    while (end_pos < end && tree_samples.Property<S>(prop, end_pos) > val) {
130
12.3M
      ++end_pos;
131
12.3M
    }
132
7.76M
    if (begin_pos < pos && end_pos < end) {
133
7.72M
      tree_samples.Swap(begin_pos, end_pos);
134
7.72M
    }
135
7.76M
    ++begin_pos;
136
7.76M
    ++end_pos;
137
7.76M
  } while (begin_pos < pos && end_pos < end);
138
163k
}
Unexecuted instantiation: void jxl::N_SSE2::SplitTreeSamples<true>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
Unexecuted instantiation: void jxl::N_SSE2::SplitTreeSamples<false>(jxl::TreeSamples&, unsigned long, unsigned long, unsigned long, unsigned long, unsigned int)
139
140
template <bool S>
141
void CollectExtraBitsIncrease(TreeSamples &tree_samples,
142
                              const std::vector<ResidualToken> &rtokens,
143
                              std::vector<int> &count_increase,
144
                              std::vector<size_t> &extra_bits_increase,
145
                              size_t begin, size_t end, size_t prop_idx,
146
2.19M
                              size_t max_symbols) {
147
339M
  for (size_t i2 = begin; i2 < end; i2++) {
148
337M
    const ResidualToken &rt = rtokens[i2];
149
337M
    size_t cnt = tree_samples.Count(i2);
150
337M
    size_t p = tree_samples.Property<S>(prop_idx, i2);
151
337M
    size_t sym = rt.tok;
152
337M
    size_t ebi = rt.nbits * cnt;
153
337M
    count_increase[p * max_symbols + sym] += cnt;
154
337M
    extra_bits_increase[p] += ebi;
155
337M
  }
156
2.19M
}
Unexecuted instantiation: void jxl::N_SSE4::CollectExtraBitsIncrease<true>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Unexecuted instantiation: void jxl::N_SSE4::CollectExtraBitsIncrease<false>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
void jxl::N_AVX2::CollectExtraBitsIncrease<true>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Line
Count
Source
146
415k
                              size_t max_symbols) {
147
72.4M
  for (size_t i2 = begin; i2 < end; i2++) {
148
72.0M
    const ResidualToken &rt = rtokens[i2];
149
72.0M
    size_t cnt = tree_samples.Count(i2);
150
72.0M
    size_t p = tree_samples.Property<S>(prop_idx, i2);
151
72.0M
    size_t sym = rt.tok;
152
72.0M
    size_t ebi = rt.nbits * cnt;
153
72.0M
    count_increase[p * max_symbols + sym] += cnt;
154
72.0M
    extra_bits_increase[p] += ebi;
155
72.0M
  }
156
415k
}
void jxl::N_AVX2::CollectExtraBitsIncrease<false>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Line
Count
Source
146
1.77M
                              size_t max_symbols) {
147
267M
  for (size_t i2 = begin; i2 < end; i2++) {
148
265M
    const ResidualToken &rt = rtokens[i2];
149
265M
    size_t cnt = tree_samples.Count(i2);
150
265M
    size_t p = tree_samples.Property<S>(prop_idx, i2);
151
265M
    size_t sym = rt.tok;
152
265M
    size_t ebi = rt.nbits * cnt;
153
265M
    count_increase[p * max_symbols + sym] += cnt;
154
265M
    extra_bits_increase[p] += ebi;
155
265M
  }
156
1.77M
}
Unexecuted instantiation: void jxl::N_SSE2::CollectExtraBitsIncrease<true>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
Unexecuted instantiation: void jxl::N_SSE2::CollectExtraBitsIncrease<false>(jxl::TreeSamples&, std::__1::vector<jxl::ResidualToken, std::__1::allocator<jxl::ResidualToken> > const&, std::__1::vector<int, std::__1::allocator<int> >&, std::__1::vector<unsigned long, std::__1::allocator<unsigned long> >&, unsigned long, unsigned long, unsigned long, unsigned long)
157
158
void FindBestSplit(TreeSamples &tree_samples, float threshold,
159
                   const std::vector<ModularMultiplierInfo> &mul_info,
160
                   StaticPropRange initial_static_prop_range,
161
2.22k
                   float fast_decode_multiplier, Tree *tree) {
162
2.22k
  struct NodeInfo {
163
2.22k
    size_t pos;
164
2.22k
    size_t begin;
165
2.22k
    size_t end;
166
2.22k
    uint64_t used_properties;
167
2.22k
    StaticPropRange static_prop_range;
168
2.22k
  };
169
2.22k
  std::vector<NodeInfo> nodes;
170
2.22k
  nodes.push_back(NodeInfo{0, 0, tree_samples.NumDistinctSamples(), 0,
171
2.22k
                           initial_static_prop_range});
172
173
2.22k
  size_t num_predictors = tree_samples.NumPredictors();
174
2.22k
  size_t num_properties = tree_samples.NumProperties();
175
176
  // TODO(veluca): consider parallelizing the search (processing multiple nodes
177
  // at a time).
178
340k
  while (!nodes.empty()) {
179
338k
    size_t pos = nodes.back().pos;
180
338k
    size_t begin = nodes.back().begin;
181
338k
    size_t end = nodes.back().end;
182
338k
    uint64_t used_properties = nodes.back().used_properties;
183
338k
    StaticPropRange static_prop_range = nodes.back().static_prop_range;
184
338k
    nodes.pop_back();
185
338k
    if (begin == end) continue;
186
187
338k
    struct SplitInfo {
188
338k
      size_t prop = 0;
189
338k
      uint32_t val = 0;
190
338k
      size_t pos = 0;
191
338k
      float lcost = std::numeric_limits<float>::max();
192
338k
      float rcost = std::numeric_limits<float>::max();
193
338k
      Predictor lpred = Predictor::Zero;
194
338k
      Predictor rpred = Predictor::Zero;
195
9.89M
      float Cost() const { return lcost + rcost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE4::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::SplitInfo::Cost() const
enc_ma.cc:jxl::N_AVX2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::SplitInfo::Cost() const
Line
Count
Source
195
9.89M
      float Cost() const { return lcost + rcost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::SplitInfo::Cost() const
196
338k
    };
197
198
338k
    SplitInfo best_split_static_constant;
199
338k
    SplitInfo best_split_static;
200
338k
    SplitInfo best_split_nonstatic;
201
338k
    SplitInfo best_split_nowp;
202
203
338k
    JXL_DASSERT(begin <= end);
204
338k
    JXL_DASSERT(end <= tree_samples.NumDistinctSamples());
205
206
    // Compute the maximum token in the range.
207
338k
    size_t max_symbols = 0;
208
676k
    for (size_t pred = 0; pred < num_predictors; pred++) {
209
48.7M
      for (size_t i = begin; i < end; i++) {
210
48.4M
        uint32_t tok = tree_samples.Token(pred, i);
211
48.4M
        max_symbols = max_symbols > tok + 1 ? max_symbols : tok + 1;
212
48.4M
      }
213
338k
    }
214
338k
    max_symbols = Padded(max_symbols);
215
338k
    std::vector<int32_t> counts(max_symbols * num_predictors);
216
338k
    std::vector<uint32_t> tot_extra_bits(num_predictors);
217
676k
    for (size_t pred = 0; pred < num_predictors; pred++) {
218
338k
      size_t extra_bits = 0;
219
338k
      const std::vector<ResidualToken>& rtokens = tree_samples.RTokens(pred);
220
48.7M
      for (size_t i = begin; i < end; i++) {
221
48.4M
        const ResidualToken& rt = rtokens[i];
222
48.4M
        size_t count = tree_samples.Count(i);
223
48.4M
        size_t eb = rt.nbits * count;
224
48.4M
        counts[pred * max_symbols + rt.tok] += count;
225
48.4M
        extra_bits += eb;
226
48.4M
      }
227
338k
      tot_extra_bits[pred] = extra_bits;
228
338k
    }
229
230
338k
    float base_bits;
231
338k
    {
232
338k
      size_t pred = tree_samples.PredictorIndex((*tree)[pos].predictor);
233
338k
      base_bits =
234
338k
          EstimateBits(counts.data() + pred * max_symbols, max_symbols) +
235
338k
          tot_extra_bits[pred];
236
338k
    }
237
238
338k
    SplitInfo *best = &best_split_nonstatic;
239
240
338k
    SplitInfo forced_split;
241
    // The multiplier ranges cut halfway through the current ranges of static
242
    // properties. We do this even if the current node is not a leaf, to
243
    // minimize the number of nodes in the resulting tree.
244
338k
    for (const auto &mmi : mul_info) {
245
102k
      uint32_t axis;
246
102k
      uint32_t val;
247
102k
      IntersectionType t =
248
102k
          BoxIntersects(static_prop_range, mmi.range, axis, val);
249
102k
      if (t == IntersectionType::kNone) continue;
250
102k
      if (t == IntersectionType::kInside) {
251
102k
        (*tree)[pos].multiplier = mmi.multiplier;
252
102k
        break;
253
102k
      }
254
0
      if (t == IntersectionType::kPartial) {
255
0
        JXL_DASSERT(axis < kNumStaticProperties);
256
0
        forced_split.val = tree_samples.QuantizeStaticProperty(axis, val);
257
0
        forced_split.prop = axis;
258
0
        forced_split.lcost = forced_split.rcost = base_bits / 2 - threshold;
259
0
        forced_split.lpred = forced_split.rpred = (*tree)[pos].predictor;
260
0
        best = &forced_split;
261
0
        best->pos = begin;
262
0
        JXL_DASSERT(best->prop == tree_samples.PropertyFromIndex(best->prop));
263
0
        if (best->prop < tree_samples.NumStaticProps()) {
264
0
        for (size_t x = begin; x < end; x++) {
265
0
          if (tree_samples.Property<true>(best->prop, x) <= best->val) {
266
0
            best->pos++;
267
0
          }
268
0
        }
269
0
      } else {
270
0
        size_t prop = best->prop - tree_samples.NumStaticProps();
271
0
        for (size_t x = begin; x < end; x++) {
272
0
          if (tree_samples.Property<false>(prop, x) <= best->val) {
273
0
            best->pos++;
274
0
          }
275
0
        }
276
0
      }
277
0
        break;
278
0
      }
279
0
    }
280
281
338k
    if (best != &forced_split) {
282
338k
      std::vector<int> prop_value_used_count;
283
338k
      std::vector<int> count_increase;
284
338k
      std::vector<size_t> extra_bits_increase;
285
      // For each property, compute which of its values are used, and what
286
      // tokens correspond to those usages. Then, iterate through the values,
287
      // and compute the entropy of each side of the split (of the form `prop >
288
      // threshold`). Finally, find the split that minimizes the cost.
289
338k
      struct CostInfo {
290
338k
        float cost = std::numeric_limits<float>::max();
291
338k
        float extra_cost = 0;
292
16.3M
        float Cost() const { return cost + extra_cost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE4::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::CostInfo::Cost() const
enc_ma.cc:jxl::N_AVX2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::CostInfo::Cost() const
Line
Count
Source
292
16.3M
        float Cost() const { return cost + extra_cost; }
Unexecuted instantiation: enc_ma.cc:jxl::N_SSE2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)::CostInfo::Cost() const
293
338k
        Predictor pred;  // will be uninitialized in some cases, but never used.
294
338k
      };
295
338k
      std::vector<CostInfo> costs_l;
296
338k
      std::vector<CostInfo> costs_r;
297
298
338k
      std::vector<int32_t> counts_above(max_symbols);
299
338k
      std::vector<int32_t> counts_below(max_symbols);
300
301
      // The lower the threshold, the higher the expected noisiness of the
302
      // estimate. Thus, discourage changing predictors.
303
338k
      float change_pred_penalty = 800.0f / (100.0f + threshold);
304
2.53M
      for (size_t prop = 0; prop < num_properties && base_bits > threshold;
305
2.19M
           prop++) {
306
2.19M
        costs_l.clear();
307
2.19M
        costs_r.clear();
308
2.19M
        size_t prop_size = tree_samples.NumPropertyValues(prop);
309
2.19M
        if (extra_bits_increase.size() < prop_size) {
310
786k
          count_increase.resize(prop_size * max_symbols);
311
786k
          extra_bits_increase.resize(prop_size);
312
786k
        }
313
        // Clear prop_value_used_count (which cannot be cleared "on the go")
314
2.19M
        prop_value_used_count.clear();
315
2.19M
        prop_value_used_count.resize(prop_size);
316
317
2.19M
        size_t first_used = prop_size;
318
2.19M
        size_t last_used = 0;
319
320
        // TODO(veluca): consider finding multiple splits along a single
321
        // property at the same time, possibly with a bottom-up approach.
322
2.19M
        if (prop < tree_samples.NumStaticProps()) {
323
72.4M
          for (size_t i = begin; i < end; i++) {
324
72.0M
            size_t p = tree_samples.Property<true>(prop, i);
325
72.0M
            prop_value_used_count[p]++;
326
72.0M
            last_used = std::max(last_used, p);
327
72.0M
            first_used = std::min(first_used, p);
328
72.0M
          }
329
1.77M
        } else {
330
1.77M
          size_t prop_idx = prop - tree_samples.NumStaticProps();
331
267M
          for (size_t i = begin; i < end; i++) {
332
265M
            size_t p = tree_samples.Property<false>(prop_idx, i);
333
265M
            prop_value_used_count[p]++;
334
265M
            last_used = std::max(last_used, p);
335
265M
            first_used = std::min(first_used, p);
336
265M
          }
337
1.77M
        }
338
2.19M
        costs_l.resize(last_used - first_used);
339
2.19M
        costs_r.resize(last_used - first_used);
340
        // For all predictors, compute the right and left costs of each split.
341
4.38M
        for (size_t pred = 0; pred < num_predictors; pred++) {
342
          // Compute cost and histogram increments for each property value.
343
2.19M
          const std::vector<ResidualToken> &rtokens =
344
2.19M
              tree_samples.RTokens(pred);
345
2.19M
          if (prop < tree_samples.NumStaticProps()) {
346
415k
            CollectExtraBitsIncrease<true>(tree_samples, rtokens,
347
415k
                                           count_increase, extra_bits_increase,
348
415k
                                           begin, end, prop, max_symbols);
349
1.77M
          } else {
350
1.77M
            CollectExtraBitsIncrease<false>(
351
1.77M
                tree_samples, rtokens, count_increase, extra_bits_increase,
352
1.77M
                begin, end, prop - tree_samples.NumStaticProps(), max_symbols);
353
1.77M
          }
354
2.19M
          memcpy(counts_above.data(), counts.data() + pred * max_symbols,
355
2.19M
                 max_symbols * sizeof counts_above[0]);
356
2.19M
          memset(counts_below.data(), 0, max_symbols * sizeof counts_below[0]);
357
2.19M
          size_t extra_bits_below = 0;
358
          // Exclude last used: this ensures neither counts_above nor
359
          // counts_below is empty.
360
17.5M
          for (size_t i = first_used; i < last_used; i++) {
361
15.3M
            if (!prop_value_used_count[i]) continue;
362
8.19M
            extra_bits_below += extra_bits_increase[i];
363
            // The increase for this property value has been used, and will not
364
            // be used again: clear it. Also below.
365
8.19M
            extra_bits_increase[i] = 0;
366
400M
            for (size_t sym = 0; sym < max_symbols; sym++) {
367
392M
              counts_above[sym] -= count_increase[i * max_symbols + sym];
368
392M
              counts_below[sym] += count_increase[i * max_symbols + sym];
369
392M
              count_increase[i * max_symbols + sym] = 0;
370
392M
            }
371
8.19M
            float rcost = EstimateBits(counts_above.data(), max_symbols) +
372
8.19M
                          tot_extra_bits[pred] - extra_bits_below;
373
8.19M
            float lcost = EstimateBits(counts_below.data(), max_symbols) +
374
8.19M
                          extra_bits_below;
375
8.19M
            JXL_DASSERT(extra_bits_below <= tot_extra_bits[pred]);
376
8.19M
            float penalty = 0;
377
            // Never discourage moving away from the Weighted predictor.
378
8.19M
            if (tree_samples.PredictorFromIndex(pred) !=
379
8.19M
                    (*tree)[pos].predictor &&
380
0
                (*tree)[pos].predictor != Predictor::Weighted) {
381
0
              penalty = change_pred_penalty;
382
0
            }
383
            // If everything else is equal, disfavour Weighted (slower) and
384
            // favour Zero (faster if it's the only predictor used in a
385
            // group+channel combination)
386
8.19M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Weighted) {
387
0
              penalty += 1e-8;
388
0
            }
389
8.19M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Zero) {
390
0
              penalty -= 1e-8;
391
0
            }
392
8.19M
            if (rcost + penalty < costs_r[i - first_used].Cost()) {
393
8.19M
              costs_r[i - first_used].cost = rcost;
394
8.19M
              costs_r[i - first_used].extra_cost = penalty;
395
8.19M
              costs_r[i - first_used].pred =
396
8.19M
                  tree_samples.PredictorFromIndex(pred);
397
8.19M
            }
398
8.19M
            if (lcost + penalty < costs_l[i - first_used].Cost()) {
399
8.19M
              costs_l[i - first_used].cost = lcost;
400
8.19M
              costs_l[i - first_used].extra_cost = penalty;
401
8.19M
              costs_l[i - first_used].pred =
402
8.19M
                  tree_samples.PredictorFromIndex(pred);
403
8.19M
            }
404
8.19M
          }
405
2.19M
        }
406
        // Iterate through the possible splits and find the one with minimum sum
407
        // of costs of the two sides.
408
2.19M
        size_t split = begin;
409
17.5M
        for (size_t i = first_used; i < last_used; i++) {
410
15.3M
          if (!prop_value_used_count[i]) continue;
411
8.19M
          split += prop_value_used_count[i];
412
8.19M
          float rcost = costs_r[i - first_used].cost;
413
8.19M
          float lcost = costs_l[i - first_used].cost;
414
          // WP was not used + we would use the WP property or predictor
415
8.19M
          bool adds_wp =
416
8.19M
              (tree_samples.PropertyFromIndex(prop) == kWPProp &&
417
1.58M
               (used_properties & (1LU << prop)) == 0) ||
418
6.80M
              ((costs_l[i - first_used].pred == Predictor::Weighted ||
419
6.80M
                costs_r[i - first_used].pred == Predictor::Weighted) &&
420
0
               (*tree)[pos].predictor != Predictor::Weighted);
421
8.19M
          bool zero_entropy_side = rcost == 0 || lcost == 0;
422
423
8.19M
          SplitInfo &best_ref =
424
8.19M
              tree_samples.PropertyFromIndex(prop) < kNumStaticProperties
425
8.19M
                  ? (zero_entropy_side ? best_split_static_constant
426
27.0k
                                       : best_split_static)
427
8.19M
                  : (adds_wp ? best_split_nonstatic : best_split_nowp);
428
8.19M
          if (lcost + rcost < best_ref.Cost()) {
429
1.78M
            best_ref.prop = prop;
430
1.78M
            best_ref.val = i;
431
1.78M
            best_ref.pos = split;
432
1.78M
            best_ref.lcost = lcost;
433
1.78M
            best_ref.lpred = costs_l[i - first_used].pred;
434
1.78M
            best_ref.rcost = rcost;
435
1.78M
            best_ref.rpred = costs_r[i - first_used].pred;
436
1.78M
          }
437
8.19M
        }
438
        // Clear extra_bits_increase and cost_increase for last_used.
439
2.19M
        extra_bits_increase[last_used] = 0;
440
109M
        for (size_t sym = 0; sym < max_symbols; sym++) {
441
107M
          count_increase[last_used * max_symbols + sym] = 0;
442
107M
        }
443
2.19M
      }
444
445
      // Try to avoid introducing WP.
446
338k
      if (best_split_nowp.Cost() + threshold < base_bits &&
447
164k
          best_split_nowp.Cost() <= fast_decode_multiplier * best->Cost()) {
448
159k
        best = &best_split_nowp;
449
159k
      }
450
      // Split along static props if possible and not significantly more
451
      // expensive.
452
338k
      if (best_split_static.Cost() + threshold < base_bits &&
453
9.50k
          best_split_static.Cost() <= fast_decode_multiplier * best->Cost()) {
454
3.93k
        best = &best_split_static;
455
3.93k
      }
456
      // Split along static props to create constant nodes if possible.
457
338k
      if (best_split_static_constant.Cost() + threshold < base_bits) {
458
433
        best = &best_split_static_constant;
459
433
      }
460
338k
    }
461
462
338k
    if (best->Cost() + threshold < base_bits) {
463
168k
      uint32_t p = tree_samples.PropertyFromIndex(best->prop);
464
168k
      pixel_type dequant =
465
168k
          tree_samples.UnquantizeProperty(best->prop, best->val);
466
      // Split node and try to split children.
467
168k
      MakeSplitNode(pos, p, dequant, best->lpred, 0, best->rpred, 0, tree);
468
      // "Sort" according to winning property
469
168k
      if (best->prop < tree_samples.NumStaticProps()) {
470
4.21k
        SplitTreeSamples<true>(tree_samples, begin, best->pos, end, best->prop,
471
4.21k
                               best->val);
472
163k
      } else {
473
163k
        SplitTreeSamples<false>(tree_samples, begin, best->pos, end,
474
163k
                                best->prop - tree_samples.NumStaticProps(),
475
163k
                                best->val);
476
163k
      }
477
168k
      if (p >= kNumStaticProperties) {
478
163k
        used_properties |= 1 << best->prop;
479
163k
      }
480
168k
      auto new_sp_range = static_prop_range;
481
168k
      if (p < kNumStaticProperties) {
482
4.21k
        JXL_DASSERT(static_cast<uint32_t>(dequant + 1) <= new_sp_range[p][1]);
483
4.21k
        new_sp_range[p][1] = dequant + 1;
484
4.21k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
485
4.21k
      }
486
168k
      nodes.push_back(NodeInfo{(*tree)[pos].rchild, begin, best->pos,
487
168k
                               used_properties, new_sp_range});
488
168k
      new_sp_range = static_prop_range;
489
168k
      if (p < kNumStaticProperties) {
490
4.21k
        JXL_DASSERT(new_sp_range[p][0] <= static_cast<uint32_t>(dequant + 1));
491
4.21k
        new_sp_range[p][0] = dequant + 1;
492
4.21k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
493
4.21k
      }
494
168k
      nodes.push_back(NodeInfo{(*tree)[pos].lchild, best->pos, end,
495
168k
                               used_properties, new_sp_range});
496
168k
    }
497
338k
  }
498
2.22k
}
Unexecuted instantiation: jxl::N_SSE4::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
jxl::N_AVX2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
Line
Count
Source
161
2.22k
                   float fast_decode_multiplier, Tree *tree) {
162
2.22k
  struct NodeInfo {
163
2.22k
    size_t pos;
164
2.22k
    size_t begin;
165
2.22k
    size_t end;
166
2.22k
    uint64_t used_properties;
167
2.22k
    StaticPropRange static_prop_range;
168
2.22k
  };
169
2.22k
  std::vector<NodeInfo> nodes;
170
2.22k
  nodes.push_back(NodeInfo{0, 0, tree_samples.NumDistinctSamples(), 0,
171
2.22k
                           initial_static_prop_range});
172
173
2.22k
  size_t num_predictors = tree_samples.NumPredictors();
174
2.22k
  size_t num_properties = tree_samples.NumProperties();
175
176
  // TODO(veluca): consider parallelizing the search (processing multiple nodes
177
  // at a time).
178
340k
  while (!nodes.empty()) {
179
338k
    size_t pos = nodes.back().pos;
180
338k
    size_t begin = nodes.back().begin;
181
338k
    size_t end = nodes.back().end;
182
338k
    uint64_t used_properties = nodes.back().used_properties;
183
338k
    StaticPropRange static_prop_range = nodes.back().static_prop_range;
184
338k
    nodes.pop_back();
185
338k
    if (begin == end) continue;
186
187
338k
    struct SplitInfo {
188
338k
      size_t prop = 0;
189
338k
      uint32_t val = 0;
190
338k
      size_t pos = 0;
191
338k
      float lcost = std::numeric_limits<float>::max();
192
338k
      float rcost = std::numeric_limits<float>::max();
193
338k
      Predictor lpred = Predictor::Zero;
194
338k
      Predictor rpred = Predictor::Zero;
195
338k
      float Cost() const { return lcost + rcost; }
196
338k
    };
197
198
338k
    SplitInfo best_split_static_constant;
199
338k
    SplitInfo best_split_static;
200
338k
    SplitInfo best_split_nonstatic;
201
338k
    SplitInfo best_split_nowp;
202
203
338k
    JXL_DASSERT(begin <= end);
204
338k
    JXL_DASSERT(end <= tree_samples.NumDistinctSamples());
205
206
    // Compute the maximum token in the range.
207
338k
    size_t max_symbols = 0;
208
676k
    for (size_t pred = 0; pred < num_predictors; pred++) {
209
48.7M
      for (size_t i = begin; i < end; i++) {
210
48.4M
        uint32_t tok = tree_samples.Token(pred, i);
211
48.4M
        max_symbols = max_symbols > tok + 1 ? max_symbols : tok + 1;
212
48.4M
      }
213
338k
    }
214
338k
    max_symbols = Padded(max_symbols);
215
338k
    std::vector<int32_t> counts(max_symbols * num_predictors);
216
338k
    std::vector<uint32_t> tot_extra_bits(num_predictors);
217
676k
    for (size_t pred = 0; pred < num_predictors; pred++) {
218
338k
      size_t extra_bits = 0;
219
338k
      const std::vector<ResidualToken>& rtokens = tree_samples.RTokens(pred);
220
48.7M
      for (size_t i = begin; i < end; i++) {
221
48.4M
        const ResidualToken& rt = rtokens[i];
222
48.4M
        size_t count = tree_samples.Count(i);
223
48.4M
        size_t eb = rt.nbits * count;
224
48.4M
        counts[pred * max_symbols + rt.tok] += count;
225
48.4M
        extra_bits += eb;
226
48.4M
      }
227
338k
      tot_extra_bits[pred] = extra_bits;
228
338k
    }
229
230
338k
    float base_bits;
231
338k
    {
232
338k
      size_t pred = tree_samples.PredictorIndex((*tree)[pos].predictor);
233
338k
      base_bits =
234
338k
          EstimateBits(counts.data() + pred * max_symbols, max_symbols) +
235
338k
          tot_extra_bits[pred];
236
338k
    }
237
238
338k
    SplitInfo *best = &best_split_nonstatic;
239
240
338k
    SplitInfo forced_split;
241
    // The multiplier ranges cut halfway through the current ranges of static
242
    // properties. We do this even if the current node is not a leaf, to
243
    // minimize the number of nodes in the resulting tree.
244
338k
    for (const auto &mmi : mul_info) {
245
102k
      uint32_t axis;
246
102k
      uint32_t val;
247
102k
      IntersectionType t =
248
102k
          BoxIntersects(static_prop_range, mmi.range, axis, val);
249
102k
      if (t == IntersectionType::kNone) continue;
250
102k
      if (t == IntersectionType::kInside) {
251
102k
        (*tree)[pos].multiplier = mmi.multiplier;
252
102k
        break;
253
102k
      }
254
0
      if (t == IntersectionType::kPartial) {
255
0
        JXL_DASSERT(axis < kNumStaticProperties);
256
0
        forced_split.val = tree_samples.QuantizeStaticProperty(axis, val);
257
0
        forced_split.prop = axis;
258
0
        forced_split.lcost = forced_split.rcost = base_bits / 2 - threshold;
259
0
        forced_split.lpred = forced_split.rpred = (*tree)[pos].predictor;
260
0
        best = &forced_split;
261
0
        best->pos = begin;
262
0
        JXL_DASSERT(best->prop == tree_samples.PropertyFromIndex(best->prop));
263
0
        if (best->prop < tree_samples.NumStaticProps()) {
264
0
        for (size_t x = begin; x < end; x++) {
265
0
          if (tree_samples.Property<true>(best->prop, x) <= best->val) {
266
0
            best->pos++;
267
0
          }
268
0
        }
269
0
      } else {
270
0
        size_t prop = best->prop - tree_samples.NumStaticProps();
271
0
        for (size_t x = begin; x < end; x++) {
272
0
          if (tree_samples.Property<false>(prop, x) <= best->val) {
273
0
            best->pos++;
274
0
          }
275
0
        }
276
0
      }
277
0
        break;
278
0
      }
279
0
    }
280
281
338k
    if (best != &forced_split) {
282
338k
      std::vector<int> prop_value_used_count;
283
338k
      std::vector<int> count_increase;
284
338k
      std::vector<size_t> extra_bits_increase;
285
      // For each property, compute which of its values are used, and what
286
      // tokens correspond to those usages. Then, iterate through the values,
287
      // and compute the entropy of each side of the split (of the form `prop >
288
      // threshold`). Finally, find the split that minimizes the cost.
289
338k
      struct CostInfo {
290
338k
        float cost = std::numeric_limits<float>::max();
291
338k
        float extra_cost = 0;
292
338k
        float Cost() const { return cost + extra_cost; }
293
338k
        Predictor pred;  // will be uninitialized in some cases, but never used.
294
338k
      };
295
338k
      std::vector<CostInfo> costs_l;
296
338k
      std::vector<CostInfo> costs_r;
297
298
338k
      std::vector<int32_t> counts_above(max_symbols);
299
338k
      std::vector<int32_t> counts_below(max_symbols);
300
301
      // The lower the threshold, the higher the expected noisiness of the
302
      // estimate. Thus, discourage changing predictors.
303
338k
      float change_pred_penalty = 800.0f / (100.0f + threshold);
304
2.53M
      for (size_t prop = 0; prop < num_properties && base_bits > threshold;
305
2.19M
           prop++) {
306
2.19M
        costs_l.clear();
307
2.19M
        costs_r.clear();
308
2.19M
        size_t prop_size = tree_samples.NumPropertyValues(prop);
309
2.19M
        if (extra_bits_increase.size() < prop_size) {
310
786k
          count_increase.resize(prop_size * max_symbols);
311
786k
          extra_bits_increase.resize(prop_size);
312
786k
        }
313
        // Clear prop_value_used_count (which cannot be cleared "on the go")
314
2.19M
        prop_value_used_count.clear();
315
2.19M
        prop_value_used_count.resize(prop_size);
316
317
2.19M
        size_t first_used = prop_size;
318
2.19M
        size_t last_used = 0;
319
320
        // TODO(veluca): consider finding multiple splits along a single
321
        // property at the same time, possibly with a bottom-up approach.
322
2.19M
        if (prop < tree_samples.NumStaticProps()) {
323
72.4M
          for (size_t i = begin; i < end; i++) {
324
72.0M
            size_t p = tree_samples.Property<true>(prop, i);
325
72.0M
            prop_value_used_count[p]++;
326
72.0M
            last_used = std::max(last_used, p);
327
72.0M
            first_used = std::min(first_used, p);
328
72.0M
          }
329
1.77M
        } else {
330
1.77M
          size_t prop_idx = prop - tree_samples.NumStaticProps();
331
267M
          for (size_t i = begin; i < end; i++) {
332
265M
            size_t p = tree_samples.Property<false>(prop_idx, i);
333
265M
            prop_value_used_count[p]++;
334
265M
            last_used = std::max(last_used, p);
335
265M
            first_used = std::min(first_used, p);
336
265M
          }
337
1.77M
        }
338
2.19M
        costs_l.resize(last_used - first_used);
339
2.19M
        costs_r.resize(last_used - first_used);
340
        // For all predictors, compute the right and left costs of each split.
341
4.38M
        for (size_t pred = 0; pred < num_predictors; pred++) {
342
          // Compute cost and histogram increments for each property value.
343
2.19M
          const std::vector<ResidualToken> &rtokens =
344
2.19M
              tree_samples.RTokens(pred);
345
2.19M
          if (prop < tree_samples.NumStaticProps()) {
346
415k
            CollectExtraBitsIncrease<true>(tree_samples, rtokens,
347
415k
                                           count_increase, extra_bits_increase,
348
415k
                                           begin, end, prop, max_symbols);
349
1.77M
          } else {
350
1.77M
            CollectExtraBitsIncrease<false>(
351
1.77M
                tree_samples, rtokens, count_increase, extra_bits_increase,
352
1.77M
                begin, end, prop - tree_samples.NumStaticProps(), max_symbols);
353
1.77M
          }
354
2.19M
          memcpy(counts_above.data(), counts.data() + pred * max_symbols,
355
2.19M
                 max_symbols * sizeof counts_above[0]);
356
2.19M
          memset(counts_below.data(), 0, max_symbols * sizeof counts_below[0]);
357
2.19M
          size_t extra_bits_below = 0;
358
          // Exclude last used: this ensures neither counts_above nor
359
          // counts_below is empty.
360
17.5M
          for (size_t i = first_used; i < last_used; i++) {
361
15.3M
            if (!prop_value_used_count[i]) continue;
362
8.19M
            extra_bits_below += extra_bits_increase[i];
363
            // The increase for this property value has been used, and will not
364
            // be used again: clear it. Also below.
365
8.19M
            extra_bits_increase[i] = 0;
366
400M
            for (size_t sym = 0; sym < max_symbols; sym++) {
367
392M
              counts_above[sym] -= count_increase[i * max_symbols + sym];
368
392M
              counts_below[sym] += count_increase[i * max_symbols + sym];
369
392M
              count_increase[i * max_symbols + sym] = 0;
370
392M
            }
371
8.19M
            float rcost = EstimateBits(counts_above.data(), max_symbols) +
372
8.19M
                          tot_extra_bits[pred] - extra_bits_below;
373
8.19M
            float lcost = EstimateBits(counts_below.data(), max_symbols) +
374
8.19M
                          extra_bits_below;
375
8.19M
            JXL_DASSERT(extra_bits_below <= tot_extra_bits[pred]);
376
8.19M
            float penalty = 0;
377
            // Never discourage moving away from the Weighted predictor.
378
8.19M
            if (tree_samples.PredictorFromIndex(pred) !=
379
8.19M
                    (*tree)[pos].predictor &&
380
0
                (*tree)[pos].predictor != Predictor::Weighted) {
381
0
              penalty = change_pred_penalty;
382
0
            }
383
            // If everything else is equal, disfavour Weighted (slower) and
384
            // favour Zero (faster if it's the only predictor used in a
385
            // group+channel combination)
386
8.19M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Weighted) {
387
0
              penalty += 1e-8;
388
0
            }
389
8.19M
            if (tree_samples.PredictorFromIndex(pred) == Predictor::Zero) {
390
0
              penalty -= 1e-8;
391
0
            }
392
8.19M
            if (rcost + penalty < costs_r[i - first_used].Cost()) {
393
8.19M
              costs_r[i - first_used].cost = rcost;
394
8.19M
              costs_r[i - first_used].extra_cost = penalty;
395
8.19M
              costs_r[i - first_used].pred =
396
8.19M
                  tree_samples.PredictorFromIndex(pred);
397
8.19M
            }
398
8.19M
            if (lcost + penalty < costs_l[i - first_used].Cost()) {
399
8.19M
              costs_l[i - first_used].cost = lcost;
400
8.19M
              costs_l[i - first_used].extra_cost = penalty;
401
8.19M
              costs_l[i - first_used].pred =
402
8.19M
                  tree_samples.PredictorFromIndex(pred);
403
8.19M
            }
404
8.19M
          }
405
2.19M
        }
406
        // Iterate through the possible splits and find the one with minimum sum
407
        // of costs of the two sides.
408
2.19M
        size_t split = begin;
409
17.5M
        for (size_t i = first_used; i < last_used; i++) {
410
15.3M
          if (!prop_value_used_count[i]) continue;
411
8.19M
          split += prop_value_used_count[i];
412
8.19M
          float rcost = costs_r[i - first_used].cost;
413
8.19M
          float lcost = costs_l[i - first_used].cost;
414
          // WP was not used + we would use the WP property or predictor
415
8.19M
          bool adds_wp =
416
8.19M
              (tree_samples.PropertyFromIndex(prop) == kWPProp &&
417
1.58M
               (used_properties & (1LU << prop)) == 0) ||
418
6.80M
              ((costs_l[i - first_used].pred == Predictor::Weighted ||
419
6.80M
                costs_r[i - first_used].pred == Predictor::Weighted) &&
420
0
               (*tree)[pos].predictor != Predictor::Weighted);
421
8.19M
          bool zero_entropy_side = rcost == 0 || lcost == 0;
422
423
8.19M
          SplitInfo &best_ref =
424
8.19M
              tree_samples.PropertyFromIndex(prop) < kNumStaticProperties
425
8.19M
                  ? (zero_entropy_side ? best_split_static_constant
426
27.0k
                                       : best_split_static)
427
8.19M
                  : (adds_wp ? best_split_nonstatic : best_split_nowp);
428
8.19M
          if (lcost + rcost < best_ref.Cost()) {
429
1.78M
            best_ref.prop = prop;
430
1.78M
            best_ref.val = i;
431
1.78M
            best_ref.pos = split;
432
1.78M
            best_ref.lcost = lcost;
433
1.78M
            best_ref.lpred = costs_l[i - first_used].pred;
434
1.78M
            best_ref.rcost = rcost;
435
1.78M
            best_ref.rpred = costs_r[i - first_used].pred;
436
1.78M
          }
437
8.19M
        }
438
        // Clear extra_bits_increase and cost_increase for last_used.
439
2.19M
        extra_bits_increase[last_used] = 0;
440
109M
        for (size_t sym = 0; sym < max_symbols; sym++) {
441
107M
          count_increase[last_used * max_symbols + sym] = 0;
442
107M
        }
443
2.19M
      }
444
445
      // Try to avoid introducing WP.
446
338k
      if (best_split_nowp.Cost() + threshold < base_bits &&
447
164k
          best_split_nowp.Cost() <= fast_decode_multiplier * best->Cost()) {
448
159k
        best = &best_split_nowp;
449
159k
      }
450
      // Split along static props if possible and not significantly more
451
      // expensive.
452
338k
      if (best_split_static.Cost() + threshold < base_bits &&
453
9.50k
          best_split_static.Cost() <= fast_decode_multiplier * best->Cost()) {
454
3.93k
        best = &best_split_static;
455
3.93k
      }
456
      // Split along static props to create constant nodes if possible.
457
338k
      if (best_split_static_constant.Cost() + threshold < base_bits) {
458
433
        best = &best_split_static_constant;
459
433
      }
460
338k
    }
461
462
338k
    if (best->Cost() + threshold < base_bits) {
463
168k
      uint32_t p = tree_samples.PropertyFromIndex(best->prop);
464
168k
      pixel_type dequant =
465
168k
          tree_samples.UnquantizeProperty(best->prop, best->val);
466
      // Split node and try to split children.
467
168k
      MakeSplitNode(pos, p, dequant, best->lpred, 0, best->rpred, 0, tree);
468
      // "Sort" according to winning property
469
168k
      if (best->prop < tree_samples.NumStaticProps()) {
470
4.21k
        SplitTreeSamples<true>(tree_samples, begin, best->pos, end, best->prop,
471
4.21k
                               best->val);
472
163k
      } else {
473
163k
        SplitTreeSamples<false>(tree_samples, begin, best->pos, end,
474
163k
                                best->prop - tree_samples.NumStaticProps(),
475
163k
                                best->val);
476
163k
      }
477
168k
      if (p >= kNumStaticProperties) {
478
163k
        used_properties |= 1 << best->prop;
479
163k
      }
480
168k
      auto new_sp_range = static_prop_range;
481
168k
      if (p < kNumStaticProperties) {
482
4.21k
        JXL_DASSERT(static_cast<uint32_t>(dequant + 1) <= new_sp_range[p][1]);
483
4.21k
        new_sp_range[p][1] = dequant + 1;
484
4.21k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
485
4.21k
      }
486
168k
      nodes.push_back(NodeInfo{(*tree)[pos].rchild, begin, best->pos,
487
168k
                               used_properties, new_sp_range});
488
168k
      new_sp_range = static_prop_range;
489
168k
      if (p < kNumStaticProperties) {
490
4.21k
        JXL_DASSERT(new_sp_range[p][0] <= static_cast<uint32_t>(dequant + 1));
491
4.21k
        new_sp_range[p][0] = dequant + 1;
492
4.21k
        JXL_DASSERT(new_sp_range[p][0] < new_sp_range[p][1]);
493
4.21k
      }
494
168k
      nodes.push_back(NodeInfo{(*tree)[pos].lchild, best->pos, end,
495
168k
                               used_properties, new_sp_range});
496
168k
    }
497
338k
  }
498
2.22k
}
Unexecuted instantiation: jxl::N_SSE2::FindBestSplit(jxl::TreeSamples&, float, std::__1::vector<jxl::ModularMultiplierInfo, std::__1::allocator<jxl::ModularMultiplierInfo> > const&, std::__1::array<std::__1::array<unsigned int, 2ul>, 2ul>, float, std::__1::vector<jxl::PropertyDecisionNode, std::__1::allocator<jxl::PropertyDecisionNode> >*)
499
500
// NOLINTNEXTLINE(google-readability-namespace-comments)
501
}  // namespace HWY_NAMESPACE
502
}  // namespace jxl
503
HWY_AFTER_NAMESPACE();
504
505
#if HWY_ONCE
506
namespace jxl {
507
508
HWY_EXPORT(FindBestSplit);  // Local function.
509
510
Status ComputeBestTree(TreeSamples &tree_samples, float threshold,
511
                       const std::vector<ModularMultiplierInfo> &mul_info,
512
                       StaticPropRange static_prop_range,
513
2.22k
                       float fast_decode_multiplier, Tree *tree) {
514
  // TODO(veluca): take into account that different contexts can have different
515
  // uint configs.
516
  //
517
  // Initialize tree.
518
2.22k
  tree->emplace_back();
519
2.22k
  tree->back().property = -1;
520
2.22k
  tree->back().predictor = tree_samples.PredictorFromIndex(0);
521
2.22k
  tree->back().predictor_offset = 0;
522
2.22k
  tree->back().multiplier = 1;
523
2.22k
  JXL_ENSURE(tree_samples.NumProperties() < 64);
524
525
2.22k
  JXL_ENSURE(tree_samples.NumDistinctSamples() <=
526
2.22k
             std::numeric_limits<uint32_t>::max());
527
2.22k
  HWY_DYNAMIC_DISPATCH(FindBestSplit)
528
2.22k
  (tree_samples, threshold, mul_info, static_prop_range, fast_decode_multiplier,
529
2.22k
   tree);
530
2.22k
  return true;
531
2.22k
}
532
533
#if JXL_CXX_LANG < JXL_CXX_17
534
constexpr int32_t TreeSamples::kPropertyRange;
535
constexpr uint32_t TreeSamples::kDedupEntryUnused;
536
#endif
537
538
Status TreeSamples::SetPredictor(Predictor predictor,
539
2.41k
                                 ModularOptions::TreeMode wp_tree_mode) {
540
2.41k
  if (wp_tree_mode == ModularOptions::TreeMode::kWPOnly) {
541
0
    predictors = {Predictor::Weighted};
542
0
    residuals.resize(1);
543
0
    return true;
544
0
  }
545
2.41k
  if (wp_tree_mode == ModularOptions::TreeMode::kNoWP &&
546
0
      predictor == Predictor::Weighted) {
547
0
    return JXL_FAILURE("Invalid predictor settings");
548
0
  }
549
2.41k
  if (predictor == Predictor::Variable) {
550
0
    for (size_t i = 0; i < kNumModularPredictors; i++) {
551
0
      predictors.push_back(static_cast<Predictor>(i));
552
0
    }
553
0
    std::swap(predictors[0], predictors[static_cast<int>(Predictor::Weighted)]);
554
0
    std::swap(predictors[1], predictors[static_cast<int>(Predictor::Gradient)]);
555
2.41k
  } else if (predictor == Predictor::Best) {
556
0
    predictors = {Predictor::Weighted, Predictor::Gradient};
557
2.41k
  } else {
558
2.41k
    predictors = {predictor};
559
2.41k
  }
560
2.41k
  if (wp_tree_mode == ModularOptions::TreeMode::kNoWP) {
561
0
    predictors.erase(
562
0
        std::remove(predictors.begin(), predictors.end(), Predictor::Weighted),
563
0
        predictors.end());
564
0
  }
565
2.41k
  residuals.resize(predictors.size());
566
2.41k
  return true;
567
2.41k
}
568
569
Status TreeSamples::SetProperties(const std::vector<uint32_t> &properties,
570
2.41k
                                  ModularOptions::TreeMode wp_tree_mode) {
571
2.41k
  props_to_use = properties;
572
2.41k
  if (wp_tree_mode == ModularOptions::TreeMode::kWPOnly) {
573
0
    props_to_use = {static_cast<uint32_t>(kWPProp)};
574
0
  }
575
2.41k
  if (wp_tree_mode == ModularOptions::TreeMode::kGradientOnly) {
576
0
    props_to_use = {static_cast<uint32_t>(kGradientProp)};
577
0
  }
578
2.41k
  if (wp_tree_mode == ModularOptions::TreeMode::kNoWP) {
579
0
    props_to_use.erase(
580
0
        std::remove(props_to_use.begin(), props_to_use.end(), kWPProp),
581
0
        props_to_use.end());
582
0
  }
583
2.41k
  if (props_to_use.empty()) {
584
0
    return JXL_FAILURE("Invalid property set configuration");
585
0
  }
586
2.41k
  num_static_props = 0;
587
  // Check that if static properties present, then those are at the beginning.
588
19.3k
  for (size_t i = 0; i < props_to_use.size(); ++i) {
589
16.9k
    uint32_t prop = props_to_use[i];
590
16.9k
    if (prop < kNumStaticProperties) {
591
3.34k
      JXL_DASSERT(i == prop);
592
3.34k
      num_static_props++;
593
3.34k
    }
594
16.9k
  }
595
2.41k
  props.resize(props_to_use.size() - num_static_props);
596
2.41k
  return true;
597
2.41k
}
598
599
5.84k
void TreeSamples::InitTable(size_t log_size) {
600
5.84k
  size_t size = 1ULL << log_size;
601
5.84k
  if (dedup_table_.size() == size) return;
602
3.99k
  dedup_table_.resize(size, kDedupEntryUnused);
603
4.28M
  for (size_t i = 0; i < NumDistinctSamples(); i++) {
604
4.27M
    if (sample_counts[i] != std::numeric_limits<uint16_t>::max()) {
605
4.27M
      AddToTable(i);
606
4.27M
    }
607
4.27M
  }
608
3.99k
}
609
610
41.9M
bool TreeSamples::AddToTableAndMerge(size_t a) {
611
41.9M
  size_t pos1 = Hash1(a);
612
41.9M
  size_t pos2 = Hash2(a);
613
41.9M
  if (dedup_table_[pos1] != kDedupEntryUnused &&
614
38.8M
      IsSameSample(a, dedup_table_[pos1])) {
615
31.4M
    JXL_DASSERT(sample_counts[a] == 1);
616
31.4M
    sample_counts[dedup_table_[pos1]]++;
617
    // Remove from hash table samples that are saturated.
618
31.4M
    if (sample_counts[dedup_table_[pos1]] ==
619
31.4M
        std::numeric_limits<uint16_t>::max()) {
620
20
      dedup_table_[pos1] = kDedupEntryUnused;
621
20
    }
622
31.4M
    return true;
623
31.4M
  }
624
10.5M
  if (dedup_table_[pos2] != kDedupEntryUnused &&
625
6.70M
      IsSameSample(a, dedup_table_[pos2])) {
626
5.24M
    JXL_DASSERT(sample_counts[a] == 1);
627
5.24M
    sample_counts[dedup_table_[pos2]]++;
628
    // Remove from hash table samples that are saturated.
629
5.24M
    if (sample_counts[dedup_table_[pos2]] ==
630
5.24M
        std::numeric_limits<uint16_t>::max()) {
631
0
      dedup_table_[pos2] = kDedupEntryUnused;
632
0
    }
633
5.24M
    return true;
634
5.24M
  }
635
5.27M
  AddToTable(a);
636
5.27M
  return false;
637
10.5M
}
638
639
9.55M
void TreeSamples::AddToTable(size_t a) {
640
9.55M
  size_t pos1 = Hash1(a);
641
9.55M
  size_t pos2 = Hash2(a);
642
9.55M
  if (dedup_table_[pos1] == kDedupEntryUnused) {
643
4.46M
    dedup_table_[pos1] = a;
644
5.09M
  } else if (dedup_table_[pos2] == kDedupEntryUnused) {
645
2.70M
    dedup_table_[pos2] = a;
646
2.70M
  }
647
9.55M
}
648
649
5.84k
void TreeSamples::PrepareForSamples(size_t extra_num_samples) {
650
5.84k
  for (auto &res : residuals) {
651
5.84k
    res.reserve(res.size() + extra_num_samples);
652
5.84k
  }
653
14.9k
  for (size_t i = 0; i < num_static_props; ++i) {
654
9.05k
    static_props[i].reserve(static_props[i].size() + extra_num_samples);
655
9.05k
  }
656
31.8k
  for (auto &p : props) {
657
31.8k
    p.reserve(p.size() + extra_num_samples);
658
31.8k
  }
659
5.84k
  size_t total_num_samples = extra_num_samples + sample_counts.size();
660
5.84k
  size_t next_size = CeilLog2Nonzero(total_num_samples * 3 / 2);
661
5.84k
  InitTable(next_size);
662
5.84k
}
663
664
51.5M
size_t TreeSamples::Hash1(size_t a) const {
665
51.5M
  constexpr uint64_t constant = 0x1e35a7bd;
666
51.5M
  uint64_t h = constant;
667
51.5M
  for (const auto &r : residuals) {
668
51.5M
    h = h * constant + r[a].tok;
669
51.5M
    h = h * constant + r[a].nbits;
670
51.5M
  }
671
117M
  for (size_t i = 0; i < num_static_props; ++i) {
672
66.3M
    h = h * constant + static_props[i][a];
673
66.3M
  }
674
294M
  for (const auto &p : props) {
675
294M
    h = h * constant + p[a];
676
294M
  }
677
51.5M
  return (h >> 16) & (dedup_table_.size() - 1);
678
51.5M
}
679
51.5M
size_t TreeSamples::Hash2(size_t a) const {
680
51.5M
  constexpr uint64_t constant = 0x1e35a7bd1e35a7bd;
681
51.5M
  uint64_t h = constant;
682
117M
  for (size_t i = 0; i < num_static_props; ++i) {
683
66.3M
    h = h * constant ^ static_props[i][a];
684
66.3M
  }
685
294M
  for (const auto &p : props) {
686
294M
    h = h * constant ^ p[a];
687
294M
  }
688
51.5M
  for (const auto &r : residuals) {
689
51.5M
    h = h * constant ^ r[a].tok;
690
51.5M
    h = h * constant ^ r[a].nbits;
691
51.5M
  }
692
51.5M
  return (h >> 16) & (dedup_table_.size() - 1);
693
51.5M
}
694
695
45.5M
bool TreeSamples::IsSameSample(size_t a, size_t b) const {
696
45.5M
  bool ret = true;
697
45.5M
  for (const auto &r : residuals) {
698
45.5M
    if (r[a].tok != r[b].tok) {
699
3.35M
      ret = false;
700
3.35M
    }
701
45.5M
    if (r[a].nbits != r[b].nbits) {
702
2.30M
      ret = false;
703
2.30M
    }
704
45.5M
  }
705
101M
  for (size_t i = 0; i < num_static_props; ++i) {
706
56.3M
    if (static_props[i][a] != static_props[i][b]) {
707
2.04M
      ret = false;
708
2.04M
    }
709
56.3M
  }
710
262M
  for (const auto &p : props) {
711
262M
    if (p[a] != p[b]) {
712
21.4M
      ret = false;
713
21.4M
    }
714
262M
  }
715
45.5M
  return ret;
716
45.5M
}
717
718
void TreeSamples::AddSample(pixel_type_w pixel, const Properties &properties,
719
41.9M
                            const pixel_type_w *predictions) {
720
83.9M
  for (size_t i = 0; i < predictors.size(); i++) {
721
41.9M
    pixel_type v = pixel - predictions[static_cast<int>(predictors[i])];
722
41.9M
    uint32_t tok, nbits, bits;
723
41.9M
    HybridUintConfig(4, 1, 2).Encode(PackSigned(v), &tok, &nbits, &bits);
724
41.9M
    JXL_DASSERT(tok < 256);
725
41.9M
    JXL_DASSERT(nbits < 256);
726
41.9M
    ResidualToken token = {static_cast<uint8_t>(tok),
727
41.9M
                           static_cast<uint8_t>(nbits)};
728
41.9M
    residuals[i].push_back(token);
729
41.9M
  }
730
94.2M
  for (size_t i = 0; i < num_static_props; ++i) {
731
52.2M
    static_props[i].push_back(QuantizeStaticProperty(i, properties[i]));
732
52.2M
  }
733
283M
  for (size_t i = num_static_props; i < props_to_use.size(); i++) {
734
241M
    props[i - num_static_props].push_back(QuantizeProperty(i, properties[props_to_use[i]]));
735
241M
  }
736
41.9M
  sample_counts.push_back(1);
737
41.9M
  num_samples++;
738
41.9M
  if (AddToTableAndMerge(sample_counts.size() - 1)) {
739
36.7M
    for (auto &r : residuals) r.pop_back();
740
80.7M
    for (size_t i = 0; i < num_static_props; ++i) static_props[i].pop_back();
741
212M
    for (auto &p : props) p.pop_back();
742
36.7M
    sample_counts.pop_back();
743
36.7M
  }
744
41.9M
}
745
746
8.23M
void TreeSamples::Swap(size_t a, size_t b) {
747
8.23M
  if (a == b) return;
748
8.23M
  for (auto &r : residuals) {
749
8.23M
    std::swap(r[a], r[b]);
750
8.23M
  }
751
20.3M
  for (size_t i = 0; i < num_static_props; ++i) {
752
12.1M
    std::swap(static_props[i][a], static_props[i][b]);
753
12.1M
  }
754
45.4M
  for (auto &p : props) {
755
45.4M
    std::swap(p[a], p[b]);
756
45.4M
  }
757
8.23M
  std::swap(sample_counts[a], sample_counts[b]);
758
8.23M
}
759
760
namespace {
761
std::vector<int32_t> QuantizeHistogram(const std::vector<uint32_t> &histogram,
762
6.85k
                                       size_t num_chunks) {
763
6.85k
  if (histogram.empty() || num_chunks == 0) return {};
764
6.85k
  uint64_t sum = std::accumulate(histogram.begin(), histogram.end(), 0LU);
765
6.85k
  if (sum == 0) return {};
766
  // TODO(veluca): selecting distinct quantiles is likely not the best
767
  // way to go about this.
768
6.60k
  std::vector<int32_t> thresholds;
769
6.60k
  uint64_t cumsum = 0;
770
6.60k
  uint64_t threshold = 1;
771
3.61M
  for (size_t i = 0; i < histogram.size(); i++) {
772
3.61M
    cumsum += histogram[i];
773
3.61M
    if (cumsum * num_chunks >= threshold * sum) {
774
31.1k
      thresholds.push_back(i);
775
348k
      while (cumsum * num_chunks >= threshold * sum) threshold++;
776
31.1k
    }
777
3.61M
  }
778
6.60k
  JXL_DASSERT(thresholds.size() <= num_chunks);
779
  // last value collects all histogram and is not really a threshold
780
6.60k
  thresholds.pop_back();
781
6.60k
  return thresholds;
782
6.85k
}
783
784
std::vector<int32_t> QuantizeSamples(const std::vector<int32_t> &samples,
785
4.87k
                                     size_t num_chunks) {
786
4.87k
  if (samples.empty()) return {};
787
3.51k
  int min = *std::min_element(samples.begin(), samples.end());
788
3.51k
  constexpr int kRange = 512;
789
3.51k
  min = jxl::Clamp1(min, -kRange, kRange);
790
3.51k
  std::vector<uint32_t> counts(2 * kRange + 1);
791
5.44M
  for (int s : samples) {
792
5.44M
    uint32_t sample_offset = jxl::Clamp1(s, -kRange, kRange) - min;
793
5.44M
    counts[sample_offset]++;
794
5.44M
  }
795
3.51k
  std::vector<int32_t> thresholds = QuantizeHistogram(counts, num_chunks);
796
22.1k
  for (auto &v : thresholds) v += min;
797
3.51k
  return thresholds;
798
4.87k
}
799
800
// `to[i]` is assigned value `v` conforming `from[v] <= i && from[v-1] > i`.
801
// This is because the decision node in the tree splits on (property) > i,
802
// hence everything that is not > of a threshold should be clustered
803
// together.
804
template <typename T>
805
void QuantMap(const std::vector<int32_t> &from, std::vector<T> &to,
806
16.9k
              size_t num_pegs, int bias) {
807
16.9k
  to.resize(num_pegs);
808
16.9k
  size_t mapped = 0;
809
17.3M
  for (size_t i = 0; i < num_pegs; i++) {
810
17.4M
    while (mapped < from.size() && static_cast<int>(i) - bias > from[mapped]) {
811
170k
      mapped++;
812
170k
    }
813
17.3M
    JXL_DASSERT(static_cast<T>(mapped) == mapped);
814
17.3M
    to[i] = mapped;
815
17.3M
  }
816
16.9k
}
enc_ma.cc:void jxl::(anonymous namespace)::QuantMap<unsigned short>(std::__1::vector<int, std::__1::allocator<int> > const&, std::__1::vector<unsigned short, std::__1::allocator<unsigned short> >&, unsigned long, int)
Line
Count
Source
806
3.34k
              size_t num_pegs, int bias) {
807
3.34k
  to.resize(num_pegs);
808
3.34k
  size_t mapped = 0;
809
3.42M
  for (size_t i = 0; i < num_pegs; i++) {
810
3.41M
    while (mapped < from.size() && static_cast<int>(i) - bias > from[mapped]) {
811
2.34k
      mapped++;
812
2.34k
    }
813
3.41M
    JXL_DASSERT(static_cast<T>(mapped) == mapped);
814
3.41M
    to[i] = mapped;
815
3.41M
  }
816
3.34k
}
enc_ma.cc:void jxl::(anonymous namespace)::QuantMap<unsigned char>(std::__1::vector<int, std::__1::allocator<int> > const&, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >&, unsigned long, int)
Line
Count
Source
806
13.5k
              size_t num_pegs, int bias) {
807
13.5k
  to.resize(num_pegs);
808
13.5k
  size_t mapped = 0;
809
13.9M
  for (size_t i = 0; i < num_pegs; i++) {
810
14.0M
    while (mapped < from.size() && static_cast<int>(i) - bias > from[mapped]) {
811
168k
      mapped++;
812
168k
    }
813
13.9M
    JXL_DASSERT(static_cast<T>(mapped) == mapped);
814
13.9M
    to[i] = mapped;
815
13.9M
  }
816
13.5k
}
817
}  // namespace
818
819
void TreeSamples::PreQuantizeProperties(
820
    const StaticPropRange &range,
821
    const std::vector<ModularMultiplierInfo> &multiplier_info,
822
    const std::vector<uint32_t> &group_pixel_count,
823
    const std::vector<uint32_t> &channel_pixel_count,
824
    std::vector<pixel_type> &pixel_samples,
825
2.41k
    std::vector<pixel_type> &diff_samples, size_t max_property_values) {
826
  // If we have forced splits because of multipliers, choose channel and group
827
  // thresholds accordingly.
828
2.41k
  std::vector<int32_t> group_multiplier_thresholds;
829
2.41k
  std::vector<int32_t> channel_multiplier_thresholds;
830
2.41k
  for (const auto &v : multiplier_info) {
831
911
    if (v.range[0][0] != range[0][0]) {
832
0
      channel_multiplier_thresholds.push_back(v.range[0][0] - 1);
833
0
    }
834
911
    if (v.range[0][1] != range[0][1]) {
835
0
      channel_multiplier_thresholds.push_back(v.range[0][1] - 1);
836
0
    }
837
911
    if (v.range[1][0] != range[1][0]) {
838
0
      group_multiplier_thresholds.push_back(v.range[1][0] - 1);
839
0
    }
840
911
    if (v.range[1][1] != range[1][1]) {
841
0
      group_multiplier_thresholds.push_back(v.range[1][1] - 1);
842
0
    }
843
911
  }
844
2.41k
  std::sort(channel_multiplier_thresholds.begin(),
845
2.41k
            channel_multiplier_thresholds.end());
846
2.41k
  channel_multiplier_thresholds.resize(
847
2.41k
      std::unique(channel_multiplier_thresholds.begin(),
848
2.41k
                  channel_multiplier_thresholds.end()) -
849
2.41k
      channel_multiplier_thresholds.begin());
850
2.41k
  std::sort(group_multiplier_thresholds.begin(),
851
2.41k
            group_multiplier_thresholds.end());
852
2.41k
  group_multiplier_thresholds.resize(
853
2.41k
      std::unique(group_multiplier_thresholds.begin(),
854
2.41k
                  group_multiplier_thresholds.end()) -
855
2.41k
      group_multiplier_thresholds.begin());
856
857
2.41k
  compact_properties.resize(props_to_use.size());
858
2.41k
  auto quantize_channel = [&]() {
859
2.41k
    if (!channel_multiplier_thresholds.empty()) {
860
0
      return channel_multiplier_thresholds;
861
0
    }
862
2.41k
    return QuantizeHistogram(channel_pixel_count, max_property_values);
863
2.41k
  };
864
2.41k
  auto quantize_group_id = [&]() {
865
921
    if (!group_multiplier_thresholds.empty()) {
866
0
      return group_multiplier_thresholds;
867
0
    }
868
921
    return QuantizeHistogram(group_pixel_count, max_property_values);
869
921
  };
870
2.41k
  auto quantize_coordinate = [&]() {
871
0
    std::vector<int32_t> quantized;
872
0
    quantized.reserve(max_property_values - 1);
873
0
    for (size_t i = 0; i + 1 < max_property_values; i++) {
874
0
      quantized.push_back((i + 1) * 256 / max_property_values - 1);
875
0
    }
876
0
    return quantized;
877
0
  };
878
2.41k
  std::vector<int32_t> abs_pixel_thresholds;
879
2.41k
  std::vector<int32_t> pixel_thresholds;
880
2.41k
  auto quantize_pixel_property = [&]() {
881
0
    if (pixel_thresholds.empty()) {
882
0
      pixel_thresholds = QuantizeSamples(pixel_samples, max_property_values);
883
0
    }
884
0
    return pixel_thresholds;
885
0
  };
886
2.41k
  auto quantize_abs_pixel_property = [&]() {
887
0
    if (abs_pixel_thresholds.empty()) {
888
0
      quantize_pixel_property();  // Compute the non-abs thresholds.
889
0
      for (auto &v : pixel_samples) v = std::abs(v);
890
0
      abs_pixel_thresholds =
891
0
          QuantizeSamples(pixel_samples, max_property_values);
892
0
    }
893
0
    return abs_pixel_thresholds;
894
0
  };
895
2.41k
  std::vector<int32_t> abs_diff_thresholds;
896
2.41k
  std::vector<int32_t> diff_thresholds;
897
11.1k
  auto quantize_diff_property = [&]() {
898
11.1k
    if (diff_thresholds.empty()) {
899
4.87k
      diff_thresholds = QuantizeSamples(diff_samples, max_property_values);
900
4.87k
    }
901
11.1k
    return diff_thresholds;
902
11.1k
  };
903
2.41k
  auto quantize_abs_diff_property = [&]() {
904
0
    if (abs_diff_thresholds.empty()) {
905
0
      quantize_diff_property();  // Compute the non-abs thresholds.
906
0
      for (auto &v : diff_samples) v = std::abs(v);
907
0
      abs_diff_thresholds = QuantizeSamples(diff_samples, max_property_values);
908
0
    }
909
0
    return abs_diff_thresholds;
910
0
  };
911
2.41k
  auto quantize_wp = [&]() {
912
2.41k
    if (max_property_values < 32) {
913
0
      return std::vector<int32_t>{-127, -63, -31, -15, -7, -3, -1, 0,
914
0
                                  1,    3,   7,   15,  31, 63, 127};
915
0
    }
916
2.41k
    if (max_property_values < 64) {
917
2.41k
      return std::vector<int32_t>{-255, -191, -127, -95, -63, -47, -31, -23,
918
2.41k
                                  -15,  -11,  -7,   -5,  -3,  -1,  0,   1,
919
2.41k
                                  3,    5,    7,    11,  15,  23,  31,  47,
920
2.41k
                                  63,   95,   127,  191, 255};
921
2.41k
    }
922
0
    return std::vector<int32_t>{
923
0
        -255, -223, -191, -159, -127, -111, -95, -79, -63, -55, -47,
924
0
        -39,  -31,  -27,  -23,  -19,  -15,  -13, -11, -9,  -7,  -6,
925
0
        -5,   -4,   -3,   -2,   -1,   0,    1,   2,   3,   4,   5,
926
0
        6,    7,    9,    11,   13,   15,   19,  23,  27,  31,  39,
927
0
        47,   55,   63,   79,   95,   111,  127, 159, 191, 223, 255};
928
2.41k
  };
929
930
2.41k
  property_mapping.resize(props_to_use.size() - num_static_props);
931
19.3k
  for (size_t i = 0; i < props_to_use.size(); i++) {
932
16.9k
    if (props_to_use[i] == 0) {
933
2.41k
      compact_properties[i] = quantize_channel();
934
14.5k
    } else if (props_to_use[i] == 1) {
935
921
      compact_properties[i] = quantize_group_id();
936
13.5k
    } else if (props_to_use[i] == 2 || props_to_use[i] == 3) {
937
0
      compact_properties[i] = quantize_coordinate();
938
13.5k
    } else if (props_to_use[i] == 6 || props_to_use[i] == 7 ||
939
13.5k
               props_to_use[i] == 8 ||
940
13.5k
               (props_to_use[i] >= kNumNonrefProperties &&
941
0
                (props_to_use[i] - kNumNonrefProperties) % 4 == 1)) {
942
0
      compact_properties[i] = quantize_pixel_property();
943
13.5k
    } else if (props_to_use[i] == 4 || props_to_use[i] == 5 ||
944
13.5k
               (props_to_use[i] >= kNumNonrefProperties &&
945
0
                (props_to_use[i] - kNumNonrefProperties) % 4 == 0)) {
946
0
      compact_properties[i] = quantize_abs_pixel_property();
947
13.5k
    } else if (props_to_use[i] >= kNumNonrefProperties &&
948
0
               (props_to_use[i] - kNumNonrefProperties) % 4 == 2) {
949
0
      compact_properties[i] = quantize_abs_diff_property();
950
13.5k
    } else if (props_to_use[i] == kWPProp) {
951
2.41k
      compact_properties[i] = quantize_wp();
952
11.1k
    } else {
953
11.1k
      compact_properties[i] = quantize_diff_property();
954
11.1k
    }
955
16.9k
    if (i < num_static_props) {
956
3.34k
      QuantMap(compact_properties[i], static_property_mapping[i],
957
3.34k
               kPropertyRange * 2 + 1, kPropertyRange);
958
13.5k
    } else {
959
13.5k
      QuantMap(compact_properties[i], property_mapping[i - num_static_props],
960
13.5k
               kPropertyRange * 2 + 1, kPropertyRange);
961
13.5k
    }
962
16.9k
  }
963
2.41k
}
964
965
void CollectPixelSamples(const Image &image, const ModularOptions &options,
966
                         uint32_t group_id,
967
                         std::vector<uint32_t> &group_pixel_count,
968
                         std::vector<uint32_t> &channel_pixel_count,
969
                         std::vector<pixel_type> &pixel_samples,
970
3.72k
                         std::vector<pixel_type> &diff_samples) {
971
3.72k
  if (options.nb_repeats == 0) return;
972
3.72k
  if (group_pixel_count.size() <= group_id) {
973
3.72k
    group_pixel_count.resize(group_id + 1);
974
3.72k
  }
975
3.72k
  if (channel_pixel_count.size() < image.channel.size()) {
976
2.41k
    channel_pixel_count.resize(image.channel.size());
977
2.41k
  }
978
3.72k
  Rng rng(group_id);
979
  // Sample 10% of the final number of samples for property quantization.
980
3.72k
  float fraction = std::min(options.nb_repeats * 0.1, 0.99);
981
3.72k
  Rng::GeometricDistribution dist = Rng::MakeGeometric(fraction);
982
3.72k
  size_t total_pixels = 0;
983
3.72k
  std::vector<size_t> channel_ids;
984
9.57k
  for (size_t i = 0; i < image.channel.size(); i++) {
985
6.30k
    if (i >= image.nb_meta_channels &&
986
5.92k
        (image.channel[i].w > options.max_chan_size ||
987
5.49k
         image.channel[i].h > options.max_chan_size)) {
988
460
      break;
989
460
    }
990
5.84k
    if (image.channel[i].w <= 1 || image.channel[i].h == 0) {
991
80
      continue;  // skip empty or width-1 channels.
992
80
    }
993
5.76k
    channel_ids.push_back(i);
994
5.76k
    group_pixel_count[group_id] += image.channel[i].w * image.channel[i].h;
995
5.76k
    channel_pixel_count[i] += image.channel[i].w * image.channel[i].h;
996
5.76k
    total_pixels += image.channel[i].w * image.channel[i].h;
997
5.76k
  }
998
3.72k
  if (channel_ids.empty()) return;
999
3.45k
  pixel_samples.reserve(pixel_samples.size() + fraction * total_pixels);
1000
3.45k
  diff_samples.reserve(diff_samples.size() + fraction * total_pixels);
1001
3.45k
  size_t i = 0;
1002
3.45k
  size_t y = 0;
1003
3.45k
  size_t x = 0;
1004
4.11M
  auto advance = [&](size_t amount) {
1005
4.11M
    x += amount;
1006
    // Detect row overflow (rare).
1007
4.64M
    while (x >= image.channel[channel_ids[i]].w) {
1008
531k
      x -= image.channel[channel_ids[i]].w;
1009
531k
      y++;
1010
      // Detect end-of-channel (even rarer).
1011
531k
      if (y == image.channel[channel_ids[i]].h) {
1012
5.76k
        i++;
1013
5.76k
        y = 0;
1014
5.76k
        if (i >= channel_ids.size()) {
1015
3.45k
          return;
1016
3.45k
        }
1017
5.76k
      }
1018
531k
    }
1019
4.11M
  };
1020
3.45k
  advance(rng.Geometric(dist));
1021
4.11M
  for (; i < channel_ids.size(); advance(rng.Geometric(dist) + 1)) {
1022
4.11M
    const pixel_type *row = image.channel[channel_ids[i]].Row(y);
1023
4.11M
    pixel_samples.push_back(row[x]);
1024
4.11M
    size_t xp = x == 0 ? 1 : x - 1;
1025
4.11M
    diff_samples.push_back(static_cast<int64_t>(row[x]) - row[xp]);
1026
4.11M
  }
1027
3.45k
}
1028
1029
// TODO(veluca): very simple encoding scheme. This should be improved.
1030
Status TokenizeTree(const Tree &tree, std::vector<Token> *tokens,
1031
3.93k
                    Tree *decoder_tree) {
1032
3.93k
  JXL_ENSURE(tree.size() <= kMaxTreeSize);
1033
3.93k
  std::queue<int> q;
1034
3.93k
  q.push(0);
1035
3.93k
  size_t leaf_id = 0;
1036
3.93k
  decoder_tree->clear();
1037
425k
  while (!q.empty()) {
1038
421k
    int cur = q.front();
1039
421k
    q.pop();
1040
421k
    JXL_ENSURE(tree[cur].property >= -1);
1041
421k
    tokens->emplace_back(kPropertyContext, tree[cur].property + 1);
1042
421k
    if (tree[cur].property == -1) {
1043
212k
      tokens->emplace_back(kPredictorContext,
1044
212k
                           static_cast<int>(tree[cur].predictor));
1045
212k
      tokens->emplace_back(kOffsetContext,
1046
212k
                           PackSigned(tree[cur].predictor_offset));
1047
212k
      uint32_t mul_log = Num0BitsBelowLS1Bit_Nonzero(tree[cur].multiplier);
1048
212k
      uint32_t mul_bits = (tree[cur].multiplier >> mul_log) - 1;
1049
212k
      tokens->emplace_back(kMultiplierLogContext, mul_log);
1050
212k
      tokens->emplace_back(kMultiplierBitsContext, mul_bits);
1051
212k
      JXL_ENSURE(tree[cur].predictor < Predictor::Best);
1052
212k
      decoder_tree->emplace_back(
1053
212k
          -1, 0, static_cast<int>(leaf_id), 0, tree[cur].predictor,
1054
212k
          tree[cur].predictor_offset, tree[cur].multiplier);
1055
212k
      leaf_id++;
1056
212k
      continue;
1057
212k
    }
1058
208k
    decoder_tree->emplace_back(
1059
208k
        tree[cur].property, tree[cur].splitval,
1060
208k
        static_cast<int>(decoder_tree->size() + q.size() + 1),
1061
208k
        static_cast<int>(decoder_tree->size() + q.size() + 2), Predictor::Zero,
1062
208k
        0, 1);
1063
208k
    q.push(tree[cur].lchild);
1064
208k
    q.push(tree[cur].rchild);
1065
208k
    tokens->emplace_back(kSplitValContext, PackSigned(tree[cur].splitval));
1066
208k
  }
1067
3.93k
  return true;
1068
3.93k
}
1069
1070
}  // namespace jxl
1071
#endif  // HWY_ONCE