aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/boosted_trees/prediction_ops.cc
blob: b2efa06941dd70fa0c5d0d7b2e5d488c160792bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <algorithm>
#include <string>
#include <vector>

#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/boosted_trees/boosted_trees.pb.h"
#include "tensorflow/core/kernels/boosted_trees/resources.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/work_sharder.h"

namespace tensorflow {

// The Op used during training time to get the predictions so far with the
// current ensemble being built.
// Expect some logits are cached from the previous step and passed through
// to be reused.
class BoostedTreesTrainingPredictOp : public OpKernel {
 public:
  explicit BoostedTreesTrainingPredictOp(OpKernelConstruction* const context)
      : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("num_bucketized_features",
                                             &num_bucketized_features_));
    OP_REQUIRES_OK(context,
                   context->GetAttr("logits_dimension", &logits_dimension_));
    OP_REQUIRES(context, logits_dimension_ == 1,
                errors::InvalidArgument(
                    "Currently only one dimensional outputs are supported."));
  }

  void Compute(OpKernelContext* const context) override {
    BoostedTreesEnsembleResource* resource;
    // Get the resource.
    OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
                                           &resource));
    // Release the reference to the resource once we're done using it.
    core::ScopedUnref unref_me(resource);

    // Get the inputs.
    OpInputList bucketized_features_list;
    OP_REQUIRES_OK(context, context->input_list("bucketized_features",
                                                &bucketized_features_list));
    std::vector<tensorflow::TTypes<int32>::ConstVec> batch_bucketized_features;
    batch_bucketized_features.reserve(bucketized_features_list.size());
    for (const Tensor& tensor : bucketized_features_list) {
      batch_bucketized_features.emplace_back(tensor.vec<int32>());
    }
    const int batch_size = batch_bucketized_features[0].size();

    const Tensor* cached_tree_ids_t;
    OP_REQUIRES_OK(context,
                   context->input("cached_tree_ids", &cached_tree_ids_t));
    const auto cached_tree_ids = cached_tree_ids_t->vec<int32>();

    const Tensor* cached_node_ids_t;
    OP_REQUIRES_OK(context,
                   context->input("cached_node_ids", &cached_node_ids_t));
    const auto cached_node_ids = cached_node_ids_t->vec<int32>();

    // Allocate outputs.
    Tensor* output_partial_logits_t = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output("partial_logits",
                                            {batch_size, logits_dimension_},
                                            &output_partial_logits_t));
    auto output_partial_logits = output_partial_logits_t->matrix<float>();

    Tensor* output_tree_ids_t = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output("tree_ids", {batch_size},
                                                     &output_tree_ids_t));
    auto output_tree_ids = output_tree_ids_t->vec<int32>();

    Tensor* output_node_ids_t = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output("node_ids", {batch_size},
                                                     &output_node_ids_t));
    auto output_node_ids = output_node_ids_t->vec<int32>();

    // Indicate that the latest tree was used.
    const int32 latest_tree = resource->num_trees() - 1;

    if (latest_tree < 0) {
      // Ensemble was empty. Output the very first node.
      output_node_ids.setZero();
      output_tree_ids = cached_tree_ids;
      // All the predictions are zeros.
      output_partial_logits.setZero();
    } else {
      output_tree_ids.setConstant(latest_tree);
      auto do_work = [&resource, &batch_bucketized_features, &cached_tree_ids,
                      &cached_node_ids, &output_partial_logits,
                      &output_node_ids, batch_size,
                      latest_tree](int32 start, int32 end) {
        for (int32 i = start; i < end; ++i) {
          int32 tree_id = cached_tree_ids(i);
          int32 node_id = cached_node_ids(i);
          float partial_tree_logit = 0.0;

          if (node_id >= 0) {
            // If the tree was pruned, returns the node id into which the
            // current_node_id was pruned, as well the correction of the cached
            // logit prediction.
            resource->GetPostPruneCorrection(tree_id, node_id, &node_id,
                                             &partial_tree_logit);
            // Logic in the loop adds the cached node value again if it is a
            // leaf. If it is not a leaf anymore we need to subtract the old
            // node's value. The following logic handles both of these cases.
            partial_tree_logit -= resource->node_value(tree_id, node_id);
          } else {
            // No cache exists, start from the very first node.
            node_id = 0;
          }
          float partial_all_logit = 0.0;
          while (true) {
            if (resource->is_leaf(tree_id, node_id)) {
              partial_tree_logit += resource->node_value(tree_id, node_id);

              // Tree is done
              partial_all_logit +=
                  resource->GetTreeWeight(tree_id) * partial_tree_logit;
              partial_tree_logit = 0.0;
              // Stop if it was the latest tree.
              if (tree_id == latest_tree) {
                break;
              }
              // Move onto other trees.
              ++tree_id;
              node_id = 0;
            } else {
              node_id = resource->next_node(tree_id, node_id, i,
                                            batch_bucketized_features);
            }
          }
          output_node_ids(i) = node_id;
          output_partial_logits(i, 0) = partial_all_logit;
        }
      };
      // 30 is the magic number. The actual value might be a function of (the
      // number of layers) * (cpu cycles spent on each layer), but this value
      // would work for many cases. May be tuned later.
      const int64 cost = 30;
      thread::ThreadPool* const worker_threads =
          context->device()->tensorflow_cpu_worker_threads()->workers;
      Shard(worker_threads->NumThreads(), worker_threads, batch_size,
            /*cost_per_unit=*/cost, do_work);
    }
  }

 private:
  int32 logits_dimension_;         // the size of the output prediction vector.
  int32 num_bucketized_features_;  // Indicates the number of features.
};

