/* 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. */ #pragma once #include "paddle/framework/eigen.h" #include "paddle/framework/op_registry.h" namespace paddle { namespace operators { template class MultiplexCPUKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& ctx) const { auto ins = ctx.MultiInput("X"); auto* out = ctx.Output("Out"); out->mutable_data(ctx.GetPlace()); auto index = ins[0]->data(); auto rows = ins[1]->dims()[0]; auto cols = ins[1]->dims()[1]; for (auto i = 0; i < rows; i++) { int k = (int)index[i] + 1; memcpy(out->data() + i * cols, ins[k]->data() + i * cols, cols * sizeof(T)); } } }; template class MultiplexGradCPUKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& ctx) const { auto* d_out = ctx.Input(framework::GradVarName("Out")); auto ins = ctx.MultiInput("X"); auto d_ins = ctx.MultiOutput(framework::GradVarName("X")); for (auto d_in : d_ins) { d_in->mutable_data(ctx.GetPlace()); auto dims = d_in->dims(); memset(d_in->data(), 0, framework::product(dims) * sizeof(T)); } auto index = ins[0]->data(); auto rows = ins[1]->dims()[0]; auto cols = ins[1]->dims()[1]; for (auto i = 0; i < rows; i++) { int k = (int)index[i] + 1; memcpy(d_ins[k]->data() + i * cols, d_out->data() + i * cols, cols * sizeof(T)); } } }; } }