/* Copyright (c) 2016 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. */ #pragma once #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/memory/memcpy.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 ids = ctx.Input("Ids"); auto* out = ctx.Output("Out"); out->mutable_data(ctx.GetPlace()); for (size_t i = 0; i < ins.size(); ++i) { PADDLE_ENFORCE_GT( ins[i]->numel(), 0, platform::errors::OutOfRange( "indexing will be out of bounds with size 0 for the %d-th input.", i)); } auto rows = ins[0]->dims()[0]; auto cols = ins[0]->numel() / rows; auto index = ids->data(); platform::CPUPlace place = BOOST_GET_CONST(platform::CPUPlace, ctx.GetPlace()); for (auto i = 0; i < rows; i++) { int32_t k = index[i]; PADDLE_ENFORCE_GE(k, 0, platform::errors::PreconditionNotMet( "index must be nonnegative.")); PADDLE_ENFORCE_LT(static_cast(k), ins.size(), platform::errors::PreconditionNotMet( "index exceeds the number of candidate tensors.")); memory::Copy(place, out->data() + i * cols, place, 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* ids = ctx.Input("Ids"); auto d_ins = ctx.MultiOutput(framework::GradVarName("X")); size_t idx = -1UL; for (size_t i = 0; i < d_ins.size(); i++) { if (d_ins[i]) { d_ins[i]->mutable_data(ctx.GetPlace()); auto t = framework::EigenVector::Flatten(*d_ins[i]); t.device(*ctx.template device_context().eigen_device()) = t.constant(static_cast(0)); idx = i; } } if (idx == -1UL) return; auto rows = d_ins[idx]->dims()[0]; auto cols = d_ins[idx]->numel() / rows; auto* index = ids->data(); platform::CPUPlace place = BOOST_GET_CONST(platform::CPUPlace, ctx.GetPlace()); for (auto i = 0; i < rows; i++) { size_t k = static_cast(index[i]); if (d_ins[k]) { memory::Copy(place, d_ins[k]->data() + i * cols, place, d_out->data() + i * cols, cols * sizeof(T)); } } } }; } // namespace operators } // namespace paddle