REGISTER_KERNEL_BUILDER(Name("BoostedTreesTrainingPredict").Device(DEVICE_CPU),
                        BoostedTreesTrainingPredictOp);

// The Op to get the predictions at the evaluation/inference time.
class BoostedTreesPredictOp : public OpKernel {
 public:
  explicit BoostedTreesPredictOp(OpKernelConstruction* const context)
      : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("num_bucketized_features",
                                             &num_bucketized_features_));
    OP_REQUIRES_OK(context,
                   context->GetAttr("logits_dimension", &logits_dimension_));
    OP_REQUIRES(context, logits_dimension_ == 1,
                errors::InvalidArgument(
                    "Currently only one dimensional outputs are supported."));
  }

  void Compute(OpKernelContext* const context) override {
    BoostedTreesEnsembleResource* resource;
    // Get the resource.
    OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
                                           &resource));
    // Release the reference to the resource once we're done using it.
    core::ScopedUnref unref_me(resource);

    // Get the inputs.
    OpInputList bucketized_features_list;
    OP_REQUIRES_OK(context, context->input_list("bucketized_features",
                                                &bucketized_features_list));
    std::vector<tensorflow::TTypes<int32>::ConstVec> batch_bucketized_features;
    batch_bucketized_features.reserve(bucketized_features_list.size());
    for (const Tensor& tensor : bucketized_features_list) {
      batch_bucketized_features.emplace_back(tensor.vec<int32>());
    }
    const int batch_size = batch_bucketized_features[0].size();

    // Allocate outputs.
    Tensor* output_logits_t = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(
                                "logits", {batch_size, logits_dimension_},
                                &output_logits_t));
    auto output_logits = output_logits_t->matrix<float>();

    // Return zero logits if it's an empty ensemble.
    if (resource->num_trees() <= 0) {
      output_logits.setZero();
      return;
    }

    const int32 last_tree = resource->num_trees() - 1;

    auto do_work = [&resource, &batch_bucketized_features, &output_logits,
                    batch_size, last_tree](int32 start, int32 end) {
      for (int32 i = start; i < end; ++i) {
        float tree_logit = 0.0;
        int32 tree_id = 0;
        int32 node_id = 0;
        while (true) {
          if (resource->is_leaf(tree_id, node_id)) {
            tree_logit += resource->GetTreeWeight(tree_id) *
                          resource->node_value(tree_id, node_id);

            // Stop if it was the last tree.
            if (tree_id == last_tree) {
              break;
            }
            // Move onto other trees.
            ++tree_id;
            node_id = 0;
          } else {
            node_id = resource->next_node(tree_id, node_id, i,
                                          batch_bucketized_features);
          }
        }
        output_logits(i, 0) = tree_logit;
      }
    };
    // 10 is the magic number. The actual number might depend on (the number of
    // layers in the trees) and (cpu cycles spent on each layer), but this
    // value would work for many cases. May be tuned later.
    const int64 cost = (last_tree + 1) * 10;
    thread::ThreadPool* const worker_threads =
        context->device()->tensorflow_cpu_worker_threads()->workers;
    Shard(worker_threads->NumThreads(), worker_threads, batch_size,
          /*cost_per_unit=*/cost, do_work);
  }

 private:
  int32
      logits_dimension_;  // Indicates the size of the output prediction vector.
  int32 num_bucketized_features_;  // Indicates the number of features.
};

REGISTER_KERNEL_BUILDER(Name("BoostedTreesPredict").Device(DEVICE_CPU),
                        BoostedTreesPredictOp);

