• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_CORE_TPU_KERNELS_COMPILATION_CACHE_ENTRY_UNLOADER_H_
16 #define TENSORFLOW_CORE_TPU_KERNELS_COMPILATION_CACHE_ENTRY_UNLOADER_H_
17 
18 #include "absl/container/flat_hash_set.h"
19 #include "absl/synchronization/mutex.h"
20 #include "tensorflow/core/framework/resource_mgr.h"
21 #include "tensorflow/core/tpu/kernels/tpu_compilation_cache_interface.h"
22 
23 namespace tensorflow {
24 namespace tpu {
25 
26 class TpuCompilationCacheEntryUnloader : public ResourceBase {
27  public:
TpuCompilationCacheEntryUnloader(TpuCompilationCacheInterface * cache)28   explicit TpuCompilationCacheEntryUnloader(TpuCompilationCacheInterface* cache)
29       : cache_(cache) {
30     // Hold a reference to the cache until the unloader is destroyed.
31     cache_->Ref();
32     VLOG(1) << "Will unload compilation cache entries when session closes.";
33   }
34 
~TpuCompilationCacheEntryUnloader()35   ~TpuCompilationCacheEntryUnloader() override {
36     absl::MutexLock lock(&mu_);
37     for (int64 uid : cache_entry_uids_) {
38       Status s = cache_->MarkEntryForEviction(uid);
39       if (!s.ok()) {
40         LOG(WARNING) << "MarkEntryForEviction in "
41                         "~CompilationCacheEntryUnloader fails with error "
42                      << s;
43       }
44     }
45     // Release our reference to the cache.
46     cache_->Unref();
47   }
48 
49   // Add cache entry uid to be unloaded in destructor.
AddCacheEntryUid(int64 uid)50   void AddCacheEntryUid(int64 uid) {
51     absl::MutexLock lock(&mu_);
52     cache_entry_uids_.insert(uid);
53   }
54 
DebugString()55   std::string DebugString() const override {
56     return "CompilationCacheEntryUnloader";
57   }
58 
59  private:
60   TF_DISALLOW_COPY_AND_ASSIGN(TpuCompilationCacheEntryUnloader);
61   mutable absl::Mutex mu_;
62   TpuCompilationCacheInterface* cache_;  // Not owned.
63   absl::flat_hash_set<int64> cache_entry_uids_ ABSL_GUARDED_BY(mu_);
64 };
65 
66 }  // namespace tpu
67 }  // namespace tensorflow
68 
69 #endif  // TENSORFLOW_CORE_TPU_KERNELS_COMPILATION_CACHE_ENTRY_UNLOADER_H_
70