aboutsummaryrefslogtreecommitdiff
path: root/llvm/tools/llvm-exegesis/lib/LatencyBenchmarkRunner.cpp
blob: 684868cf23e8f8f49aa6c098f42d9e97893b893e (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
//===-- LatencyBenchmarkRunner.cpp ------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "LatencyBenchmarkRunner.h"

#include "BenchmarkRunner.h"
#include "Target.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include <algorithm>
#include <cmath>

#define DEBUG_TYPE "exegesis-latency-benchmarkrunner"

namespace llvm {
namespace exegesis {

LatencyBenchmarkRunner::LatencyBenchmarkRunner(
    const LLVMState &State, Benchmark::ModeE Mode,
    BenchmarkPhaseSelectorE BenchmarkPhaseSelector,
    Benchmark::ResultAggregationModeE ResultAgg, ExecutionModeE ExecutionMode,
    ArrayRef<ValidationEvent> ValCounters, unsigned BenchmarkRepeatCount)
    : BenchmarkRunner(State, Mode, BenchmarkPhaseSelector, ExecutionMode,
                      ValCounters) {
  assert((Mode == Benchmark::Latency || Mode == Benchmark::InverseThroughput) &&
         "invalid mode");
  ResultAggMode = ResultAgg;
  NumMeasurements = BenchmarkRepeatCount;
}

LatencyBenchmarkRunner::~LatencyBenchmarkRunner() = default;

static double computeVariance(const SmallVector<int64_t, 4> &Values) {
  if (Values.empty())
    return 0.0;
  double Sum = std::accumulate(Values.begin(), Values.end(), 0.0);

  const double Mean = Sum / Values.size();
  double Ret = 0;
  for (const auto &V : Values) {
    double Delta = V - Mean;
    Ret += Delta * Delta;
  }
  return Ret / Values.size();
}

static int64_t findMin(const SmallVector<int64_t, 4> &Values) {
  if (Values.empty())
    return 0;
  return *llvm::min_element(Values);
}

static int64_t findMax(const SmallVector<int64_t, 4> &Values) {
  if (Values.empty())
    return 0;
  return *llvm::max_element(Values);
}

static int64_t findMean(const SmallVector<int64_t, 4> &Values) {
  if (Values.empty())
    return 0;
  return std::accumulate(Values.begin(), Values.end(), 0.0) /
         static_cast<double>(Values.size());
}

Expected<std::vector<BenchmarkMeasure>> LatencyBenchmarkRunner::runMeasurements(
    const FunctionExecutor &Executor) const {
  // Cycle measurements include some overhead from the kernel. Repeat the
  // measure several times and return the aggregated value, as specified by
  // ResultAggMode.
  SmallVector<int64_t, 4> AccumulatedValues;
  double MinVariance = std::numeric_limits<double>::infinity();
  const PfmCountersInfo &PCI = State.getPfmCounters();
  const char *CounterName = PCI.CycleCounter;

  SmallVector<const char *> ValCountersToRun;
  Error ValCounterErr = getValidationCountersToRun(ValCountersToRun);
  if (ValCounterErr)
    return std::move(ValCounterErr);

  SmallVector<int64_t> ValCounterValues(ValCountersToRun.size(), 0);
  // Values count for each run.
  int ValuesCount = 0;
  for (size_t I = 0; I < NumMeasurements; ++I) {
    SmallVector<int64_t> IterationValCounterValues(ValCountersToRun.size(), -1);
    auto ExpectedCounterValues = Executor.runAndSample(
        CounterName, ValCountersToRun, IterationValCounterValues);
    if (!ExpectedCounterValues)
      return ExpectedCounterValues.takeError();
    ValuesCount = ExpectedCounterValues.get().size();
    if (ValuesCount == 1) {
      LLVM_DEBUG(dbgs() << "Latency value: " << ExpectedCounterValues.get()[0]
                        << "\n");
      AccumulatedValues.push_back(ExpectedCounterValues.get()[0]);
    } else {
      // We'll keep the reading with lowest variance (ie., most stable)
      double Variance = computeVariance(*ExpectedCounterValues);
      if (MinVariance > Variance) {
        AccumulatedValues = std::move(ExpectedCounterValues.get());
        MinVariance = Variance;
      }
    }

    for (size_t I = 0; I < ValCounterValues.size(); ++I) {
      LLVM_DEBUG(dbgs() << getValidationEventName(ValidationCounters[I]) << ": "
                        << IterationValCounterValues[I] << "\n");
      ValCounterValues[I] += IterationValCounterValues[I];
    }
  }

  std::map<ValidationEvent, int64_t> ValidationInfo;
  for (size_t I = 0; I < ValidationCounters.size(); ++I)
    ValidationInfo[ValidationCounters[I]] = ValCounterValues[I];

  std::string ModeName;
  switch (Mode) {
  case Benchmark::Latency:
    ModeName = "latency";
    break;
  case Benchmark::InverseThroughput:
    ModeName = "inverse_throughput";
    break;
  default:
    break;
  }

  switch (ResultAggMode) {
  case Benchmark::MinVariance: {
    if (ValuesCount == 1)
      errs() << "Each sample only has one value. result-aggregation-mode "
                "of min-variance is probably non-sensical\n";
    std::vector<BenchmarkMeasure> Result;
    Result.reserve(AccumulatedValues.size());
    for (const int64_t Value : AccumulatedValues)
      Result.push_back(
          BenchmarkMeasure::Create(ModeName, Value, ValidationInfo));
    return std::move(Result);
  }
  case Benchmark::Min: {
    std::vector<BenchmarkMeasure> Result;
    Result.push_back(BenchmarkMeasure::Create(
        ModeName, findMin(AccumulatedValues), ValidationInfo));
    return std::move(Result);
  }
  case Benchmark::Max: {
    std::vector<BenchmarkMeasure> Result;
    Result.push_back(BenchmarkMeasure::Create(
        ModeName, findMax(AccumulatedValues), ValidationInfo));
    return std::move(Result);
  }
  case Benchmark::Mean: {
    std::vector<BenchmarkMeasure> Result;
    Result.push_back(BenchmarkMeasure::Create(
        ModeName, findMean(AccumulatedValues), ValidationInfo));
    return std::move(Result);
  }
  }
  return make_error<Failure>(Twine("Unexpected benchmark mode(")
                                 .concat(std::to_string(Mode))
                                 .concat(" and unexpected ResultAggMode ")
                                 .concat(std::to_string(ResultAggMode)));
}

} // namespace exegesis
} // namespace llvm