// The Op that returns debugging/model interpretability outputs for each
// example. Currently it outputs the split feature ids and logits after each
// split along the decision path for each example. This will be used to compute
// directional feature contributions at predict time for an arbitrary activation
// function.
// TODO(crawles): return in proto 1) Node IDs for ensemble prediction path
// 2) Leaf node IDs.
class BoostedTreesExampleDebugOutputsOp : public OpKernel {
 public:
  explicit BoostedTreesExampleDebugOutputsOp(
      OpKernelConstruction* const context)
      : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("num_bucketized_features",
                                             &num_bucketized_features_));
    OP_REQUIRES_OK(context,
                   context->GetAttr("logits_dimension", &logits_dimension_));
    OP_REQUIRES(context, logits_dimension_ == 1,
                errors::InvalidArgument(
                    "Currently only one dimensional outputs are supported."));
  }

  void Compute(OpKernelContext* const context) override {
    BoostedTreesEnsembleResource* resource;
    // Get the resource.
    OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
                                           &resource));
    // Release the reference to the resource once we're done using it.
    core::ScopedUnref unref_me(resource);

    // Get the inputs.
    OpInputList bucketized_features_list;
    OP_REQUIRES_OK(context, context->input_list("bucketized_features",
                                                &bucketized_features_list));
    std::vector<tensorflow::TTypes<int32>::ConstVec> batch_bucketized_features;
    batch_bucketized_features.reserve(bucketized_features_list.size());
    for (const Tensor& tensor : bucketized_features_list) {
      batch_bucketized_features.emplace_back(tensor.vec<int32>());
    }
    const int batch_size = batch_bucketized_features[0].size();

    // We need to get the feature ids used for splitting and the logits after
    // each split. We will use these to calulate the changes in the prediction
    // (contributions) for an arbitrary activation function (done in Python) and
    // attribute them to the associated feature ids. We will store these in
    // a proto below.
    Tensor* output_debug_info_t = nullptr;
    OP_REQUIRES_OK(
        context, context->allocate_output("examples_debug_outputs_serialized",
                                          {batch_size}, &output_debug_info_t));
    // Will contain serialized protos, per example.
    auto output_debug_info = output_debug_info_t->flat<string>();
    const int32 last_tree = resource->num_trees() - 1;

    // For each given example, traverse through all trees keeping track of the
    // features used to split and the associated logits at each point along the
    // path. Note: feature_ids has one less value than logits_path because the
    // first value of each logit path will be the bias.
    auto do_work = [&resource, &batch_bucketized_features, &output_debug_info,
                    batch_size, last_tree](int32 start, int32 end) {
      for (int32 i = start; i < end; ++i) {
        // Proto to store debug outputs, per example.
        boosted_trees::DebugOutput example_debug_info;
        // Initial bias prediction. E.g., prediction based off training mean.
        example_debug_info.add_logits_path(resource->GetTreeWeight(0) *
                                           resource->node_value(0, 0));
        int32 node_id = 0;
        int32 tree_id = 0;
        int32 feature_id;
        float tree_logit;
        float past_trees_logit = 0;  // Sum of leaf logits from prior trees.
        // Populate proto.
        while (tree_id <= last_tree) {
          // Feature id used to split.
          feature_id = resource->feature_id(tree_id, node_id);
          example_debug_info.add_feature_ids(feature_id);
          // Get logit after split.
          node_id = resource->next_node(tree_id, node_id, i,
                                        batch_bucketized_features);
          tree_logit = resource->GetTreeWeight(tree_id) *
                       resource->node_value(tree_id, node_id);
          // Output logit incorporates sum of leaf logits from prior trees.
          example_debug_info.add_logits_path(tree_logit + past_trees_logit);
          if (resource->is_leaf(tree_id, node_id)) {
            // Move onto other trees.
            past_trees_logit += tree_logit;
            ++tree_id;
            node_id = 0;
          }
        }
        // Set output as serialized proto containing debug info.
        string serialized = example_debug_info.SerializeAsString();
        output_debug_info(i) = serialized;
      }
    };

    // 10 is the magic number. The actual number might depend on (the number of
    // layers in the trees) and (cpu cycles spent on each layer), but this
    // value would work for many cases. May be tuned later.
    const int64 cost = (last_tree + 1) * 10;
    thread::ThreadPool* const worker_threads =
        context->device()->tensorflow_cpu_worker_threads()->workers;
    Shard(worker_threads->NumThreads(), worker_threads, batch_size,
          /*cost_per_unit=*/cost, do_work);
  }

 private:
  int32 logits_dimension_;  // Indicates dimension of logits in the tree nodes.
  int32 num_bucketized_features_;  // Indicates the number of features.
};

REGISTER_KERNEL_BUILDER(
    Name("BoostedTreesExampleDebugOutputs").Device(DEVICE_CPU),
    BoostedTreesExampleDebugOutputsOp);

}  // namespace tensorflow