selected_rows.cc 8.5 KB
Newer Older
1 2
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Q
qijun 已提交
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

Q
qijun 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
8

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

Y
Yi Wang 已提交
15
#include "paddle/fluid/framework/selected_rows.h"
Q
qijun 已提交
16

W
wanghuancoder 已提交
17 18 19 20 21 22
namespace paddle {
namespace platform {
class DeviceContext;
}  // namespace platform
}  // namespace paddle

Q
qijun 已提交
23
namespace paddle {
24
namespace framework {
25

Y
Yancey1989 已提交
26
struct ReAllocateVisitor {
27 28
  ReAllocateVisitor(const framework::DDim& dims, framework::Tensor* tensor)
      : dims_(dims), tensor_(tensor) {}
Y
Yancey1989 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

  template <typename T>
  void operator()() const {
    framework::Tensor cpu_tensor;
    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);
  }

  framework::DDim dims_;
Q
qiaolongfei 已提交
44
  framework::Tensor* tensor_;
Y
Yancey1989 已提交
45 46
};

Y
update  
Yancey1989 已提交
47
struct TensorCopyVisitor {
Y
Yancey1989 已提交
48 49 50 51
  TensorCopyVisitor(framework::Tensor* dst, int64_t dst_offset,
                    const framework::Tensor src, int64_t src_offset,
                    int64_t size)
      : dst_(dst),
Y
Yancey1989 已提交
52 53 54 55 56 57
        dst_offset_(dst_offset),
        src_(src),
        src_offset_(src_offset),
        size_(size) {}

  template <typename T>
D
dzhwinter 已提交
58
  void apply() const {
Y
Yancey1989 已提交
59 60 61 62
    // TODO(Yancey1989): support other place
    platform::CPUPlace cpu;
    memory::Copy(cpu, dst_->mutable_data<T>(cpu) + dst_offset_, cpu,
                 src_.data<T>() + src_offset_, size_ * sizeof(T));
Y
Yancey1989 已提交
63 64 65 66 67 68 69 70 71
  }

  framework::Tensor* dst_;
  int64_t dst_offset_;
  framework::Tensor src_;
  int64_t src_offset_;
  int64_t size_;
};

Q
Qiao Longfei 已提交
72 73 74 75 76 77 78
struct TensorFillVisitor {
  TensorFillVisitor(framework::Tensor* dst, int64_t dst_offset, int64_t size,
                    float value)
      : dst_(dst), dst_offset_(dst_offset), size_(size) {}

