implement parallel BroadcastTo

pull/7090/head
Yi Huaijie 5 years ago
parent c1b9efe8e6
commit 45d373d40e

@ -172,6 +172,8 @@ using TransposeCost = ActivationCost;
using TransposeCostPtr = std::shared_ptr<TransposeCost>;
using StridedSliceCost = ActivationCost;
using StridedSliceCostPtr = std::shared_ptr<StridedSliceCost>;
using SplitCost = ActivationCost;
using SplitCostPtr = std::shared_ptr<SplitCost>;
class SoftmaxCost : public OperatorCost {
public:
@ -203,8 +205,8 @@ using PackCost = TileCost;
using PackCostPtr = std::shared_ptr<PackCost>;
using ConcatCost = TileCost;
using ConcatCostPtr = std::shared_ptr<ConcatCost>;
using SplitCost = TileCost;
using SplitCostPtr = std::shared_ptr<SplitCost>;
using BroadcastToCost = SoftmaxCost;
using BroadcastToCostPtr = std::shared_ptr<BroadcastToCost>;
class TmpIdentityCost : public OperatorCost {
public:

@ -176,6 +176,7 @@ REGISTER(SquareInfo);
REGISTER(GatherV2PInfo);
REGISTER(EmbeddingLookupInfo);
REGISTER(TileInfo);
REGISTER(BroadcastToInfo);
REGISTER(StridedSliceInfo);
REGISTER(DropoutInfo);
REGISTER(PackInfo);

@ -0,0 +1,64 @@
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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.
*/
#ifndef MINDSPORE_CCSRC_FRONTEND_PARALLEL_OPS_INFO_BROADCAST_TO_INFO_H_
#define MINDSPORE_CCSRC_FRONTEND_PARALLEL_OPS_INFO_BROADCAST_TO_INFO_H_
#include <string>
#include <memory>
#include <unordered_map>
#include <vector>
#include "ir/value.h"
#include "frontend/parallel/auto_parallel/operator_costmodel.h"
#include "frontend/parallel/ops_info/operator_info.h"
#include "frontend/parallel/strategy.h"
namespace mindspore {
namespace parallel {
/*
* Limitation: Dimensions with size 1 can't be splited.
*/
class BroadcastToInfo : public OperatorInfo {
public:
BroadcastToInfo(const std::string &operator_name, const Shapes &inputs_shape, const Shapes &outputs_shape,
const PrimitiveAttrs &attrs)
: OperatorInfo(operator_name, inputs_shape, outputs_shape, attrs, std::make_shared<BroadcastToCost>(false)) {}
~BroadcastToInfo() override = default;
Status Init(const StrategyPtr &strategy) override;
Status InitForCostModel(const StrategyPtr &strategy) override;
Status GenerateStrategies(int32_t) override;
Status SetCostUnderStrategy(const StrategyPtr &) override;
ReplaceGraphPtr replace_graph(const CNodePtr &cnode) override;
protected:
Status GetAttrs() override;
Status CheckStrategy(const StrategyPtr &strategy) override;
Status InferMirrorOps() override;
Status InferForwardCommunication() override { return SUCCESS; }
Status InferTensorInfo() override;
Status InferDevMatrixShape() override;
Status InferTensorMap() override;
Status ComputeReplaceGraph(const CNodePtr &cnode);
private:
Shape out_shape_;
};
} // namespace parallel
} // namespace mindspore
#endif // MINDSPORE_CCSRC_FRONTEND_PARALLEL_OPS_INFO_BROADCAST_TO_INFO_H_

@ -42,5 +42,6 @@
#include "frontend/parallel/ops_info/concat_info.h"
#include "frontend/parallel/ops_info/split_info.h"
#include "frontend/parallel/ops_info/pack_info.h"
#include "frontend/parallel/ops_info/broadcast_to_info.h"
#endif // MINDSPORE_CCSRC_FRONTEND_PARALLEL_OPS_INFO_HEAD_FILES_H_

@ -222,6 +222,7 @@ constexpr char GATHERV2[] = "GatherV2";
constexpr char SPARSE_GATHERV2[] = "SparseGatherV2";
constexpr char STRIDEDSLICE[] = "StridedSlice";
constexpr char BROADCAST[] = "Broadcast";
constexpr char BROADCAST_TO[] = "BroadcastTo";
constexpr char SQRT[] = "Sqrt";
constexpr char ASSIGN[] = "Assign";
constexpr char GET_NEXT[] = "GetNext";

@ -265,7 +265,7 @@ bool IsSplittableOperator(const std::string &op_name) {
LOG, REDUCE_MEAN, REAL_DIV, SIGMOID, POW, MAXIMUM, MINIMUM, EQUAL, NOT_EQUAL, LOGICALNOT, GATHERV2, SQRT, CONCAT,
STRIDEDSLICE, GET_NEXT, CAST, NEG, SQUARE, BATCH_MATMUL, EXPAND_DIMS, SQUEEZE, SPARSE_GATHERV2, TILE, DROPOUT,
SOFTMAX_CROSS_ENTROPY_WITH_LOGITS, SIGMOID_CROSS_ENTROPY_WITH_LOGITS, SPARSE_SOFTMAX_CROSS_ENTROPY_WITH_LOGITS,
EMBEDDING_LOOKUP, FUSE_BATCH_NORM_EX, SPLIT};
EMBEDDING_LOOKUP, FUSE_BATCH_NORM_EX, SPLIT, BROADCAST_TO};
// clang-format on
auto iter = splittable_op.find(op_name);

@ -0,0 +1,112 @@
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
import numpy as np
import mindspore as ms
import mindspore.context as context
from mindspore import Tensor, Parameter
import mindspore.nn as nn
from mindspore.common.api import _executor
from mindspore.nn import TrainOneStepCell, Momentum
from mindspore.ops import operations as P
class Net(nn.Cell):
def __init__(self, weight1, strategy1=None, strategy2=None, is_parameter=True):
super(Net, self).__init__()
self.shape = (8, 48, 64)
self.broadcast = P.BroadcastTo(self.shape).shard(strategy1)
self.mul = P.Mul().shard(strategy2)
if is_parameter:
self.weight1 = Parameter(weight1, "w1")
else:
self.weight1 = weight1
def construct(self, x):
out = self.broadcast(self.weight1)
out = self.mul(x, out)
return out
class MatMulNet(nn.Cell):
def __init__(self, weight1, strategy1=None, strategy2=None, strategy3=None, is_parameter=True):
super(MatMulNet, self).__init__()
self.shape = (8, 64, 64)
self.broadcast = P.BroadcastTo(self.shape).shard(strategy1)
self.matmul = P.BatchMatMul().shard(strategy2)
self.mul = P.Mul().shard(strategy3)
if is_parameter:
self.weight1 = Parameter(weight1, "w1")
else:
self.weight1 = weight1
def construct(self, x1, x2):
out = self.broadcast(x2)
out = self.matmul(x1, out)
out = self.mul(out, self.weight1)
return out
_w1 = Tensor(np.ones([1, 48, 64]), dtype=ms.float32)
_x1 = Tensor(np.ones([8, 48, 64]), dtype=ms.float32)
_x2 = Tensor(np.ones([64, 64]), dtype=ms.float32)
def compile_net(net):
context.set_context(mode=context.GRAPH_MODE, save_graphs=True)
optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
train_net = TrainOneStepCell(net, optimizer)
train_net.set_auto_parallel()
_executor.compile(train_net, _x1)
context.reset_auto_parallel_context()
def compile_net2(net):
context.set_context(mode=context.GRAPH_MODE, save_graphs=True)
optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
train_net = TrainOneStepCell(net, optimizer)
train_net.set_auto_parallel()
_executor.compile(train_net, _x1, _x2)
context.reset_auto_parallel_context()
def test_BroadcastTo_parameter():
context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=8, global_rank=0)
strategy1 = ((1, 4, 2),)
strategy2 = ((1, 4, 2), (1, 4, 2))
net = Net(_w1, strategy1, strategy2)
compile_net(net)
def test_BroadcastTo_parameter_no_full():
context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=8, global_rank=0)
strategy1 = ((1, 2, 2),)
strategy2 = ((1, 4, 2), (1, 4, 2))
net = Net(_w1, strategy1, strategy2)
compile_net(net)
def test_BroadcastTo_auto_parallel():
context.set_auto_parallel_context(parallel_mode="auto_parallel", device_num=8, global_rank=0)
net = Net(_w1)
compile_net(net)
def test_BroadcastTo_matmul():
context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=8, global_rank=0)
strategy1 = ((2, 4),)
strategy2 = ((1, 1, 2), (1, 2, 4))
strategy3 = ((1, 2, 4), (1, 2, 4))
net = MatMulNet(_w1, strategy1, strategy2, strategy3)
compile_net2(net)
Loading…
Cancel
Save