7 #include <dmlc/registry.h> 14 DMLC_REGISTRY_FILE_TAG(quantize);
16 template <
typename ThresholdType>
18 scan_thresholds(ASTNode* node, std::vector<std::set<ThresholdType>>* cut_pts) {
19 NumericalConditionNode<ThresholdType>* num_cond;
20 if ( (num_cond =
dynamic_cast<NumericalConditionNode<ThresholdType>*
>(node)) ) {
21 CHECK(!num_cond->quantized) <<
"should not be already quantized";
22 const ThresholdType threshold = num_cond->threshold.float_val;
23 if (std::isfinite(threshold)) {
24 (*cut_pts)[num_cond->split_index].insert(threshold);
27 for (ASTNode* child : node->children) {
28 scan_thresholds(child, cut_pts);
32 template <
typename ThresholdType>
34 rewrite_thresholds(ASTNode* node,
const std::vector<std::vector<ThresholdType>>& cut_pts) {
35 NumericalConditionNode<ThresholdType>* num_cond;
36 if ( (num_cond =
dynamic_cast<NumericalConditionNode<ThresholdType>*
>(node)) ) {
37 CHECK(!num_cond->quantized) <<
"should not be already quantized";
38 const ThresholdType threshold = num_cond->threshold.float_val;
39 if (std::isfinite(threshold)) {
40 const auto& v = cut_pts[num_cond->split_index];
42 auto loc = math::binary_search(v.begin(), v.end(), threshold);
43 CHECK(loc != v.end());
44 num_cond->threshold.int_val =
static_cast<int>(loc - v.begin()) * 2;
47 ThresholdType zero =
static_cast<ThresholdType
>(0);
48 auto loc = std::lower_bound(v.begin(), v.end(), zero);
49 num_cond->zero_quantized =
static_cast<int>(loc - v.begin()) * 2;
50 if (loc != v.end() && zero != *loc) {
51 --num_cond->zero_quantized;
54 num_cond->quantized =
true;
57 for (ASTNode* child : node->children) {
58 rewrite_thresholds(child, cut_pts);
62 template <
typename ThresholdType,
typename LeafOutputType>
64 ASTBuilder<ThresholdType, LeafOutputType>::QuantizeThresholds() {
65 this->quantize_threshold_flag =
true;
66 std::vector<std::set<ThresholdType>> cut_pts;
67 std::vector<std::vector<ThresholdType>> cut_pts_vec;
68 cut_pts.resize(this->num_feature);
69 cut_pts_vec.resize(this->num_feature);
70 scan_thresholds(this->main_node, &cut_pts);
72 for (
int i = 0; i < this->num_feature; ++i) {
73 std::copy(cut_pts[i].begin(), cut_pts[i].end(), std::back_inserter(cut_pts_vec[i]));
77 rewrite_thresholds(this->main_node, cut_pts_vec);
79 CHECK_EQ(this->main_node->children.size(), 1);
80 ASTNode* top_ac_node = this->main_node->children[0];
81 CHECK(dynamic_cast<AccumulatorContextNode*>(top_ac_node));
85 ASTNode* quantizer_node
86 = AddNode<QuantizerNode<ThresholdType>>(this->main_node, std::move(cut_pts_vec));
87 quantizer_node->children.push_back(top_ac_node);
88 top_ac_node->parent = quantizer_node;
89 this->main_node->children[0] = quantizer_node;
92 template void ASTBuilder<float, uint32_t>::QuantizeThresholds();
93 template void ASTBuilder<float, float>::QuantizeThresholds();
94 template void ASTBuilder<double, uint32_t>::QuantizeThresholds();
95 template void ASTBuilder<double, double>::QuantizeThresholds();
Some useful math utilities.