Coverage Report

Created: 2026-11-12 07:35

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