reid from https://github.com/michuanhaohao/reid-strong-baseline
zhangmeng
2020-01-17 f7c4a3cfd07adede3308f8d9d3d7315427d90a7c
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
#ifndef CAFFE2_OPERATORS_WHILE_OP_H_
#define CAFFE2_OPERATORS_WHILE_OP_H_
 
#include "caffe2/core/context.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
 
namespace caffe2 {
 
template <class Context>
class WhileOp final : public Operator<Context> {
 public:
  explicit WhileOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws) {
    CAFFE_ENFORCE(
        this->template HasSingleArgumentOfType<NetDef>("loop_net"),
        "loop_net must be specified in While operator");
    loop_net_def_ =
        this->template GetSingleArgument<NetDef>("loop_net", NetDef());
    loop_net_ = CreateNet(loop_net_def_, ws);
    CAFFE_ENFORCE(loop_net_, "Failed to initialize loop subnet");
 
    cond_net_ = nullptr;
    bool has_cond_net =
        this->template HasSingleArgumentOfType<NetDef>("cond_net");
    if (has_cond_net) {
      cond_net_def_ =
          this->template GetSingleArgument<NetDef>("cond_net", NetDef());
      cond_net_ = CreateNet(cond_net_def_, ws);
      CAFFE_ENFORCE(cond_net_, "Failed to initialize condition subnet");
    }
  }
 
  USE_OPERATOR_CONTEXT_FUNCTIONS;
 
  bool RunOnDevice() override {
    CAFFE_ENFORCE(
        this->InputIsTensorType(0, Context::GetDeviceType()),
        "Invalid condition in While operator: tensor expected");
 
    const auto& condition = Input(0);
    CAFFE_ENFORCE_EQ(
        condition.numel(),
        1,
        "Invalid condition tensor in While operator: single value expected");
 
    while (true) {
      if (cond_net_ && !cond_net_->Run()) {
        return false;
      }
      if (!*condition.template data<bool>()) {
        return true;
      }
      if (!loop_net_->Run()) {
        return false;
      }
    }
 
    return true;
  }
 
 private:
  NetDef loop_net_def_;
  std::unique_ptr<NetBase> loop_net_;
 
  NetDef cond_net_def_;
  std::unique_ptr<NetBase> cond_net_;
};
 
} // namespace caffe2
 
#endif // CAFFE2_OPERATORS_WHILE_OP_H_