Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Hackathon 5th No.123】 Support r to p on cross mesh #59367

Merged
merged 6 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions paddle/fluid/pybind/auto_parallel_py.cc
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ void BindAutoParallel(py::module *m) {
*m, "RToPReshardFunction", ReshardFunction)
.def(py::init<>());

py::class_<phi::distributed::RToPReshardFunctionCrossMesh>(
*m, "RToPReshardFunctionCrossMesh", ReshardFunction)
.def(py::init<>());

py::class_<phi::distributed::PToRReshardFunction>(
*m, "PToRReshardFunction", ReshardFunction)
.def(py::init<>());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include "paddle/phi/core/distributed/auto_parallel/dist_attr.h"
#include "paddle/phi/core/distributed/auto_parallel/dist_tensor.h"
#include "paddle/phi/core/distributed/auto_parallel/reshard/reshard_utils.h"
#include "paddle/phi/core/distributed/auto_parallel/reshard/same_status_reshard_function.h"
#include "paddle/phi/kernels/assign_kernel.h"
#include "paddle/phi/kernels/full_kernel.h"

Expand Down Expand Up @@ -70,5 +71,48 @@ void RToPReshardFunction::Eval(phi::DeviceContext* dev_ctx,
SetDistProps(out, in.dims(), out_dist_attr);
}

bool RToPReshardFunctionCrossMesh::IsSuitable(
const DistTensor& in, const TensorDistAttr& out_dist_attr) {
const auto& in_dist_attr = in.dist_attr();

RESHARD_SHORTCUT_IF_FALSE(in_dist_attr.is_replicated());
RESHARD_SHORTCUT_IF_FALSE(out_dist_attr.is_partial());

const auto& in_process_mesh = in_dist_attr.process_mesh();
const auto& out_process_mesh = out_dist_attr.process_mesh();

RESHARD_SHORTCUT_IF_FALSE(in_process_mesh.ndim() == 1);
RESHARD_SHORTCUT_IF_FALSE(out_process_mesh.ndim() == 1);
RESHARD_SHORTCUT_IF_FALSE(in_process_mesh.shape() ==
out_process_mesh.shape());
RESHARD_SHORTCUT_IF_FALSE(in_process_mesh != out_process_mesh);

return true;
}

void RToPReshardFunctionCrossMesh::Eval(phi::DeviceContext* dev_ctx,
const DistTensor& in,
const TensorDistAttr& out_dist_attr,
DistTensor* out) {
VLOG(3) << "Call RToPReshardFunctionCrossMesh Eval";
const auto& out_process_mesh = out_dist_attr.process_mesh();

DistTensor tmp_result;

SameStatusReshardFunction same_status_func;
TensorDistAttr tmp_dist_attr = in.dist_attr();
tmp_dist_attr.set_process_mesh(out_process_mesh);
same_status_func.Eval(dev_ctx, in, tmp_dist_attr, &tmp_result);

RToPReshardFunction r_to_p_func;
PADDLE_ENFORCE(
r_to_p_func.IsSuitable(tmp_result, out_dist_attr),
phi::errors::InvalidArgument(
"Invoke the r to p reshard function is not valid from %s to %s.",
tmp_result.dist_attr(),
out_dist_attr));
r_to_p_func.Eval(dev_ctx, tmp_result, out_dist_attr, out);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

忘了把这个reshard策略注册进单例了

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


} // namespace distributed
} // namespace phi
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,18 @@ class RToPReshardFunction final : public ReshardFunction {
std::string Name() override { return "RToPReshard"; }
};

class RToPReshardFunctionCrossMesh final : public ReshardFunction {
public:
bool IsSuitable(const DistTensor& in,
const TensorDistAttr& out_dist_attr) override;

void Eval(DeviceContext* dev_ctx,
const DistTensor& in,
const TensorDistAttr& out_dist_attr,
DistTensor* out) override;

std::string Name() override { return "RToPReshardCrossMesh"; }
};

} // namespace distributed
} // namespace phi
75 changes: 75 additions & 0 deletions test/auto_parallel/reshard_r_to_p_cross_mesh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Copyright (c) 2023 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.

import os

import numpy as np

import paddle
import paddle.distributed as dist
from paddle.base import core


class TestReshardRToPCrossMesh:
def __init__(self):
self._shape = eval(os.getenv("shape"))
self._dtype = os.getenv("dtype")
self._seeds = eval(os.getenv("seeds"))
self._shard = eval(os.getenv("shard"))
self._backend = os.getenv("backend")
self._in_mesh = dist.ProcessMesh([0, 1], dim_names=["x"])
self._out_mesh = dist.ProcessMesh([1, 0], dim_names=["x"])

def run_test_case(self):
# cpu does not support send/recv
if self._backend == "cpu":
return
elif self._backend == "gpu":
place = paddle.CUDAPlace(dist.get_rank())

dev_ctx = core.DeviceContext.create(place)
a = paddle.ones(self._shape)

in_shard_specs = [None for i in range(len(self._shape))]
out_shard_specs = [None for i in range(len(self._shape))]

dist_attr = dist.DistAttr(
mesh=self._in_mesh, sharding_specs=in_shard_specs
)
out_dist_attr = dist.DistAttr(
mesh=self._out_mesh, sharding_specs=out_shard_specs
)
out_dist_attr._set_partial_dims([0])

input_tensor = dist.shard_tensor(a, dist_attr=dist_attr)

reshard_func = core.RToPReshardFunctionCrossMesh()
assert reshard_func.is_suitable(input_tensor, out_dist_attr)

out = reshard_func.eval(dev_ctx, input_tensor, out_dist_attr)

if dist.get_rank() == 1:
np.testing.assert_equal(
out._local_value().numpy(), input_tensor.numpy()
)
else:
zeros = paddle.zeros(self._shape)
np.testing.assert_equal(out._local_value().numpy(), zeros.numpy())

assert np.equal(out.shape, input_tensor.shape).all()
assert np.equal(out._local_shape, input_tensor._local_shape).all()


if __name__ == '__main__':
TestReshardRToPCrossMesh().run_test_case()
14 changes: 13 additions & 1 deletion test/auto_parallel/test_reshard_r_to_p.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ def setUp(self):
self._default_envs = {
"shape": "(10, 20)",
"dtype": "float32",
"seeds": str(self._seeds),
"seeds": "2023",
}
self._changeable_envs = {
"shape": ["(10, 20)"],
"shard": ["0", "1"],
"backend": ["cpu", "gpu"],
}

Expand All @@ -40,6 +41,17 @@ def test_reshard_r_to_p(self):
user_defined_envs=envs,
)

def test_reshard_r_to_p_cross_mesh(self):
envs_list = test_base.gen_product_envs_list(
self._default_envs, self._changeable_envs
)
for envs in envs_list:
if envs["backend"] != "cpu":
self.run_test_case(
"reshard_r_to_p_cross_mesh.py",
user_defined_envs=envs,
)


if __name__ == "__main__":
unittest.main()