selected_rows.h 2.1 KB
Newer Older
L
liuruilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

朔-望's avatar
朔-望 已提交
15 16 17 18 19 20 21 22
#pragma once

#include <vector>

#include "lod_tensor.h"
#include "tensor.h"

namespace paddle_mobile {
朔-望's avatar
朔-望 已提交
23
namespace framework {
朔-望's avatar
朔-望 已提交
24

朔-望's avatar
朔-望 已提交
25
class SelectedRows {
朔-望's avatar
朔-望 已提交
26
 public:
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  SelectedRows(const std::vector<int64_t> &rows, const int64_t &height)
      : rows_(rows), height_(height) {
    value_.reset(new Tensor());
  }

  SelectedRows() {
    height_ = 0;
    value_.reset(new Tensor());
  }

  const Tensor &value() const { return *value_; }

  Tensor *mutable_value() { return value_.get(); }

  int64_t height() const { return height_; }

  void set_height(int64_t height) { height_ = height; }

  const std::vector<int64_t> &rows() const { return rows_; }

  std::vector<int64_t> *mutable_rows() { return &rows_; }

  void set_rows(const std::vector<int64_t> &rows) { rows_ = rows; }

  /**
   * get the index of id in rows
   */
  int64_t index(int64_t id) const {
    auto it = std::find(rows_.begin(), rows_.end(), id);
    //    PADDLE_ENFORCE(it != rows_.end(), "id should be in rows");
    return static_cast<int64_t>(std::distance(rows_.begin(), it));
  }

  DDim GetCompleteDims() const {
    std::vector<int64_t> dims = vectorize(value_->dims());
    dims[0] = height_;
    return make_ddim(dims);
  }

朔-望's avatar
朔-望 已提交
66
 private:
67 68 69 70 71 72 73
  // Notice: rows can be duplicate. We can have {0, 4, 7, 0, 5, 7, 9}
  // here.
  // SelectedRows are simply concated when adding together. Until a
  // SelectedRows add a Tensor, will the duplicate rows be handled.
  std::vector<int64_t> rows_;
  std::unique_ptr<Tensor> value_{nullptr};
  int64_t height_;
朔-望's avatar
朔-望 已提交
74
};
朔-望's avatar
朔-望 已提交
75

朔-望's avatar
朔-望 已提交
76 77
}  // namespace framework
}  // namespace paddle_mobile