selected_rows.cc 6.2 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 17

namespace paddle {
18
namespace framework {
19

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

  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::Tensor* tensor_;
  framework::DDim dims_;
};

Y
update  
Yancey1989 已提交
41
struct TensorCopyVisitor {
Y
Yancey1989 已提交
42 43 44 45
  TensorCopyVisitor(framework::Tensor* dst, int64_t dst_offset,
                    const framework::Tensor src, int64_t src_offset,
                    int64_t size)
      : dst_(dst),
Y
Yancey1989 已提交
46 47 48 49 50 51 52
        dst_offset_(dst_offset),
        src_(src),
        src_offset_(src_offset),
        size_(size) {}

  template <typename T>
  void operator()() const {
Y
Yancey1989 已提交
53 54 55 56
    // 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 已提交
57 58 59 60 61 62 63 64 65
  }

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

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
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 已提交
87
  TensorToStream(os, selected_rows.value(), dev_ctx);
88 89
}

Y
Yancey 已提交
90 91
void DeserializeFromStream(std::istream& is, SelectedRows* selected_rows,
                           const platform::DeviceContext& dev_ctx) {
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  {
    // the 1st field, unit32_t version for SelectedRows
    uint32_t version;
    is.read(reinterpret_cast<char*>(&version), sizeof(version));
    PADDLE_ENFORCE_EQ(version, 0U, "Only version 0 is supported");
  }
  {
    // 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 已提交
115
  TensorFromStream(is, selected_rows->mutable_value(), dev_ctx);
116 117
}

Y
Yancey1989 已提交
118 119 120 121 122
bool SelectedRows::HasKey(int64_t key) const {
  return std::find(rows_.begin(), rows_.end(), key) == rows_.end() ? false
                                                                   : true;
}

Y
Yancey1989 已提交
123 124
std::vector<std::pair<int64_t, int64_t>> SelectedRows::Get(
    std::vector<int64_t> keys, framework::Tensor* value) const {
Y
update  
Yancey1989 已提交
125 126
  PADDLE_ENFORCE(value->IsInitialized(),
                 "The value tensor should be initialized.");
Y
Yancey1989 已提交
127
  std::vector<std::pair<int64_t, int64_t>> non_keys_pair;
Y
Yancey1989 已提交
128 129
  int64_t value_width = value_->numel() / value_->dims()[0];
  PADDLE_ENFORCE_EQ(value_width, value->numel() / value->dims()[0],
Y
update  
Yancey1989 已提交
130 131 132
                    "output tensor should have the same shape with table "
                    "execpt the dims[0].");

Y
Yancey1989 已提交
133 134 135
  for (size_t i = 0; i < keys.size(); ++i) {
    int64_t index = Index(keys[i]);
    if (index == -1) {
Y
Yancey1989 已提交
136
      non_keys_pair.push_back(std::make_pair(keys[i], static_cast<int64_t>(i)));
Y
Yancey1989 已提交
137 138 139
    } else {
      framework::VisitDataType(
          framework::ToDataType(value_->type()),
Y
Yancey1989 已提交
140
          TensorCopyVisitor(value, i * value_width, *value_.get(),
Y
Yancey1989 已提交
141 142 143
                            index * value_width, value_width));
    }
  }
Y
Yancey1989 已提交
144
  return non_keys_pair;
Y
Yancey1989 已提交
145 146 147 148 149 150 151 152 153 154 155
}

bool SelectedRows::Set(int64_t key, const framework::Tensor& value) {
  PADDLE_ENFORCE(value.IsInitialized(), "The value should be initialized.");
  if (value_->IsInitialized()) {
    PADDLE_ENFORCE_EQ(
        value.type(), value_->type(),
        "The type of the value should be same with the original value");
  }
  PADDLE_ENFORCE_EQ(value.dims()[0], static_cast<size_t>(1),
                    "The first dim of value should be 1.");
156
  std::lock_guard<std::mutex> lock(auto_grown_mutex_);
Y
Yancey1989 已提交
157 158 159 160 161 162
  auto index = Index(key);
  bool is_new_key = false;
  if (index == -1) {
    rows_.push_back(key);
    index = rows_.size() - 1;
    is_new_key = true;
Y
update  
Yancey1989 已提交
163
    // whether need to resize the table
Y
Yancey1989 已提交
164 165 166 167
    if (static_cast<int64_t>(rows_.size()) > value_->dims()[0]) {
      auto dims = value_->dims();
      dims[0] = (dims[0] + 1) << 1;
      framework::VisitDataType(framework::ToDataType(value.type()),
168
                               ReAllocateVisitor(dims, value_.get()));
Y
Yancey1989 已提交
169 170 171 172 173
    }
  }

  framework::VisitDataType(
      framework::ToDataType(value.type()),
Y
Yancey1989 已提交
174
      TensorCopyVisitor(value_.get(),
Y
update  
Yancey1989 已提交
175 176
                        index * value_->numel() / value_->dims()[0], value,
                        static_cast<int64_t>(0), value.numel()));
Y
Yancey1989 已提交
177 178 179
  return is_new_key;
}

180
}  // namespace framework
Q
qijun 已提交
181
}  // namespace paddle