  template <typename T>
  void apply() const {
Q
Qiao Longfei 已提交
79
    // TODO(qiao): support other place
Q
Qiao Longfei 已提交
80 81 82 83 84 85 86 87 88 89 90 91
    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));
  }

  framework::Tensor* dst_;
  int64_t dst_offset_;
  int64_t size_;
};

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
void SerializeToStream(std::ostream& os, const SelectedRows& selected_rows,
                       const platform::DeviceContext& dev_ctx) {
  {  // the 1st field, uint32_t version
    constexpr uint32_t version = 0;
    os.write(reinterpret_cast<const char*>(&version), sizeof(version));
  }
  {
    // the 2st field, rows information
    auto& rows = selected_rows.rows();
    uint64_t size = rows.size();
    os.write(reinterpret_cast<const char*>(&size), sizeof(size));
    for (uint64_t i = 0; i < size; ++i) {
      os.write(reinterpret_cast<const char*>(&rows[i]), sizeof(rows[i]));
    }
  }
  {
    // the 3st field, the height of SelectedRows
    int64_t height = selected_rows.height();
    os.write(reinterpret_cast<const char*>(&height), sizeof(height));
  }
  // the 4st field, Tensor data
Y
Yi Wang 已提交
113
  TensorToStream(os, selected_rows.value(), dev_ctx);
114 115
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
void SerializeToStream(std::ostream& os, const SelectedRows& selected_rows) {
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  const platform::DeviceContext* dev_ctx;
  auto place = selected_rows.place();
  dev_ctx = pool.Get(place);
  SerializeToStream(os, selected_rows, *dev_ctx);
}

void DeserializeFromStream(std::ifstream& os, SelectedRows* selected_rows) {
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  const platform::DeviceContext* dev_ctx;
  dev_ctx = pool.Get(platform::CPUPlace());
  DeserializeFromStream(os, selected_rows, *dev_ctx);
}

Y
Yancey 已提交
131 132
void DeserializeFromStream(std::istream& is, SelectedRows* selected_rows,
                           const platform::DeviceContext& dev_ctx) {
133 134 135 136
  {
    // the 1st field, unit32_t version for SelectedRows
    uint32_t version;
    is.read(reinterpret_cast<char*>(&version), sizeof(version));
137 138 139
    PADDLE_ENFORCE_EQ(version, 0U,
                      platform::errors::InvalidArgument(
                          "Only version 0 SelectedRows is supported."));
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  }
  {
    // the 2st field, rows information
    uint64_t size;
    is.read(reinterpret_cast<char*>(&size), sizeof(size));
    auto& rows = *selected_rows->mutable_rows();
    rows.resize(size);
    for (uint64_t i = 0; i < size; ++i) {
      is.read(reinterpret_cast<char*>(&rows[i]), sizeof(int64_t));
    }
  }
  {
    // the 3st field, the height of the SelectedRows
    int64_t height;
    is.read(reinterpret_cast<char*>(&height), sizeof(int64_t));
    selected_rows->set_height(height);
  }
  // the 4st field, tensor which contains the data
Y
Yi Wang 已提交
158
  TensorFromStream(is, selected_rows->mutable_value(), dev_ctx);
159 160
}

Y
Yancey1989 已提交
161 162 163 164 165
bool SelectedRows::HasKey(int64_t key) const {
  return std::find(rows_.begin(), rows_.end(), key) == rows_.end() ? false
                                                                   : true;
}

Q
Qiao Longfei 已提交
166 167 168 169 170 171 172 173 174 175 176
int64_t SelectedRows::AutoGrownIndex(int64_t key, bool auto_grown,
                                     bool is_test) {
  if (is_test) {
    auto iter = id_to_index_.find(key);
    if (iter == id_to_index_.end()) {
      return -1;
    } else {
      return iter->second;
    }
  }

177 178 179 180
  rwlock_->RDLock();
  auto iter = id_to_index_.find(key);
  if (iter == id_to_index_.end()) {
    rwlock_->UNLock();
181 182 183
    PADDLE_ENFORCE_EQ(
        auto_grown, true,
        platform::errors::NotFound("Input key(%lld) is not found.", key));
184 185 186 187 188
    rwlock_->WRLock();
    auto map_size = id_to_index_.size();
    auto vector_size = rows_.size();
    if (map_size != vector_size) {
      rwlock_->UNLock();
189 190 191
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Row map size(%zu) should be equal to rows size(%zu).", map_size,
          vector_size));
192 193 194
    }
    auto write_iter = id_to_index_.find(key);
    if (write_iter == id_to_index_.end()) {
195
      int row_num = rows_.size();
196 197
      if (row_num == value_->dims()[0]) {
        rwlock_->UNLock();
198 199 200 201
        PADDLE_THROW(platform::errors::InvalidArgument(
            "Selected rows is full, then length exceed the length of first "
            "dimension (%d).",
            row_num));
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
      }
      // 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;
  }
}

void SelectedRows::SyncIndex() {
  rwlock_->WRLock();
  id_to_index_.clear();
  for (size_t i = 0; i < rows_.size(); ++i) {
    id_to_index_[rows_[i]] = i;
  }
  rwlock_->UNLock();
}

void SelectedRows::Get(const framework::Tensor& ids, framework::Tensor* value,
Q
Qiao Longfei 已提交
231
                       bool auto_grown, bool is_test) {
232 233 234
  PADDLE_ENFORCE_EQ(value->IsInitialized(), true,
                    platform::errors::InvalidArgument(
                        "The value tensor is not initialized."));
235
  if (ids.numel() == 0) {
M
minqiyang 已提交
236
    VLOG(3) << "keys is empty, please check data!";
Q
qiaolongfei 已提交
237 238
  } else {
    int64_t value_width = value_->numel() / value_->dims()[0];
239 240 241 242 243 244 245
    PADDLE_ENFORCE_EQ(
        value_width, value->numel() / value->dims()[0],
        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]));
246
    for (int i = 0; i < ids.numel(); ++i) {
Q
Qiao Longfei 已提交
247 248
      auto id = ids.data<int64_t>()[i];
      int64_t index = AutoGrownIndex(id, auto_grown, is_test);
Q
Qiao Longfei 已提交
249
      if (index < 0) {
Q
Qiao Longfei 已提交
250
        VLOG(5) << "id " << id << " not in the table, return 0";
Q
Qiao Longfei 已提交
251
        framework::VisitDataType(
Y
Yu Yang 已提交
252
            value_->type(),
Q
Qiao Longfei 已提交
253 254 255
            TensorFillVisitor(value, i * value_width, value_width, 0.0));
      } else {
        framework::VisitDataType(
Y
Yu Yang 已提交
256
            value_->type(),
Q
Qiao Longfei 已提交
257 258 259
            TensorCopyVisitor(value, i * value_width, *value_.get(),
                              index * value_width, value_width));
      }
Y
Yancey1989 已提交
260 261
    }
  }
Y
Yancey1989 已提交
262 263
}

264
}  // namespace framework
Q
qijun 已提交
265
}  // namespace paddle