File: perplexity_op.cc

package info (click to toggle)
pytorch 1.7.1-7
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 80,340 kB
  • sloc: cpp: 670,830; python: 343,991; ansic: 67,845; asm: 5,503; sh: 2,924; java: 2,888; xml: 266; makefile: 244; ruby: 148; yacc: 144; objc: 51; lex: 44
file content (39 lines) | stat: -rw-r--r-- 1,259 bytes parent folder | download
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
#include "caffe2/operators/perplexity_op.h"

namespace caffe2 {

template <>
bool PerplexityOp<float, CPUContext>::RunOnDevice() {
  auto& X = Input(0);

  DCHECK_EQ(X.dim(), 1);
  int N = X.dim32(0);

  auto* Y = Output(0, vector<int64_t>(), at::dtype<float>());
  const auto* Xdata = X.data<float>();

  float perplexity = 1.0;
  for (int i = 0; i < N; ++i) {
    perplexity *= pow(Xdata[i], -1.0/N);
  }
  *(Y->template mutable_data<float>()) = perplexity;
  return true;
}

REGISTER_CPU_OPERATOR(Perplexity, PerplexityOp<float, CPUContext>);

OPERATOR_SCHEMA(Perplexity).NumInputs(1).NumOutputs(1)
.SetDoc(R"DOC(
Perplexity calculates how well a probability distribution predicts a sample.
Perplexity takes a 1-D tensor containing a batch of probabilities. Each value
in the tensor belongs to a different sample and represents the probability of
the model predicting the true label for that sample. The operator returns a
single (float) perplexity value for the batch.
)DOC")
.Input(0, "probabilities", "The input data as Tensor. It contains a batch of"
       "true label or target probabilities")
.Output(0, "output", "The output- a single (float) perplexity value for the "
        "batch");

SHOULD_NOT_DO_GRADIENT(Perplexity);
}  // namespace caffe2