cache.h 5.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
16

17 18
#include <algorithm>
#include <mutex>
19
#include <numeric>
20 21
#include <unordered_map>
#include <vector>
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
#include "paddle/phi/common/data_type.h"
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/errors.h"

inline void HashCombine(std::size_t* seed) {}

// combine hash value
// https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x
template <typename T, typename... Rest>
inline void HashCombine(std::size_t* seed, const T& v, Rest... rest) {
  std::hash<T> hasher;
  *seed ^= hasher(v) + 0x9e3779b9 + (*seed << 6) + (*seed >> 2);
  HashCombine(seed, rest...);
}

// custom specialization of std::hash can be injected in namespace std
// ref: https://en.cppreference.com/w/cpp/utility/hash
namespace std {
template <typename T>
struct hash<std::vector<T>> {
  std::size_t operator()(std::vector<T> const& vec) const noexcept {
    std::size_t seed = 0;
    for (auto val : vec) {
      HashCombine(&seed, val);
    }
    return seed;
  }
};
}  // namespace std

namespace phi {
namespace autotune {

56 57 58 59 60 61 62 63 64 65 66 67 68
template <typename... Args>
size_t GetKey(Args&&... args) {
  size_t seed = 0;
  HashCombine(&seed, std::forward<Args>(args)...);
  return seed;
}

// Define the cache key of operator
size_t ConvKey(const std::vector<int64_t>& x_dims,
               const std::vector<int64_t>& w_dims,
               const std::vector<int>& strides,
               const std::vector<int>& paddings,
               const std::vector<int>& dilations,
69
               phi::DataType dtype);
70

71 72 73
template <typename AlgorithmT>
class AlgorithmsCache {
 public:
74
  AlgorithmsCache() : cache_mutex_(new std::mutex()) { hash_.clear(); }
75 76

  AlgorithmT Get(size_t key) {
77
    std::lock_guard<std::mutex> lock(*cache_mutex_);
78 79 80 81 82 83 84 85 86
    PADDLE_ENFORCE_NE(
        hash_.find(key),
        hash_.end(),
        phi::errors::PreconditionNotMet("The key does not exist."));
    return hash_[key];
  }

  bool Find(size_t key) {
    bool ret = false;
87
    std::lock_guard<std::mutex> lock(*cache_mutex_);
88 89 90 91 92 93 94 95 96
    if (hash_.find(key) != hash_.end()) {
      cache_hits_++;
      ret = true;
    } else {
      cache_misses_++;
    }
    return ret;
  }

97 98 99 100 101 102 103
  void Clean() {
    std::lock_guard<std::mutex> lock(*cache_mutex_);
    hash_.clear();
    cache_hits_ = 0;
    cache_misses_ = 0;
  }

104
  void Set(size_t key, AlgorithmT algo) {
105
    std::lock_guard<std::mutex> lock(*cache_mutex_);
106 107 108
    hash_[key] = algo;
  }

109 110 111 112
  int64_t CacheMisses() const { return cache_misses_; }

  int64_t CacheHits() const { return cache_hits_; }

113 114
  float CacheHitRate() const {
    int64_t num_accesses = cache_hits_ + cache_misses_;
115 116 117 118 119
    float cache_hit_rate = 0.;
    if (num_accesses != 0) {
      cache_hit_rate =
          static_cast<float>(cache_hits_) / static_cast<float>(num_accesses);
    }
120 121 122
    return cache_hit_rate;
  }

123
  int64_t Size() const { return hash_.size(); }
124 125 126

 private:
  std::unordered_map<size_t, AlgorithmT> hash_;
127
  std::shared_ptr<std::mutex> cache_mutex_;
128 129 130 131 132 133 134 135 136

  int64_t cache_hits_{0};
  int64_t cache_misses_{0};
};

enum class AlgorithmType {
  kConvForward = 1,
  kConvBackwardData = 2,
  kConvBackwardFilter = 3,
137 138
  kTranspose = 4,
  kAlgorithmCount = 5
139 140
};

141
// AlgorithmsConfigKey -> AlgorithmsID
142 143 144
using AlgorithmsCacheMap = AlgorithmsCache<int64_t>;
// AlgorithmType -> AlgorithmsCache
using AlgorithmsTypeMap = std::unordered_map<int64_t, AlgorithmsCacheMap>;
145 146 147 148 149 150 151 152

class AutoTuneCache {
 public:
  static AutoTuneCache& Instance() {
    static AutoTuneCache autotune_cache;
    return autotune_cache;
  }

153 154
  AlgorithmsCacheMap& Get(const AlgorithmType& algo_type) {
    return auto_tune_map_[static_cast<int64_t>(algo_type)];
155 156
  }

157 158 159 160 161 162 163 164 165 166
  AlgorithmsCacheMap& GetConvForward() {
    return Get(AlgorithmType::kConvForward);
  }

  AlgorithmsCacheMap& GetConvBackwardData() {
    return Get(AlgorithmType::kConvBackwardData);
  }

  AlgorithmsCacheMap& GetConvBackwardFilter() {
    return Get(AlgorithmType::kConvBackwardFilter);
167 168
  }

169 170
  AlgorithmsCacheMap& GetTranspose() { return Get(AlgorithmType::kTranspose); }

171
  void Clean() {
172
    for (auto& v : auto_tune_map_) {
173
      v.second.Clean();
174
    }
175 176
  }

177 178
  void UpdateStatus();

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  // The number of total config cached
  int64_t Size() const { return total_size_; }

  int64_t CacheHits() const { return total_cache_hits_; }

  int64_t CacheMisses() const { return total_cache_misses_; }

  float CacheHitRate() const {
    float total_cache_hit_rate = 0.;
    int64_t total_num_accesses = total_cache_hits_ + total_cache_misses_;
    if (total_num_accesses != 0) {
      total_cache_hit_rate = static_cast<float>(total_cache_hits_) /
                             static_cast<float>(total_num_accesses);
    }
    return total_cache_hit_rate;
194 195 196
  }

 private:
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  AutoTuneCache() : autotune_cache_mutex_(new std::mutex()) {
    for (int i = 1; i < static_cast<int>(AlgorithmType::kAlgorithmCount); ++i) {
      Register(static_cast<AlgorithmType>(i));
    }
  }

  void Register(const AlgorithmType& algo_type) {
    std::lock_guard<std::mutex> lock(*autotune_cache_mutex_);
    int64_t key = static_cast<int64_t>(algo_type);
    if (auto_tune_map_.find(key) == auto_tune_map_.end()) {
      AlgorithmsCacheMap cache;
      auto_tune_map_[key] = cache;
    }
  }

212 213
  AlgorithmsTypeMap auto_tune_map_;
  std::shared_ptr<std::mutex> autotune_cache_mutex_;
214 215 216
  int64_t total_cache_hits_{0};
  int64_t total_cache_misses_{0};
  int64_t total_size_{0};
217 218
};

219 220
}  // namespace autotune
}  // namespace phi