blob: 36e6c5b110ffe0a69ba97a01ccb554af649d8bc1 [file] [log] [blame]
Clement Courbet96715412018-05-07 09:09:48 +00001//===-- Clustering.cpp ------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Clement Courbet96715412018-05-07 09:09:48 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Clustering.h"
Clement Courbet176388c2019-01-02 09:21:00 +000010#include "llvm/ADT/SetVector.h"
Roman Lebedev8aecb0c2018-11-19 13:28:22 +000011#include "llvm/ADT/SmallVector.h"
Clement Courbet96715412018-05-07 09:09:48 +000012#include <string>
Clement Courbet96715412018-05-07 09:09:48 +000013
Fangrui Song32401af2018-10-22 17:10:47 +000014namespace llvm {
Clement Courbet96715412018-05-07 09:09:48 +000015namespace exegesis {
16
17// The clustering problem has the following characteristics:
18// (A) - Low dimension (dimensions are typically proc resource units,
19// typically < 10).
20// (B) - Number of points : ~thousands (points are measurements of an MCInst)
21// (C) - Number of clusters: ~tens.
22// (D) - The number of clusters is not known /a priory/.
Clement Courbetdffc4ca2018-05-14 11:35:37 +000023// (E) - The amount of noise is relatively small.
Clement Courbet96715412018-05-07 09:09:48 +000024// The problem is rather small. In terms of algorithms, (D) disqualifies
25// k-means and makes algorithms such as DBSCAN[1] or OPTICS[2] more applicable.
26//
27// We've used DBSCAN here because it's simple to implement. This is a pretty
28// straightforward and inefficient implementation of the pseudocode in [2].
29//
30// [1] https://en.wikipedia.org/wiki/DBSCAN
31// [2] https://en.wikipedia.org/wiki/OPTICS_algorithm
32
Clement Courbet96715412018-05-07 09:09:48 +000033// Finds the points at distance less than sqrt(EpsilonSquared) of Q (not
34// including Q).
Roman Lebedev666d8552018-11-19 13:28:31 +000035void InstructionBenchmarkClustering::rangeQuery(
Roman Lebedev71fdb572018-11-19 13:28:41 +000036 const size_t Q, std::vector<size_t> &Neighbors) const {
Roman Lebedev666d8552018-11-19 13:28:31 +000037 Neighbors.clear();
Roman Lebedev71fdb572018-11-19 13:28:41 +000038 Neighbors.reserve(Points_.size() - 1); // The Q itself isn't a neighbor.
Clement Courbet72287212018-06-04 11:11:55 +000039 const auto &QMeasurements = Points_[Q].Measurements;
40 for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
Clement Courbet96715412018-05-07 09:09:48 +000041 if (P == Q)
42 continue;
Clement Courbet72287212018-06-04 11:11:55 +000043 const auto &PMeasurements = Points_[P].Measurements;
Clement Courbet96715412018-05-07 09:09:48 +000044 if (PMeasurements.empty()) // Error point.
45 continue;
Clement Courbet72287212018-06-04 11:11:55 +000046 if (isNeighbour(PMeasurements, QMeasurements)) {
Clement Courbet96715412018-05-07 09:09:48 +000047 Neighbors.push_back(P);
48 }
49 }
Clement Courbet96715412018-05-07 09:09:48 +000050}
51
Clement Courbet37f0ca02018-05-15 12:08:00 +000052InstructionBenchmarkClustering::InstructionBenchmarkClustering(
Clement Courbet72287212018-06-04 11:11:55 +000053 const std::vector<InstructionBenchmark> &Points,
54 const double EpsilonSquared)
55 : Points_(Points), EpsilonSquared_(EpsilonSquared),
56 NoiseCluster_(ClusterId::noise()), ErrorCluster_(ClusterId::error()) {}
Clement Courbet96715412018-05-07 09:09:48 +000057
Clement Courbet37f0ca02018-05-15 12:08:00 +000058llvm::Error InstructionBenchmarkClustering::validateAndSetup() {
59 ClusterIdForPoint_.resize(Points_.size());
Clement Courbet96715412018-05-07 09:09:48 +000060 // Mark erroneous measurements out.
61 // All points must have the same number of dimensions, in the same order.
62 const std::vector<BenchmarkMeasure> *LastMeasurement = nullptr;
Clement Courbet37f0ca02018-05-15 12:08:00 +000063 for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
64 const auto &Point = Points_[P];
Clement Courbet96715412018-05-07 09:09:48 +000065 if (!Point.Error.empty()) {
66 ClusterIdForPoint_[P] = ClusterId::error();
67 ErrorCluster_.PointIndices.push_back(P);
68 continue;
69 }
70 const auto *CurMeasurement = &Point.Measurements;
71 if (LastMeasurement) {
72 if (LastMeasurement->size() != CurMeasurement->size()) {
73 return llvm::make_error<llvm::StringError>(
74 "inconsistent measurement dimensions",
75 llvm::inconvertibleErrorCode());
76 }
77 for (size_t I = 0, E = LastMeasurement->size(); I < E; ++I) {
78 if (LastMeasurement->at(I).Key != CurMeasurement->at(I).Key) {
79 return llvm::make_error<llvm::StringError>(
80 "inconsistent measurement dimensions keys",
81 llvm::inconvertibleErrorCode());
82 }
83 }
84 }
85 LastMeasurement = CurMeasurement;
86 }
87 if (LastMeasurement) {
88 NumDimensions_ = LastMeasurement->size();
89 }
90 return llvm::Error::success();
91}
92
Clement Courbet72287212018-06-04 11:11:55 +000093void InstructionBenchmarkClustering::dbScan(const size_t MinPts) {
Clement Courbet176388c2019-01-02 09:21:00 +000094 std::vector<size_t> Neighbors; // Persistent buffer to avoid allocs.
95 for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
Clement Courbet96715412018-05-07 09:09:48 +000096 if (!ClusterIdForPoint_[P].isUndef())
97 continue; // Previously processed in inner loop.
Roman Lebedev666d8552018-11-19 13:28:31 +000098 rangeQuery(P, Neighbors);
Clement Courbet96715412018-05-07 09:09:48 +000099 if (Neighbors.size() + 1 < MinPts) { // Density check.
100 // The region around P is not dense enough to create a new cluster, mark
101 // as noise for now.
102 ClusterIdForPoint_[P] = ClusterId::noise();
103 continue;
104 }
105
106 // Create a new cluster, add P.
107 Clusters_.emplace_back(ClusterId::makeValid(Clusters_.size()));
108 Cluster &CurrentCluster = Clusters_.back();
109 ClusterIdForPoint_[P] = CurrentCluster.Id; /* Label initial point */
110 CurrentCluster.PointIndices.push_back(P);
111
Clement Courbet176388c2019-01-02 09:21:00 +0000112 // Process P's neighbors.
113 llvm::SetVector<size_t, std::deque<size_t>> ToProcess;
114 ToProcess.insert(Neighbors.begin(), Neighbors.end());
115 while (!ToProcess.empty()) {
116 // Retrieve a point from the set.
117 const size_t Q = *ToProcess.begin();
118 ToProcess.erase(ToProcess.begin());
Clement Courbet96715412018-05-07 09:09:48 +0000119
Clement Courbet176388c2019-01-02 09:21:00 +0000120 if (ClusterIdForPoint_[Q].isNoise()) {
121 // Change noise point to border point.
122 ClusterIdForPoint_[Q] = CurrentCluster.Id;
123 CurrentCluster.PointIndices.push_back(Q);
Clement Courbet96715412018-05-07 09:09:48 +0000124 continue;
Clement Courbet176388c2019-01-02 09:21:00 +0000125 }
126 if (!ClusterIdForPoint_[Q].isUndef()) {
127 continue; // Previously processed.
128 }
129 // Add Q to the current custer.
130 ClusterIdForPoint_[Q] = CurrentCluster.Id;
131 CurrentCluster.PointIndices.push_back(Q);
132 // And extend to the neighbors of Q if the region is dense enough.
133 rangeQuery(Q, Neighbors);
134 if (Neighbors.size() + 1 >= MinPts) {
135 ToProcess.insert(Neighbors.begin(), Neighbors.end());
136 }
Clement Courbet96715412018-05-07 09:09:48 +0000137 }
138 }
Clement Courbet176388c2019-01-02 09:21:00 +0000139 // assert(Neighbors.capacity() == (Points_.size() - 1));
140 // ^ True, but it is not quaranteed to be true in all the cases.
Clement Courbet96715412018-05-07 09:09:48 +0000141
142 // Add noisy points to noise cluster.
Clement Courbet176388c2019-01-02 09:21:00 +0000143 for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
144 if (ClusterIdForPoint_[P].isNoise()) {
Clement Courbet96715412018-05-07 09:09:48 +0000145 NoiseCluster_.PointIndices.push_back(P);
Clement Courbet176388c2019-01-02 09:21:00 +0000146 }
147 }
Clement Courbet96715412018-05-07 09:09:48 +0000148}
149
150llvm::Expected<InstructionBenchmarkClustering>
151InstructionBenchmarkClustering::create(
152 const std::vector<InstructionBenchmark> &Points, const size_t MinPts,
153 const double Epsilon) {
Clement Courbet72287212018-06-04 11:11:55 +0000154 InstructionBenchmarkClustering Clustering(Points, Epsilon * Epsilon);
Clement Courbet37f0ca02018-05-15 12:08:00 +0000155 if (auto Error = Clustering.validateAndSetup()) {
Clement Courbetcdb0eb82018-05-15 12:38:06 +0000156 return std::move(Error);
Clement Courbet96715412018-05-07 09:09:48 +0000157 }
158 if (Clustering.ErrorCluster_.PointIndices.size() == Points.size()) {
159 return Clustering; // Nothing to cluster.
160 }
161
Clement Courbet72287212018-06-04 11:11:55 +0000162 Clustering.dbScan(MinPts);
Clement Courbet96715412018-05-07 09:09:48 +0000163 return Clustering;
164}
165
166} // namespace exegesis
Fangrui Song32401af2018-10-22 17:10:47 +0000167} // namespace llvm