Matrix.cpp 2.3 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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. */

Y
Yu Yang 已提交
15 16 17 18 19 20 21 22 23 24
#include "PaddleCAPI.h"
#include "PaddleCAPIPrivate.h"
#include "hl_cuda.h"

#define cast(v) paddle::capi::cast<paddle::capi::CMatrix>(v)
extern "C" {
int PDMatCreate(PD_Matrix* mat, uint64_t height, uint64_t width, bool useGpu) {
  auto ptr = new paddle::capi::CMatrix();
  ptr->mat = paddle::Matrix::create(height, width, false, useGpu);
  *mat = ptr;
Y
Yu Yang 已提交
25
  return kPD_NO_ERROR;
Y
Yu Yang 已提交
26 27 28 29 30
}

int PDMatCreateNone(PD_Matrix* mat) {
  auto ptr = new paddle::capi::CMatrix();
  *mat = ptr;
Y
Yu Yang 已提交
31
  return kPD_NO_ERROR;
Y
Yu Yang 已提交
32 33 34
}

int PDMatDestroy(PD_Matrix mat) {
Y
Yu Yang 已提交
35
  if (mat == nullptr) return kPD_NULLPTR;
Y
Yu Yang 已提交
36 37
  auto ptr = cast(mat);
  delete ptr;
Y
Yu Yang 已提交
38
  return kPD_NO_ERROR;
Y
Yu Yang 已提交
39 40 41
}

int PDMatCopyToRow(PD_Matrix mat, uint64_t rowID, pd_real* rowArray) {
Y
Yu Yang 已提交
42
  if (mat == nullptr) return kPD_NULLPTR;
Y
Yu Yang 已提交
43
  auto ptr = cast(mat);
Y
Yu Yang 已提交
44 45
  if (ptr->mat == nullptr) return kPD_NULLPTR;
  if (rowID >= ptr->mat->getHeight()) return kPD_OUT_OF_RANGE;
Y
Yu Yang 已提交
46 47 48 49 50 51 52
  paddle::real* buf = ptr->mat->getRowBuf(rowID);
  size_t width = ptr->mat->getWidth();
#ifndef PADDLE_ONLY_CPU
  hl_memcpy(buf, rowArray, sizeof(paddle::real) * width);
#else
  std::copy(rowArray, rowArray + width, buf);
#endif
Y
Yu Yang 已提交
53
  return kPD_NO_ERROR;
Y
Yu Yang 已提交
54 55 56
}

int PDMatGetRow(PD_Matrix mat, uint64_t rowID, pd_real** rawRowBuffer) {
Y
Yu Yang 已提交
57
  if (mat == nullptr) return kPD_NULLPTR;
Y
Yu Yang 已提交
58
  auto ptr = cast(mat);
Y
Yu Yang 已提交
59 60
  if (ptr->mat == nullptr) return kPD_NULLPTR;
  if (rowID >= ptr->mat->getHeight()) return kPD_OUT_OF_RANGE;
Y
Yu Yang 已提交
61
  *rawRowBuffer = ptr->mat->getRowBuf(rowID);
Y
Yu Yang 已提交
62
  return kPD_NO_ERROR;
Y
Yu Yang 已提交
63 64 65
}

int PDMatGetShape(PD_Matrix mat, uint64_t* height, uint64_t* width) {
Y
Yu Yang 已提交
66
  if (mat == nullptr) return kPD_NULLPTR;
Y
Yu Yang 已提交
67 68 69 70 71 72
  if (height != nullptr) {
    *height = cast(mat)->mat->getHeight();
  }
  if (width != nullptr) {
    *width = cast(mat)->mat->getWidth();
  }
Y
Yu Yang 已提交
73
  return kPD_NO_ERROR;
Y
Yu Yang 已提交
74 75
}
}