selected_rows_impl.cc 6.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

15
#include "paddle/phi/core/selected_rows_impl.h"
16

17
#include "paddle/phi/core/utils/data_type.h"
18

19 20 21
// See Note [ Why still include the fluid headers? ]
#include "paddle/fluid/memory/memcpy.h"

22
namespace phi {
23 24

struct ReAllocateVisitor {
25
  ReAllocateVisitor(const phi::DDim& dims, phi::DenseTensor* tensor)
26 27 28 29
      : dims_(dims), tensor_(tensor) {}

  template <typename T>
  void operator()() const {
30
    phi::DenseTensor cpu_tensor;
31 32 33 34 35 36 37 38 39 40
    paddle::platform::CPUPlace cpu;
    T* ptr = cpu_tensor.mutable_data<T>(dims_, cpu);
    const T* old_ptr =
        tensor_->memory_size() == 0 ? nullptr : tensor_->data<T>();
    if (old_ptr != nullptr) {
      std::copy(old_ptr, old_ptr + tensor_->numel(), ptr);
    }
    tensor_->ShareDataWith(cpu_tensor);
  }

41 42
  phi::DDim dims_;
  phi::DenseTensor* tensor_;
43 44 45
};

struct TensorCopyVisitor {
46
  TensorCopyVisitor(phi::DenseTensor* dst,
47
                    int64_t dst_offset,
48
                    const phi::DenseTensor src,
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
                    int64_t src_offset,
                    int64_t size)
      : dst_(dst),
        dst_offset_(dst_offset),
        src_(src),
        src_offset_(src_offset),
        size_(size) {}

  template <typename T>
  void apply() const {
    // TODO(Yancey1989): support other place
    paddle::platform::CPUPlace cpu;
    paddle::memory::Copy(cpu,
                         dst_->mutable_data<T>(cpu) + dst_offset_,
                         cpu,
                         src_.data<T>() + src_offset_,
                         size_ * sizeof(T));
  }

68
  phi::DenseTensor* dst_;
69
  int64_t dst_offset_;
70
  phi::DenseTensor src_;
71 72 73 74 75
  int64_t src_offset_;
  int64_t size_;
};

struct TensorFillVisitor {
76
  TensorFillVisitor(phi::DenseTensor* dst,
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
                    int64_t dst_offset,
                    int64_t size,
                    float value)
      : dst_(dst), dst_offset_(dst_offset), size_(size) {}

  template <typename T>
  void apply() const {
    // TODO(qiao): support other place
    paddle::platform::CPUPlace cpu;
    auto* tensor_data = dst_->mutable_data<T>(cpu);
    auto* start = tensor_data + dst_offset_;
    auto* end = start + size_;
    std::fill(start, end, static_cast<T>(0.0));
  }

92
  phi::DenseTensor* dst_;
93 94 95 96
  int64_t dst_offset_;
  int64_t size_;
};

J
Jiabin Yang 已提交
97 98 99
void* SelectedRowsImpl::AllocateFrom(Allocator* allocator,
                                     DataType dtype,
                                     size_t requested_size) {
100 101 102
  return value_->AllocateFrom(allocator, dtype, requested_size);
}

J
Jiabin Yang 已提交
103
bool SelectedRowsImpl::HasKey(int64_t key) const {
104 105 106 107
  return std::find(rows_.begin(), rows_.end(), key) == rows_.end() ? false
                                                                   : true;
}

J
Jiabin Yang 已提交
108 109 110
int64_t SelectedRowsImpl::AutoGrownIndex(int64_t key,
                                         bool auto_grown,
                                         bool is_test) {
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
  if (is_test) {
    auto iter = id_to_index_.find(key);
    if (iter == id_to_index_.end()) {
      return -1;
    } else {
      return iter->second;
    }
  }

  rwlock_->RDLock();
  auto iter = id_to_index_.find(key);
  if (iter == id_to_index_.end()) {
    rwlock_->UNLock();
    PADDLE_ENFORCE_EQ(auto_grown,
                      true,
                      paddle::platform::errors::NotFound(
                          "Input key(%lld) is not found.", key));
    rwlock_->WRLock();
    auto map_size = id_to_index_.size();
    auto vector_size = rows_.size();
    if (map_size != vector_size) {
      rwlock_->UNLock();
      PADDLE_THROW(paddle::platform::errors::InvalidArgument(
          "Row map size(%zu) should be equal to rows size(%zu).",
          map_size,
          vector_size));
    }
    auto write_iter = id_to_index_.find(key);
    if (write_iter == id_to_index_.end()) {
      int row_num = rows_.size();
      if (row_num == value_->dims()[0]) {
        rwlock_->UNLock();
        PADDLE_THROW(paddle::platform::errors::InvalidArgument(
            "Selected rows is full, then length exceed the length of first "
            "dimension (%d).",
            row_num));
      }
      // key logic to put a key into id_to_index_
      rows_.push_back(key);
      auto index = static_cast<int64_t>(rows_.size() - 1);
      id_to_index_[key] = index;
      rwlock_->UNLock();
      return index;
    } else {
      auto index = write_iter->second;
      rwlock_->UNLock();
      return index;
    }
  } else {
    auto index = iter->second;
    rwlock_->UNLock();
    return index;
  }
}

J
Jiabin Yang 已提交
166
void SelectedRowsImpl::SyncIndex() {
167 168 169 170 171 172 173 174
  rwlock_->WRLock();
  id_to_index_.clear();
  for (size_t i = 0; i < rows_.size(); ++i) {
    id_to_index_[rows_[i]] = i;
  }
  rwlock_->UNLock();
}

175 176
void SelectedRowsImpl::Get(const phi::DenseTensor& ids,
                           phi::DenseTensor* value,
J
Jiabin Yang 已提交
177 178
                           bool auto_grown,
                           bool is_test) {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  PADDLE_ENFORCE_EQ(value->IsInitialized(),
                    true,
                    paddle::platform::errors::InvalidArgument(
                        "The value tensor is not initialized."));
  if (ids.numel() == 0) {
    VLOG(3) << "keys is empty, please check data!";
  } else {
    int64_t value_width = value_->numel() / value_->dims()[0];
    PADDLE_ENFORCE_EQ(
        value_width,
        value->numel() / value->dims()[0],
        paddle::platform::errors::InvalidArgument(
            "Output tensor should have the same shape with table "
            "except the first dimmension, excepted value width not counting "
            "the first dimension is %d, actual value width is %d.",
            value_width,
            value->numel() / value->dims()[0]));
    for (int i = 0; i < ids.numel(); ++i) {
      auto id = ids.data<int64_t>()[i];
      int64_t index = AutoGrownIndex(id, auto_grown, is_test);
      if (index < 0) {
        VLOG(5) << "id " << id << " not in the table, return 0";
201
        phi::VisitDataType(
202
            value_->dtype(),
203 204
            TensorFillVisitor(value, i * value_width, value_width, 0.0));
      } else {
205 206 207 208 209 210
        phi::VisitDataType(value_->dtype(),
                           TensorCopyVisitor(value,
                                             i * value_width,
                                             *value_.get(),
                                             index * value_width,
                                             value_width));
211 212 213 214
      }
    }
  }
}
215
}  // namespace phi