Caffe2 - C++ API
A deep learning, cross platform ML framework
softmax_with_loss_op.h
1 #ifndef SOFTMAX_WITH_LOSS_OP_H_
2 #define SOFTMAX_WITH_LOSS_OP_H_
3 
4 #include "caffe2/core/context.h"
5 #include "caffe2/core/logging.h"
6 #include "caffe2/core/operator.h"
7 #include "caffe2/utils/math.h"
8 
9 namespace caffe2 {
10 
11 template <typename T, class Context>
12 class SoftmaxWithLossOp final : public Operator<Context> {
13  public:
14  template <class... Args>
15  explicit SoftmaxWithLossOp(Args&&... args)
16  : Operator<Context>(std::forward<Args>(args)...),
17  scale_(this->template GetSingleArgument<float>("scale", 1.)),
18  label_prob_mode_(
19  this->template GetSingleArgument<int>("label_prob", 0)),
20  order_(StringToStorageOrder(
21  this->template GetSingleArgument<string>("order", "NCHW"))),
22  axis_(this->template GetSingleArgument<int>("axis", 1)) {
23  CAFFE_ENFORCE(scale_ >= 0);
24  CAFFE_ENFORCE_EQ(
25  order_, StorageOrder::NCHW, "Only NCHW order is supported right now.");
26  }
27  USE_OPERATOR_CONTEXT_FUNCTIONS;
28 
29  bool RunOnDevice() override;
30 
31  protected:
32  float scale_;
33  int label_prob_mode_;
34  StorageOrder order_;
35  int axis_;
36 
37  Tensor losses_; // Per example loss
38  Tensor rowmax_; // per example row max
39  Tensor weights_; // unignored weights
40  Tensor sum_multiplier_; // Vector of ones for summing via dot prod
41  Tensor total_weight_ptr_;
42  // passed to a function
43  Tensor scratch_{Context::GetDeviceType()};
44 };
45 
46 template <typename T, class Context>
47 class SoftmaxWithLossGradientOp final : public Operator<Context> {
48  public:
49  template <class... Args>
50  explicit SoftmaxWithLossGradientOp(Args&&... args)
51  : Operator<Context>(std::forward<Args>(args)...),
52  scale_(this->template GetSingleArgument<float>("scale", 1.)),
53  label_prob_mode_(
54  this->template GetSingleArgument<int>("label_prob", 0)),
55  order_(StringToStorageOrder(
56  this->template GetSingleArgument<string>("order", "NCHW"))),
57  only_loss_(this->template GetSingleArgument<bool>("only_loss", false)),
58  axis_(this->template GetSingleArgument<int>("axis", 1)) {
59  CAFFE_ENFORCE(scale_ >= 0);
60  CAFFE_ENFORCE_EQ(
61  order_, StorageOrder::NCHW, "Only NCHW order is supported right now.");
62  }
63  USE_OPERATOR_CONTEXT_FUNCTIONS;
64 
65  bool RunOnDevice() override;
66 
67  protected:
68  float scale_;
69  int label_prob_mode_;
70  // not used?
71  Tensor sum_multiplier_{Context::GetDeviceType()};
72  Tensor weights_; // unignored weights
73  Tensor total_weight_ptr_;
74  StorageOrder order_;
75  bool only_loss_;
76  int axis_;
77  Tensor scratch_{Context::GetDeviceType()};
78 };
79 
80 } // namespace caffe2
81 
82 #endif // SOFTMAX_WITH_LOSS_OP_H_
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13