Clustering.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. //===-- Clustering.cpp ------------------------------------------*- C++ -*-===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "Clustering.h"
  9. #include "Error.h"
  10. #include "llvm/ADT/SetVector.h"
  11. #include "llvm/ADT/SmallSet.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include <algorithm>
  14. #include <string>
  15. #include <vector>
  16. #include <deque>
  17. namespace llvm {
  18. namespace exegesis {
  19. // The clustering problem has the following characteristics:
  20. // (A) - Low dimension (dimensions are typically proc resource units,
  21. // typically < 10).
  22. // (B) - Number of points : ~thousands (points are measurements of an MCInst)
  23. // (C) - Number of clusters: ~tens.
  24. // (D) - The number of clusters is not known /a priory/.
  25. // (E) - The amount of noise is relatively small.
  26. // The problem is rather small. In terms of algorithms, (D) disqualifies
  27. // k-means and makes algorithms such as DBSCAN[1] or OPTICS[2] more applicable.
  28. //
  29. // We've used DBSCAN here because it's simple to implement. This is a pretty
  30. // straightforward and inefficient implementation of the pseudocode in [2].
  31. //
  32. // [1] https://en.wikipedia.org/wiki/DBSCAN
  33. // [2] https://en.wikipedia.org/wiki/OPTICS_algorithm
  34. // Finds the points at distance less than sqrt(EpsilonSquared) of Q (not
  35. // including Q).
  36. void InstructionBenchmarkClustering::rangeQuery(
  37. const size_t Q, std::vector<size_t> &Neighbors) const {
  38. Neighbors.clear();
  39. Neighbors.reserve(Points_.size() - 1); // The Q itself isn't a neighbor.
  40. const auto &QMeasurements = Points_[Q].Measurements;
  41. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
  42. if (P == Q)
  43. continue;
  44. const auto &PMeasurements = Points_[P].Measurements;
  45. if (PMeasurements.empty()) // Error point.
  46. continue;
  47. if (isNeighbour(PMeasurements, QMeasurements,
  48. AnalysisClusteringEpsilonSquared_)) {
  49. Neighbors.push_back(P);
  50. }
  51. }
  52. }
  53. // Given a set of points, checks that all the points are neighbours
  54. // up to AnalysisClusteringEpsilon. This is O(2*N).
  55. bool InstructionBenchmarkClustering::areAllNeighbours(
  56. ArrayRef<size_t> Pts) const {
  57. // First, get the centroid of this group of points. This is O(N).
  58. SchedClassClusterCentroid G;
  59. for_each(Pts, [this, &G](size_t P) {
  60. assert(P < Points_.size());
  61. ArrayRef<BenchmarkMeasure> Measurements = Points_[P].Measurements;
  62. if (Measurements.empty()) // Error point.
  63. return;
  64. G.addPoint(Measurements);
  65. });
  66. const std::vector<BenchmarkMeasure> Centroid = G.getAsPoint();
  67. // Since we will be comparing with the centroid, we need to halve the epsilon.
  68. double AnalysisClusteringEpsilonHalvedSquared =
  69. AnalysisClusteringEpsilonSquared_ / 4.0;
  70. // And now check that every point is a neighbour of the centroid. Also O(N).
  71. return all_of(
  72. Pts, [this, &Centroid, AnalysisClusteringEpsilonHalvedSquared](size_t P) {
  73. assert(P < Points_.size());
  74. const auto &PMeasurements = Points_[P].Measurements;
  75. if (PMeasurements.empty()) // Error point.
  76. return true; // Pretend that error point is a neighbour.
  77. return isNeighbour(PMeasurements, Centroid,
  78. AnalysisClusteringEpsilonHalvedSquared);
  79. });
  80. }
  81. InstructionBenchmarkClustering::InstructionBenchmarkClustering(
  82. const std::vector<InstructionBenchmark> &Points,
  83. const double AnalysisClusteringEpsilonSquared)
  84. : Points_(Points),
  85. AnalysisClusteringEpsilonSquared_(AnalysisClusteringEpsilonSquared),
  86. NoiseCluster_(ClusterId::noise()), ErrorCluster_(ClusterId::error()) {}
  87. Error InstructionBenchmarkClustering::validateAndSetup() {
  88. ClusterIdForPoint_.resize(Points_.size());
  89. // Mark erroneous measurements out.
  90. // All points must have the same number of dimensions, in the same order.
  91. const std::vector<BenchmarkMeasure> *LastMeasurement = nullptr;
  92. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
  93. const auto &Point = Points_[P];
  94. if (!Point.Error.empty()) {
  95. ClusterIdForPoint_[P] = ClusterId::error();
  96. ErrorCluster_.PointIndices.push_back(P);
  97. continue;
  98. }
  99. const auto *CurMeasurement = &Point.Measurements;
  100. if (LastMeasurement) {
  101. if (LastMeasurement->size() != CurMeasurement->size()) {
  102. return make_error<ClusteringError>(
  103. "inconsistent measurement dimensions");
  104. }
  105. for (size_t I = 0, E = LastMeasurement->size(); I < E; ++I) {
  106. if (LastMeasurement->at(I).Key != CurMeasurement->at(I).Key) {
  107. return make_error<ClusteringError>(
  108. "inconsistent measurement dimensions keys");
  109. }
  110. }
  111. }
  112. LastMeasurement = CurMeasurement;
  113. }
  114. if (LastMeasurement) {
  115. NumDimensions_ = LastMeasurement->size();
  116. }
  117. return Error::success();
  118. }
  119. void InstructionBenchmarkClustering::clusterizeDbScan(const size_t MinPts) {
  120. std::vector<size_t> Neighbors; // Persistent buffer to avoid allocs.
  121. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
  122. if (!ClusterIdForPoint_[P].isUndef())
  123. continue; // Previously processed in inner loop.
  124. rangeQuery(P, Neighbors);
  125. if (Neighbors.size() + 1 < MinPts) { // Density check.
  126. // The region around P is not dense enough to create a new cluster, mark
  127. // as noise for now.
  128. ClusterIdForPoint_[P] = ClusterId::noise();
  129. continue;
  130. }
  131. // Create a new cluster, add P.
  132. Clusters_.emplace_back(ClusterId::makeValid(Clusters_.size()));
  133. Cluster &CurrentCluster = Clusters_.back();
  134. ClusterIdForPoint_[P] = CurrentCluster.Id; /* Label initial point */
  135. CurrentCluster.PointIndices.push_back(P);
  136. // Process P's neighbors.
  137. SetVector<size_t, std::deque<size_t>> ToProcess;
  138. ToProcess.insert(Neighbors.begin(), Neighbors.end());
  139. while (!ToProcess.empty()) {
  140. // Retrieve a point from the set.
  141. const size_t Q = *ToProcess.begin();
  142. ToProcess.erase(ToProcess.begin());
  143. if (ClusterIdForPoint_[Q].isNoise()) {
  144. // Change noise point to border point.
  145. ClusterIdForPoint_[Q] = CurrentCluster.Id;
  146. CurrentCluster.PointIndices.push_back(Q);
  147. continue;
  148. }
  149. if (!ClusterIdForPoint_[Q].isUndef()) {
  150. continue; // Previously processed.
  151. }
  152. // Add Q to the current custer.
  153. ClusterIdForPoint_[Q] = CurrentCluster.Id;
  154. CurrentCluster.PointIndices.push_back(Q);
  155. // And extend to the neighbors of Q if the region is dense enough.
  156. rangeQuery(Q, Neighbors);
  157. if (Neighbors.size() + 1 >= MinPts) {
  158. ToProcess.insert(Neighbors.begin(), Neighbors.end());
  159. }
  160. }
  161. }
  162. // assert(Neighbors.capacity() == (Points_.size() - 1));
  163. // ^ True, but it is not quaranteed to be true in all the cases.
  164. // Add noisy points to noise cluster.
  165. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
  166. if (ClusterIdForPoint_[P].isNoise()) {
  167. NoiseCluster_.PointIndices.push_back(P);
  168. }
  169. }
  170. }
  171. void InstructionBenchmarkClustering::clusterizeNaive(unsigned NumOpcodes) {
  172. // Given an instruction Opcode, which are the benchmarks of this instruction?
  173. std::vector<SmallVector<size_t, 1>> OpcodeToPoints;
  174. OpcodeToPoints.resize(NumOpcodes);
  175. size_t NumOpcodesSeen = 0;
  176. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
  177. const InstructionBenchmark &Point = Points_[P];
  178. const unsigned Opcode = Point.keyInstruction().getOpcode();
  179. assert(Opcode < NumOpcodes && "NumOpcodes is incorrect (too small)");
  180. SmallVectorImpl<size_t> &PointsOfOpcode = OpcodeToPoints[Opcode];
  181. if (PointsOfOpcode.empty()) // If we previously have not seen any points of
  182. ++NumOpcodesSeen; // this opcode, then naturally this is the new opcode.
  183. PointsOfOpcode.emplace_back(P);
  184. }
  185. assert(OpcodeToPoints.size() == NumOpcodes && "sanity check");
  186. assert(NumOpcodesSeen <= NumOpcodes &&
  187. "can't see more opcodes than there are total opcodes");
  188. assert(NumOpcodesSeen <= Points_.size() &&
  189. "can't see more opcodes than there are total points");
  190. Clusters_.reserve(NumOpcodesSeen); // One cluster per opcode.
  191. for (ArrayRef<size_t> PointsOfOpcode :
  192. make_filter_range(OpcodeToPoints, [](ArrayRef<size_t> PointsOfOpcode) {
  193. return !PointsOfOpcode.empty(); // Ignore opcodes with no points.
  194. })) {
  195. // Create a new cluster.
  196. Clusters_.emplace_back(ClusterId::makeValid(
  197. Clusters_.size(), /*IsUnstable=*/!areAllNeighbours(PointsOfOpcode)));
  198. Cluster &CurrentCluster = Clusters_.back();
  199. // Mark points as belonging to the new cluster.
  200. for_each(PointsOfOpcode, [this, &CurrentCluster](size_t P) {
  201. ClusterIdForPoint_[P] = CurrentCluster.Id;
  202. });
  203. // And add all the points of this opcode to the new cluster.
  204. CurrentCluster.PointIndices.reserve(PointsOfOpcode.size());
  205. CurrentCluster.PointIndices.assign(PointsOfOpcode.begin(),
  206. PointsOfOpcode.end());
  207. assert(CurrentCluster.PointIndices.size() == PointsOfOpcode.size());
  208. }
  209. assert(Clusters_.size() == NumOpcodesSeen);
  210. }
  211. // Given an instruction Opcode, we can make benchmarks (measurements) of the
  212. // instruction characteristics/performance. Then, to facilitate further analysis
  213. // we group the benchmarks with *similar* characteristics into clusters.
  214. // Now, this is all not entirely deterministic. Some instructions have variable
  215. // characteristics, depending on their arguments. And thus, if we do several
  216. // benchmarks of the same instruction Opcode, we may end up with *different*
  217. // performance characteristics measurements. And when we then do clustering,
  218. // these several benchmarks of the same instruction Opcode may end up being
  219. // clustered into *different* clusters. This is not great for further analysis.
  220. // We shall find every opcode with benchmarks not in just one cluster, and move
  221. // *all* the benchmarks of said Opcode into one new unstable cluster per Opcode.
  222. void InstructionBenchmarkClustering::stabilize(unsigned NumOpcodes) {
  223. // Given an instruction Opcode and Config, in which clusters do benchmarks of
  224. // this instruction lie? Normally, they all should be in the same cluster.
  225. struct OpcodeAndConfig {
  226. explicit OpcodeAndConfig(const InstructionBenchmark &IB)
  227. : Opcode(IB.keyInstruction().getOpcode()), Config(&IB.Key.Config) {}
  228. unsigned Opcode;
  229. const std::string *Config;
  230. auto Tie() const -> auto { return std::tie(Opcode, *Config); }
  231. bool operator<(const OpcodeAndConfig &O) const { return Tie() < O.Tie(); }
  232. bool operator!=(const OpcodeAndConfig &O) const { return Tie() != O.Tie(); }
  233. };
  234. std::map<OpcodeAndConfig, SmallSet<ClusterId, 1>> OpcodeConfigToClusterIDs;
  235. // Populate OpcodeConfigToClusterIDs and UnstableOpcodes data structures.
  236. assert(ClusterIdForPoint_.size() == Points_.size() && "size mismatch");
  237. for (auto Point : zip(Points_, ClusterIdForPoint_)) {
  238. const ClusterId &ClusterIdOfPoint = std::get<1>(Point);
  239. if (!ClusterIdOfPoint.isValid())
  240. continue; // Only process fully valid clusters.
  241. const OpcodeAndConfig Key(std::get<0>(Point));
  242. SmallSet<ClusterId, 1> &ClusterIDsOfOpcode = OpcodeConfigToClusterIDs[Key];
  243. ClusterIDsOfOpcode.insert(ClusterIdOfPoint);
  244. }
  245. for (const auto &OpcodeConfigToClusterID : OpcodeConfigToClusterIDs) {
  246. const SmallSet<ClusterId, 1> &ClusterIDs = OpcodeConfigToClusterID.second;
  247. const OpcodeAndConfig &Key = OpcodeConfigToClusterID.first;
  248. // We only care about unstable instructions.
  249. if (ClusterIDs.size() < 2)
  250. continue;
  251. // Create a new unstable cluster, one per Opcode.
  252. Clusters_.emplace_back(ClusterId::makeValidUnstable(Clusters_.size()));
  253. Cluster &UnstableCluster = Clusters_.back();
  254. // We will find *at least* one point in each of these clusters.
  255. UnstableCluster.PointIndices.reserve(ClusterIDs.size());
  256. // Go through every cluster which we recorded as containing benchmarks
  257. // of this UnstableOpcode. NOTE: we only recorded valid clusters.
  258. for (const ClusterId &CID : ClusterIDs) {
  259. assert(CID.isValid() &&
  260. "We only recorded valid clusters, not noise/error clusters.");
  261. Cluster &OldCluster = Clusters_[CID.getId()]; // Valid clusters storage.
  262. // Within each cluster, go through each point, and either move it to the
  263. // new unstable cluster, or 'keep' it.
  264. // In this case, we'll reshuffle OldCluster.PointIndices vector
  265. // so that all the points that are *not* for UnstableOpcode are first,
  266. // and the rest of the points is for the UnstableOpcode.
  267. const auto it = std::stable_partition(
  268. OldCluster.PointIndices.begin(), OldCluster.PointIndices.end(),
  269. [this, &Key](size_t P) {
  270. return OpcodeAndConfig(Points_[P]) != Key;
  271. });
  272. assert(std::distance(it, OldCluster.PointIndices.end()) > 0 &&
  273. "Should have found at least one bad point");
  274. // Mark to-be-moved points as belonging to the new cluster.
  275. std::for_each(it, OldCluster.PointIndices.end(),
  276. [this, &UnstableCluster](size_t P) {
  277. ClusterIdForPoint_[P] = UnstableCluster.Id;
  278. });
  279. // Actually append to-be-moved points to the new cluster.
  280. UnstableCluster.PointIndices.insert(UnstableCluster.PointIndices.end(),
  281. it, OldCluster.PointIndices.end());
  282. // And finally, remove "to-be-moved" points form the old cluster.
  283. OldCluster.PointIndices.erase(it, OldCluster.PointIndices.end());
  284. // Now, the old cluster may end up being empty, but let's just keep it
  285. // in whatever state it ended up. Purging empty clusters isn't worth it.
  286. };
  287. assert(UnstableCluster.PointIndices.size() > 1 &&
  288. "New unstable cluster should end up with more than one point.");
  289. assert(UnstableCluster.PointIndices.size() >= ClusterIDs.size() &&
  290. "New unstable cluster should end up with no less points than there "
  291. "was clusters");
  292. }
  293. }
  294. Expected<InstructionBenchmarkClustering> InstructionBenchmarkClustering::create(
  295. const std::vector<InstructionBenchmark> &Points, const ModeE Mode,
  296. const size_t DbscanMinPts, const double AnalysisClusteringEpsilon,
  297. Optional<unsigned> NumOpcodes) {
  298. InstructionBenchmarkClustering Clustering(
  299. Points, AnalysisClusteringEpsilon * AnalysisClusteringEpsilon);
  300. if (auto Error = Clustering.validateAndSetup()) {
  301. return std::move(Error);
  302. }
  303. if (Clustering.ErrorCluster_.PointIndices.size() == Points.size()) {
  304. return Clustering; // Nothing to cluster.
  305. }
  306. if (Mode == ModeE::Dbscan) {
  307. Clustering.clusterizeDbScan(DbscanMinPts);
  308. if (NumOpcodes.hasValue())
  309. Clustering.stabilize(NumOpcodes.getValue());
  310. } else /*if(Mode == ModeE::Naive)*/ {
  311. if (!NumOpcodes.hasValue())
  312. return make_error<Failure>(
  313. "'naive' clustering mode requires opcode count to be specified");
  314. Clustering.clusterizeNaive(NumOpcodes.getValue());
  315. }
  316. return Clustering;
  317. }
  318. void SchedClassClusterCentroid::addPoint(ArrayRef<BenchmarkMeasure> Point) {
  319. if (Representative.empty())
  320. Representative.resize(Point.size());
  321. assert(Representative.size() == Point.size() &&
  322. "All points should have identical dimensions.");
  323. for (auto I : zip(Representative, Point))
  324. std::get<0>(I).push(std::get<1>(I));
  325. }
  326. std::vector<BenchmarkMeasure> SchedClassClusterCentroid::getAsPoint() const {
  327. std::vector<BenchmarkMeasure> ClusterCenterPoint(Representative.size());
  328. for (auto I : zip(ClusterCenterPoint, Representative))
  329. std::get<0>(I).PerInstructionValue = std::get<1>(I).avg();
  330. return ClusterCenterPoint;
  331. }
  332. bool SchedClassClusterCentroid::validate(
  333. InstructionBenchmark::ModeE Mode) const {
  334. size_t NumMeasurements = Representative.size();
  335. switch (Mode) {
  336. case InstructionBenchmark::Latency:
  337. if (NumMeasurements != 1) {
  338. errs()
  339. << "invalid number of measurements in latency mode: expected 1, got "
  340. << NumMeasurements << "\n";
  341. return false;
  342. }
  343. break;
  344. case InstructionBenchmark::Uops:
  345. // Can have many measurements.
  346. break;
  347. case InstructionBenchmark::InverseThroughput:
  348. if (NumMeasurements != 1) {
  349. errs() << "invalid number of measurements in inverse throughput "
  350. "mode: expected 1, got "
  351. << NumMeasurements << "\n";
  352. return false;
  353. }
  354. break;
  355. default:
  356. llvm_unreachable("unimplemented measurement matching mode");
  357. return false;
  358. }
  359. return true; // All good.
  360. }
  361. } // namespace exegesis
  362. } // namespace llvm