1 //
2 //  GeometryReduce.cpp
3 //  MNN
4 //
5 //  Created by MNN on 2020/06/09.
6 //  Copyright © 2018, Alibaba Group Holding Limited
7 //
8 
9 #include "geometry/GeometryComputer.hpp"
10 #include "geometry/GeometryComputerUtils.hpp"
11 #include "core/OpCommonUtils.hpp"
12 namespace MNN {
13 class GeometryReduce : public GeometryComputer {
14 public:
onCompute(const Op * op,const std::vector<Tensor * > & inputs,const std::vector<Tensor * > & outputs,Context & context,CommandBuffer & res) const15     virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
16                            Context& context, CommandBuffer& res) const override {
17         MNN_ASSERT(1 == outputs.size());
18         MNN_ASSERT(inputs.size() >= 1);
19         auto reduceDims      = OpCommonUtils::computeReduceDims(inputs, op);
20         auto reduct          = op->main_as_ReductionParam();
21         auto reductOp        = reduct->operation();
22         Tensor* currentInput = inputs[0];
23         MNN_ASSERT(reduceDims.size() > 0);
24         auto dimType = currentInput->getDimensionType();
25         for (int i = 0; i < reduceDims.size(); ++i) {
26             auto& iter   = reduceDims[i];
27             auto inside  = std::get<2>(iter);
28             auto outside = std::get<0>(iter);
29             auto axis    = std::get<1>(iter);
30 
31             std::shared_ptr<Tensor> inputTensor(
32                 Tensor::createDevice({outside, axis, inside}, inputs[0]->getType(), dimType));
33             auto des        = TensorUtils::getDescribe(inputTensor.get());
34             des->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL;
35             des->regions    = {TensorUtils::makeFullSlice(currentInput)};
36             res.extras.emplace_back(inputTensor);
37             std::shared_ptr<Tensor> outputTensor(
38                 Tensor::createDevice({outside, 1, inside}, inputs[0]->getType(), dimType));
39             res.extras.emplace_back(outputTensor);
40 
41             // Create Command
42             {
43                 auto cmd = GeometryComputerUtils::makeReduce(reductOp, inputTensor.get(), outputTensor.get());
44                 res.command.emplace_back(std::move(cmd));
45             }
46             currentInput = outputTensor.get();
47             // Ref output
48             if (i == reduceDims.size() - 1) {
49                 auto outputDes        = TensorUtils::getDescribe(outputs[0]);
50                 outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL;
51                 outputDes->regions    = {TensorUtils::makeFullSlice(outputTensor.get())};
52             }
53         }
54         return true;
55     }
56 };
_create()57 static void _create() {
58     std::shared_ptr<GeometryComputer> comp(new GeometryReduce);
59     GeometryComputer::registerGeometryComputer(comp, {OpType_Reduction});
60 }
61 
62 REGISTER_GEOMETRY(GeometryReduce, _create);
63 
64 } // namespace MNN
65