Lunderberg commented on code in PR #16098:
URL: https://github.com/apache/tvm/pull/16098#discussion_r1391204352
##########
python/tvm/relax/op/distributed/distributed.py:
##########
@@ -59,3 +59,28 @@ def redistribute(input: Expr, device_mesh: DeviceMesh,
placement: Placement) ->
The tensor after redistribution.
"""
return _ffi_api.redistribute(input, device_mesh, placement) # type: ignore
+
+
+def redistribute_replica_to_shard(input: Expr, num_workers: int, axis: int) ->
Expr:
Review Comment:
I think we should change the type of `num_workers` from `int` to `Expr`.
That allows the number of workers to be a symbolic variable. It doesn't
require any runtime support, as the symbolic variable would be specialized
later on, but this is very useful when writing generic implementations.
##########
python/tvm/relax/op/distributed/distributed.py:
##########
@@ -59,3 +59,28 @@ def redistribute(input: Expr, device_mesh: DeviceMesh,
placement: Placement) ->
The tensor after redistribution.
"""
return _ffi_api.redistribute(input, device_mesh, placement) # type: ignore
+
+
+def redistribute_replica_to_shard(input: Expr, num_workers: int, axis: int) ->
Expr:
+ """Slice tensor into several parts along one axis,
+ and each worker takes one part.
+ Assumes input is already broadcasted.
+ This is a specialized version of redistribute op.
+
+ Parameters
+ ----------
+ input : relax.Expr
+ The buffer to be sliced into equal parts.
+
+ num_worker : int
Review Comment:
Do we require that `input.struct_info.shape[axis] % num_worker == 0`? If
so, we should document whether that is an assumption on the input shape, or an
error condition that is checked by TVM.
##########
python/tvm/relax/op/distributed/distributed.py:
##########
@@ -59,3 +59,28 @@ def redistribute(input: Expr, device_mesh: DeviceMesh,
placement: Placement) ->
The tensor after redistribution.
"""
return _ffi_api.redistribute(input, device_mesh, placement) # type: ignore
+
+
+def redistribute_replica_to_shard(input: Expr, num_workers: int, axis: int) ->
Expr:
+ """Slice tensor into several parts along one axis,
+ and each worker takes one part.
+ Assumes input is already broadcasted.
Review Comment:
What does "assumes input is already broadcasted" mean in this context? From
the "redistribute" in the name, I would assume that this function transfers
data between multiple workers. However, from the "assumes input is already
broadcasted", that sounds like the input has already been broadcasted to each
worker, and each worker already has an independent copy.
##########
python/tvm/relax/distributed/transform/transform.py:
##########
@@ -30,3 +30,14 @@ def PropagateSharding() -> tvm.ir.transform.Pass:
The registered pass
"""
return _ffi_api.PropagateSharding() # type: ignore
+
+
+def LegalizeRedistribute() -> tvm.ir.transform.Pass:
+ """Legalize redistribute op to ccl op.
Review Comment:
Can we state the specific operation name that is being legalized
(`"relax.dist.redistribute_replica_to_shard"`)? That makes it much more
informative for a reader.
##########
python/tvm/relax/transform/legalize_ops/distributed.py:
##########
@@ -0,0 +1,54 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+# pylint: disable=invalid-name
+"""Default legalization function for distir-related operators."""
+from tvm import tir, te
+from ...block_builder import BlockBuilder
+from ...expr import Call, Expr
+from ...op import call_pure_packed
+from ...struct_info import ShapeStructInfo
+from .common import register_legalize
+
+
+@register_legalize("relax.dist.redistribute_replica_to_shard")
+def _redistribute_replica_to_shard(_bb: BlockBuilder, call: Call) -> Expr:
+ num_workers = call.attrs.num_workers
+ axis = call.attrs.axis
+ worker_id_symbol = tir.Var("worker_id", "int64")
+ worker_id_var = _bb.emit(
+ call_pure_packed("runtime.disco.worker_id",
sinfo_args=[ShapeStructInfo(None)])
+ )
+ _bb.match_cast(worker_id_var, ShapeStructInfo([worker_id_symbol]))
+
+ def te_R_to_S(tensor, worker_id):
Review Comment:
This looks like a duplicate of `R.strided_slice`. Instead of duplicating
the TE definition, we should delegate to the existing implementation.
```python
split_axis_size = call.args[0].struct_info.shape[axis]
return relax.op.strided_slice(
call.args[0],
axes=[axis],
begin=[worker_id_symbol * split_axis_size // num_workers],
end=[(worker_id_symbol+1) * split_axis_size // num_workers],
)
```
##########
src/relax/distributed/transform/legalize_redistribute.cc:
##########
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+/*!
+ * \file tvm/relax/distributed/transform/legalize_redistribute.cc
+ * \brief Pass for legalizing redistribute op to ccl op.
+ */
+
+#include <tvm/relax/attrs/ccl.h>
+#include <tvm/relax/attrs/distributed.h>
+#include <tvm/relax/distributed/axis_group_graph.h>
+#include <tvm/relax/distributed/transform.h>
+#include <tvm/relax/expr_functor.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "../../../tir/schedule/transform.h"
+#include "../../op/ccl/ccl.h"
+#include "../../op/distributed/distributed.h"
+
+namespace tvm {
+namespace relax {
+namespace distributed {
+
+class RedistributeLegalizer : public ExprMutator {
+ public:
+ static IRModule LegalizeRedistribute(IRModule mod) {
+ return RedistributeLegalizer(mod).Legalize();
+ }
+
+ private:
+ explicit RedistributeLegalizer(IRModule mod) : ExprMutator(mod) {}
+
+ IRModule Legalize() {
+ auto mod = builder_->GetContextIRModule();
+ for (const auto& [gv, base_func] : mod->functions) {
+ const auto* func_ = base_func.as<FunctionNode>();
+ if (func_ == nullptr) {
+ continue;
+ }
+ Expr new_func_body = VisitExpr(func_->body);
+ auto new_func = make_object<FunctionNode>(*func_);
+ new_func->body = new_func_body;
+ builder_->UpdateFunction(gv, Function(new_func));
+ }
+ return builder_->GetContextIRModule();
+ }
+ using ExprMutator::VisitExpr_;
+ Expr VisitExpr_(const CallNode* op) final {
+ Call call = Downcast<Call>(ExprMutator::VisitExpr_(op));
+ static Op redistribute_op = Op::Get("relax.dist.redistribute");
+ if (call->op.same_as(redistribute_op)) {
+ const auto* attrs = call->attrs.as<DistributionAttrs>();
+ ICHECK(attrs);
+ const auto* input_sinfo =
call->args[0]->struct_info_.as<DTensorStructInfoNode>();
+ ICHECK(input_sinfo);
+ // As the first step, we only support redistribute in the same device
mesh,
+ // and the device mesh must be 1d
+ // todo: extend the ccl ops so that it can support 2d device mesh, and
different sharding
+ // dimension
+ ICHECK(StructuralEqual()(input_sinfo->device_mesh, attrs->device_mesh));
+ ICHECK(input_sinfo->device_mesh->shape.size() == 1);
+ // only support "S[x]"-> "R" and "R" -> "S[x]"
+ PlacementSpec input_spec = input_sinfo->placement->dim_specs[0];
+ PlacementSpec output_spec = attrs->placement->dim_specs[0];
+ if (input_spec->kind == PlacementSpecKind::kReplica &&
+ output_spec->kind == PlacementSpecKind::kReplica) {
+ // "R" -> "R"
+ return call->args[0];
+ } else if (input_spec->kind == PlacementSpecKind::kSharding &&
+ output_spec->kind == PlacementSpecKind::kSharding) {
+ // "S[x]" -> "S[y]"
+ if (input_spec->axis != output_spec->axis) {
+ LOG(FATAL) << "AlltoAll not implemented yet";
+ } else {
+ return call->args[0];
+ }
+ } else if (input_spec->kind == PlacementSpecKind::kSharding &&
+ output_spec->kind == PlacementSpecKind::kReplica) {
+ // "S[x]" -> "R"
+ LOG(FATAL) << "Allgather not implemented yet";
+ } else if (input_spec->kind == PlacementSpecKind::kReplica &&
+ output_spec->kind == PlacementSpecKind::kSharding) {
+ // "R" -> "S[x]"
+ return redistribute_replica_to_shard(call->args[0],
attrs->device_mesh->shape[0],
Review Comment:
Alternatively, would we want to directly produce `relax.op.strided_slice`?
If there aren't any places where the existence of
`redistribute_replica_to_shard` is used for analysis, we wouldn't even need the
intermediate operator.
##########
python/tvm/relax/transform/legalize_ops/distributed.py:
##########
@@ -0,0 +1,54 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+# pylint: disable=invalid-name
+"""Default legalization function for distir-related operators."""
+from tvm import tir, te
+from ...block_builder import BlockBuilder
+from ...expr import Call, Expr
+from ...op import call_pure_packed
+from ...struct_info import ShapeStructInfo
+from .common import register_legalize
+
+
+@register_legalize("relax.dist.redistribute_replica_to_shard")
+def _redistribute_replica_to_shard(_bb: BlockBuilder, call: Call) -> Expr:
+ num_workers = call.attrs.num_workers
Review Comment:
To allow `num_workers: Expr` instead of `num_workers: int`, we should have
`num_workers` provided as an argument with `PrimStructInfo` instead of an
attribute.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]