You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.9 KiB
66 lines
1.9 KiB
8 years ago
|
/* 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
|
||
|
|
||
8 years ago
|
http://www.apache.org/licenses/LICENSE-2.0
|
||
8 years ago
|
|
||
|
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. */
|
||
|
|
||
|
#pragma once
|
||
8 years ago
|
#include <memory.h>
|
||
8 years ago
|
#include <cstring>
|
||
8 years ago
|
|
||
8 years ago
|
#include "paddle/framework/ddim.h"
|
||
8 years ago
|
#include "paddle/framework/eigen.h"
|
||
8 years ago
|
#include "paddle/framework/tensor.h"
|
||
|
#include "paddle/platform/place.h"
|
||
|
|
||
8 years ago
|
namespace paddle {
|
||
|
namespace operators {
|
||
8 years ago
|
|
||
7 years ago
|
using framework::Tensor;
|
||
|
|
||
8 years ago
|
/**
|
||
7 years ago
|
* A thin wrapper for gathering on cpu tensor
|
||
8 years ago
|
* Return a new tensor from source tensor, gathered according to index
|
||
|
* input[src]: type-T source Tensor
|
||
|
* input[index]: type-int index Tensor (1-D)
|
||
|
* return: output tensor
|
||
|
*/
|
||
8 years ago
|
template <typename T>
|
||
7 years ago
|
void CPUGather(const platform::DeviceContext& ctx, const Tensor& src,
|
||
|
const Tensor& index, Tensor* output) {
|
||
7 years ago
|
PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()));
|
||
8 years ago
|
// check index of shape 1-D
|
||
7 years ago
|
PADDLE_ENFORCE(index.dims().size() == 1);
|
||
|
int index_size = index.dims()[0];
|
||
8 years ago
|
|
||
7 years ago
|
auto src_dims = src.dims();
|
||
8 years ago
|
framework::DDim output_dims(src_dims);
|
||
8 years ago
|
output_dims[0] = index_size;
|
||
|
|
||
7 years ago
|
const T* p_src = src.data<T>();
|
||
|
const int* p_index = index.data<int>();
|
||
7 years ago
|
T* p_output = output->data<T>();
|
||
|
|
||
8 years ago
|
// slice size
|
||
|
int slice_size = 1;
|
||
8 years ago
|
for (int i = 1; i < src_dims.size(); ++i) slice_size *= src_dims[i];
|
||
8 years ago
|
|
||
7 years ago
|
const size_t slice_bytes = slice_size * sizeof(T);
|
||
|
|
||
|
for (int i = 0; i < index_size; ++i) {
|
||
|
int index_ = p_index[i];
|
||
|
memcpy(p_output + i * slice_size, p_src + index_ * slice_size, slice_bytes);
|
||
|
}
|
||
8 years ago
|
}
|
||
8 years ago
|
|
||
|
} // namespace operators
|
||
|
} // namespace paddle
|