meta_cache.cc 1.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2

L
Luo Tao 已提交
3 4 5
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
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
14

15
#include "glog/logging.h"
Y
Yi Wang 已提交
16
#include "paddle/fluid/memory/detail/memory_block.h"
17
#include "paddle/fluid/platform/enforce.h"
18 19 20 21 22 23 24

namespace paddle {
namespace memory {
namespace detail {

MetadataCache::MetadataCache(bool uses_gpu) : uses_gpu_(uses_gpu) {}

25
MemoryBlock::Desc* MetadataCache::LoadDesc(MemoryBlock* block) {
26
  if (uses_gpu_) {
27 28 29 30 31
    auto iter = cache_.find(block);
    PADDLE_ENFORCE_NE(iter, cache_.end());
    auto* desc = &(iter->second);
    PADDLE_ENFORCE_EQ(desc->CheckGuards(), true, "Invalid CPU memory access");
    return desc;
32
  } else {
33
    auto* desc = reinterpret_cast<MemoryBlock::Desc*>(block);
M
minqiyang 已提交
34
    VLOG(10) << "Load MemoryBlock::Desc type=" << desc->type;
35
    PADDLE_ENFORCE_EQ(desc->CheckGuards(), true, "Invalid CPU memory access");
36
    return reinterpret_cast<MemoryBlock::Desc*>(block);
37 38 39
  }
}

40
void MetadataCache::Save(MemoryBlock* block,
Y
Update  
Yi Wang 已提交
41 42
                         const MemoryBlock::Desc& original_desc) {
  auto desc = original_desc;
43
  desc.UpdateGuards();
44 45

  if (uses_gpu_) {
Y
Update  
Yi Wang 已提交
46
    cache_[block] = desc;
47
  } else {
Y
Update  
Yi Wang 已提交
48
    *reinterpret_cast<MemoryBlock::Desc*>(block) = desc;
49 50 51
  }
}

52
void MetadataCache::Invalidate(MemoryBlock* block) {
53 54 55 56 57 58 59 60
  if (uses_gpu_) {
    cache_.erase(block);
  }
}

}  // namespace detail
}  // namespace memory
}  // namespace paddle