diff --git a/docs/AI-all-to-all.md b/docs/AI-all-to-all.md index de1fba1..c1440eb 100644 --- a/docs/AI-all-to-all.md +++ b/docs/AI-all-to-all.md @@ -42,6 +42,18 @@ local maximum. It runs an even `alltoall` and unpads the result. This fallback is correct only when every rank has the same largest send chunk, such as the permute pattern. +## Compiler lowering + +`transformAllToAllSingle` in +`third_party/torch-mlir/lib/Conversion/TorchToNeuron/TorchToNeuron.cpp` lowers +uneven `torch._c10d_functional.all_to_all_single` by padding each send chunk +to the input row count, exchanging chunks with one even StableHLO all-to-all, +and trimming received chunks using `output_split_sizes`. Trailing dimensions +are preserved, and zero-size chunks are supported. This path requires static +input shapes and the same input row count on every rank. It is separate from +the eager `alltoall_base` fallback above. + + ## NKI a2a-v buffers and metadata `torch_neuronx/python_ops/nki_kernels/all_to_all_v.py` defines the kernels. diff --git a/third_party/torch-mlir/lib/Conversion/TorchToNeuron/TorchToNeuron.cpp b/third_party/torch-mlir/lib/Conversion/TorchToNeuron/TorchToNeuron.cpp index 845758f..24d7491 100644 --- a/third_party/torch-mlir/lib/Conversion/TorchToNeuron/TorchToNeuron.cpp +++ b/third_party/torch-mlir/lib/Conversion/TorchToNeuron/TorchToNeuron.cpp @@ -23,6 +23,7 @@ #include "torch-mlir/Dialect/TorchConversion/IR/TorchConversionOps.h" #include "torch-mlir/Dialect/TorchConversion/Transforms/BackendTypeConversion.h" #include +#include #include using namespace mlir; @@ -991,26 +992,14 @@ class ConvertNeuronOperatorOp : public OpConversionPattern { // Lower all_to_all_single to StableHLO operations. // - // PyTorch all_to_all_single(input, output_split_sizes, input_split_sizes, - // group) semantics: - // - input_split_sizes[i]: how much data rank i wants from the gathered tensor - // - output_split_sizes[i]: how much data rank i contributes (unused in this - // implementation) - // - Each rank gathers all data, then extracts only what it needs based on - // input_split_sizes + // all_to_all_single(input, output_split_sizes, input_split_sizes, group): + // - input_split_sizes[j] is the number of rows that this rank sends to rank j. + // - output_split_sizes[i] is the number of rows that this rank receives from + // rank i. // - // Two lowering strategies: - // 1. Uniform splits (all elements equal): Use AllToAllOp directly for - // efficiency - // 2. Non-uniform splits: Use AllGatherOp + slice operations to handle permute - // gather patterns - // - AllGatherOp collects all tensors: [rank0_data, rank1_data, ...] - // - Slice operations extract portions based on input_split_sizes - // - Offset calculation: each rank contributes actualRankSize to gathered - // tensor - // - Example: input_splits=[0,4] means rank 0 wants 0 elements, rank 1 - // wants 4 elements - // from gathered tensor layout [rank0_4_elements, rank1_4_elements] + // Uniform splits lower to one AllToAllOp. Non-uniform splits pad each chunk + // to the input row count, exchange the chunks with one even AllToAllOp, and + // trim each received chunk. LogicalResult transformAllToAllSingle(Torch::OperatorOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const { @@ -1019,8 +1008,8 @@ class ConvertNeuronOperatorOp : public OpConversionPattern { return rewriter.notifyMatchFailure(op, "expected 4 operands"); Value input = operands[0]; - Value inputSplitSizes = operands[1]; - Value outputSplitSizes = operands[2]; + Value outputSplitSizes = operands[1]; + Value inputSplitSizes = operands[2]; Value group = operands[3]; // Handle non-uniform split sizes for permute gather @@ -1099,55 +1088,97 @@ class ConvertNeuronOperatorOp : public OpConversionPattern { Value allToAllResult; if ((hasOutputSplits || hasInputSplits) && !isUniform) { - // Use all_gather + slice for non-uniform splits - auto gatheredType = RankedTensorType::get( - {inputType.getDimSize(0) * worldSize}, inputType.getElementType()); - auto allGatherOp = stablehlo::AllGatherOp::create( - rewriter, op.getLoc(), gatheredType, ValueRange{input}, - /*all_gather_dim=*/rewriter.getI64IntegerAttr(0), replicaGroupsAttr, - createChannelHandle(rewriter), - /*use_global_device_ids=*/rewriter.getUnitAttr()); - - SmallVector inputSplitSizes = + // The pad size must be equal on all ranks. A rank cannot see the input + // shapes of other ranks, so all ranks must have the same input row count. + if (!inputType.hasStaticShape()) + return rewriter.notifyMatchFailure( + op, "non-uniform all_to_all_single needs a static input shape"); + Location loc = op.getLoc(); + Type elemType = inputType.getElementType(); + int64_t rows = inputType.getDimSize(0); + if ((!hasInputSplits || !hasOutputSplits) && rows % worldSize != 0) + return rewriter.notifyMatchFailure( + op, "input rows are not divisible by the group size"); + SmallVector sendRows = hasInputSplits ? inputSplits - : SmallVector( - worldSize, inputType.getDimSize(0) / worldSize); - SmallVector outputSplitSizes = - hasOutputSplits ? outputSplits : inputSplitSizes; - - SmallVector slices; + : SmallVector(worldSize, rows / worldSize); + SmallVector recvRows = + hasOutputSplits ? outputSplits + : SmallVector(worldSize, rows / worldSize); + if (static_cast(sendRows.size()) != worldSize || + static_cast(recvRows.size()) != worldSize) + return rewriter.notifyMatchFailure( + op, "split size count is not equal to the group size"); + auto outOfRange = [&](int64_t n) { return n < 0 || n > rows; }; + if (std::accumulate(sendRows.begin(), sendRows.end(), int64_t{0}) != + rows || + llvm::any_of(sendRows, outOfRange) || + llvm::any_of(recvRows, outOfRange)) + return rewriter.notifyMatchFailure( + op, "split sizes do not fit the input rows"); + + auto withRows = [&](int64_t n) { + SmallVector shape(inputType.getShape()); + shape[0] = n; + return RankedTensorType::get(shape, elemType); + }; + auto sliceRows = [&](Value v, int64_t start, int64_t n) -> Value { + auto vType = cast(v.getType()); + SmallVector starts(vType.getRank(), 0); + SmallVector limits(vType.getShape()); + SmallVector strides(vType.getRank(), 1); + starts[0] = start; + limits[0] = start + n; + return stablehlo::SliceOp::create( + rewriter, loc, withRows(n), v, + rewriter.getDenseI64ArrayAttr(starts), + rewriter.getDenseI64ArrayAttr(limits), + rewriter.getDenseI64ArrayAttr(strides)); + }; + + Value zero = stablehlo::ConstantOp::create( + rewriter, loc, + cast( + rewriter.getZeroAttr(RankedTensorType::get({}, elemType)))); + SmallVector chunks; int64_t offset = 0; - int64_t actualRankSize = inputType.getDimSize(0); - for (int64_t i = 0; i < worldSize; ++i) { - int64_t inputSize = inputSplitSizes[i]; - if (inputSize > 0) { - auto sliceType = - RankedTensorType::get({inputSize}, inputType.getElementType()); - auto slice = stablehlo::SliceOp::create( - rewriter, op.getLoc(), sliceType, allGatherOp.getResult(0), - rewriter.getDenseI64ArrayAttr({offset}), - rewriter.getDenseI64ArrayAttr({offset + inputSize}), - rewriter.getDenseI64ArrayAttr({1})); - slices.push_back(slice.getResult()); + for (int64_t n : sendRows) { + if (n == rows) { + chunks.push_back(input); + } else if (n == 0) { + chunks.push_back(stablehlo::BroadcastInDimOp::create( + rewriter, loc, withRows(rows), zero, + rewriter.getDenseI64ArrayAttr({}))); + } else { + SmallVector low(inputType.getRank(), 0); + SmallVector high(inputType.getRank(), 0); + high[0] = rows - n; + chunks.push_back(stablehlo::PadOp::create( + rewriter, loc, withRows(rows), sliceRows(input, offset, n), zero, + rewriter.getDenseI64ArrayAttr(low), + rewriter.getDenseI64ArrayAttr(high), + rewriter.getDenseI64ArrayAttr(low))); } - offset += actualRankSize; - } - - if (slices.empty()) { - // All input splits are zero - create empty slice - auto emptyType = RankedTensorType::get({0}, inputType.getElementType()); - allToAllResult = - stablehlo::SliceOp::create(rewriter, op.getLoc(), emptyType, - allGatherOp.getResult(0), - rewriter.getDenseI64ArrayAttr({0}), - rewriter.getDenseI64ArrayAttr({0}), - rewriter.getDenseI64ArrayAttr({1})) - .getResult(); - } else { - allToAllResult = - stablehlo::ConcatenateOp::create(rewriter, op.getLoc(), slices, 0) - .getResult(); + offset += n; } + Value packed = + stablehlo::ConcatenateOp::create(rewriter, loc, chunks, 0); + Value exchanged = + stablehlo::AllToAllOp::create( + rewriter, loc, withRows(rows * worldSize), packed, splitDim, + concatDim, /*split_count=*/worldSize, replicaGroupsAttr, + createChannelHandle(rewriter)) + .getResult(0); + + SmallVector received; + for (int64_t i = 0; i < worldSize; ++i) + if (recvRows[i] > 0) + received.push_back(sliceRows(exchanged, i * rows, recvRows[i])); + allToAllResult = + received.empty() + ? sliceRows(exchanged, 0, 0) + : stablehlo::ConcatenateOp::create(rewriter, loc, received, 0) + .getResult(); } else { auto allToAllOp = stablehlo::AllToAllOp::create( rewriter, op.getLoc(), outType, input, splitDim, concatDim, diff --git a/third_party/torch-mlir/test/Conversion/TorchToNeuron/all-to-all-nonuniform.mlir b/third_party/torch-mlir/test/Conversion/TorchToNeuron/all-to-all-nonuniform.mlir index 9af9b25..0229a68 100644 --- a/third_party/torch-mlir/test/Conversion/TorchToNeuron/all-to-all-nonuniform.mlir +++ b/third_party/torch-mlir/test/Conversion/TorchToNeuron/all-to-all-nonuniform.mlir @@ -1,19 +1,82 @@ -// RUN: env WORLD_SIZE=2 RANK=1 torch-mlir-opt %s -convert-torch-to-neuron -split-input-file | FileCheck %s +// RUN: torch-mlir-opt %s -convert-torch-to-neuron -split-input-file | FileCheck %s -// CHECK-LABEL: func.func @all_to_all_nonuniform -func.func @all_to_all_nonuniform(%arg0: !torch.vtensor<[4],f32>) -> !torch.vtensor<[4],f32> { +// Rank 1 of send = [[1, 3], [2, 2]]: output_split_sizes = [3, 2], input_split_sizes = [2, 2]. +// Each chunk is padded to 4 rows, exchanged with an even all_to_all, then trimmed. + +// CHECK-LABEL: func.func @all_to_all_nonuniform_2d +func.func @all_to_all_nonuniform_2d(%arg0: !torch.vtensor<[4,8],f32>) -> !torch.vtensor<[5,8],f32> { + %int2 = torch.constant.int 2 + %int3 = torch.constant.int 3 + %output_splits = torch.prim.ListConstruct %int3, %int2 : (!torch.int, !torch.int) -> !torch.list + %input_splits = torch.prim.ListConstruct %int2, %int2 : (!torch.int, !torch.int) -> !torch.list + %str = torch.constant.str "[[0, 1]]" + + // CHECK: %[[T0:.*]] = torch_c.to_builtin_tensor %arg0 : !torch.vtensor<[4,8],f32> -> tensor<4x8xf32> + // CHECK: %[[ZERO:.*]] = stablehlo.constant dense<0.000000e+00> : tensor + // CHECK: %[[S0:.*]] = stablehlo.slice %[[T0]] [0:2, 0:8] : (tensor<4x8xf32>) -> tensor<2x8xf32> + // CHECK: %[[P0:.*]] = stablehlo.pad %[[S0]], %[[ZERO]], low = [0, 0], high = [2, 0], interior = [0, 0] : (tensor<2x8xf32>, tensor) -> tensor<4x8xf32> + // CHECK: %[[S1:.*]] = stablehlo.slice %[[T0]] [2:4, 0:8] : (tensor<4x8xf32>) -> tensor<2x8xf32> + // CHECK: %[[P1:.*]] = stablehlo.pad %[[S1]], %[[ZERO]], low = [0, 0], high = [2, 0], interior = [0, 0] : (tensor<2x8xf32>, tensor) -> tensor<4x8xf32> + // CHECK: %[[PACKED:.*]] = stablehlo.concatenate %[[P0]], %[[P1]], dim = 0 : (tensor<4x8xf32>, tensor<4x8xf32>) -> tensor<8x8xf32> + // CHECK: %[[A2A:.*]] = "stablehlo.all_to_all"(%[[PACKED]]) <{channel_handle = {{.*}}, concat_dimension = 0 : i64, replica_groups = dense<{{\[\[}}0, 1]]> : tensor<1x2xi64>, split_count = 2 : i64, split_dimension = 0 : i64}> : (tensor<8x8xf32>) -> tensor<8x8xf32> + // CHECK: %[[R0:.*]] = stablehlo.slice %[[A2A]] [0:3, 0:8] : (tensor<8x8xf32>) -> tensor<3x8xf32> + // CHECK: %[[R1:.*]] = stablehlo.slice %[[A2A]] [4:6, 0:8] : (tensor<8x8xf32>) -> tensor<2x8xf32> + // CHECK: %[[OUT:.*]] = stablehlo.concatenate %[[R0]], %[[R1]], dim = 0 : (tensor<3x8xf32>, tensor<2x8xf32>) -> tensor<5x8xf32> + // CHECK: torch_c.from_builtin_tensor %[[OUT]] : tensor<5x8xf32> -> !torch.vtensor<[5,8],f32> + %result = torch.operator "torch._c10d_functional.all_to_all_single"(%arg0, %output_splits, %input_splits, %str) : (!torch.vtensor<[4,8],f32>, !torch.list, !torch.list, !torch.str) -> !torch.vtensor<[5,8],f32> + + return %result : !torch.vtensor<[5,8],f32> +} + +// ----- + +// Rank 0 of send = [[1, 3], [2, 2]]: output_split_sizes = [1, 2], input_split_sizes = [1, 3]. + +// CHECK-LABEL: func.func @all_to_all_nonuniform_1d +func.func @all_to_all_nonuniform_1d(%arg0: !torch.vtensor<[4],f32>) -> !torch.vtensor<[3],f32> { + %int1 = torch.constant.int 1 + %int2 = torch.constant.int 2 + %int3 = torch.constant.int 3 + %output_splits = torch.prim.ListConstruct %int1, %int2 : (!torch.int, !torch.int) -> !torch.list + %input_splits = torch.prim.ListConstruct %int1, %int3 : (!torch.int, !torch.int) -> !torch.list + %str = torch.constant.str "[[0, 1]]" + + // CHECK: %[[T0:.*]] = torch_c.to_builtin_tensor %arg0 : !torch.vtensor<[4],f32> -> tensor<4xf32> + // CHECK: %[[ZERO:.*]] = stablehlo.constant dense<0.000000e+00> : tensor + // CHECK: %[[S0:.*]] = stablehlo.slice %[[T0]] [0:1] : (tensor<4xf32>) -> tensor<1xf32> + // CHECK: %[[P0:.*]] = stablehlo.pad %[[S0]], %[[ZERO]], low = [0], high = [3], interior = [0] : (tensor<1xf32>, tensor) -> tensor<4xf32> + // CHECK: %[[S1:.*]] = stablehlo.slice %[[T0]] [1:4] : (tensor<4xf32>) -> tensor<3xf32> + // CHECK: %[[P1:.*]] = stablehlo.pad %[[S1]], %[[ZERO]], low = [0], high = [1], interior = [0] : (tensor<3xf32>, tensor) -> tensor<4xf32> + // CHECK: %[[PACKED:.*]] = stablehlo.concatenate %[[P0]], %[[P1]], dim = 0 : (tensor<4xf32>, tensor<4xf32>) -> tensor<8xf32> + // CHECK: %[[A2A:.*]] = "stablehlo.all_to_all"(%[[PACKED]]) {{.*}} : (tensor<8xf32>) -> tensor<8xf32> + // CHECK: %[[R0:.*]] = stablehlo.slice %[[A2A]] [0:1] : (tensor<8xf32>) -> tensor<1xf32> + // CHECK: %[[R1:.*]] = stablehlo.slice %[[A2A]] [4:6] : (tensor<8xf32>) -> tensor<2xf32> + // CHECK: %[[OUT:.*]] = stablehlo.concatenate %[[R0]], %[[R1]], dim = 0 : (tensor<1xf32>, tensor<2xf32>) -> tensor<3xf32> + %result = torch.operator "torch._c10d_functional.all_to_all_single"(%arg0, %output_splits, %input_splits, %str) : (!torch.vtensor<[4],f32>, !torch.list, !torch.list, !torch.str) -> !torch.vtensor<[3],f32> + + return %result : !torch.vtensor<[3],f32> +} + +// ----- + +// Rank 1 of send = [[0, 4], [4, 0]]: a zero-size chunk becomes a zero block of 4 rows. + +// CHECK-LABEL: func.func @all_to_all_nonuniform_zero_chunk +func.func @all_to_all_nonuniform_zero_chunk(%arg0: !torch.vtensor<[4,2],f32>) -> !torch.vtensor<[4,2],f32> { %int0 = torch.constant.int 0 %int4 = torch.constant.int 4 - %input_splits = torch.prim.ListConstruct %int0, %int4 : (!torch.int, !torch.int) -> !torch.list - %output_splits = torch.prim.ListConstruct %int0, %int4 : (!torch.int, !torch.int) -> !torch.list + %output_splits = torch.prim.ListConstruct %int4, %int0 : (!torch.int, !torch.int) -> !torch.list + %input_splits = torch.prim.ListConstruct %int4, %int0 : (!torch.int, !torch.int) -> !torch.list %str = torch.constant.str "[[0, 1]]" - // CHECK: %[[T0:.*]] = torch_c.to_builtin_tensor %arg0 : !torch.vtensor<[4],f32> -> tensor<4xf32> - // CHECK: %[[GATHER:.*]] = "stablehlo.all_gather"(%[[T0]]) <{all_gather_dim = 0 : i64, channel_handle = {{.*}}, replica_groups = dense<{{\[\[}}0, 1]]> : tensor<1x2xi64>, use_global_device_ids}> : (tensor<4xf32>) -> tensor<8xf32> - // CHECK: %[[SLICE:.*]] = stablehlo.slice %[[GATHER]] [4:8] : (tensor<8xf32>) -> tensor<4xf32> - // CHECK: %[[CONCAT:.*]] = stablehlo.concatenate %[[SLICE]], dim = 0 : (tensor<4xf32>) -> tensor<4xf32> - // CHECK: %[[T1:.*]] = torch_c.from_builtin_tensor %[[CONCAT]] : tensor<4xf32> -> !torch.vtensor<[4],f32> - %result = torch.operator "torch._c10d_functional.all_to_all_single"(%arg0, %input_splits, %output_splits, %str) : (!torch.vtensor<[4],f32>, !torch.list, !torch.list, !torch.str) -> !torch.vtensor<[4],f32> + // CHECK: %[[T0:.*]] = torch_c.to_builtin_tensor %arg0 : !torch.vtensor<[4,2],f32> -> tensor<4x2xf32> + // CHECK: %[[ZERO:.*]] = stablehlo.constant dense<0.000000e+00> : tensor + // CHECK: %[[EMPTY:.*]] = stablehlo.broadcast_in_dim %[[ZERO]], dims = [] : (tensor) -> tensor<4x2xf32> + // CHECK: %[[PACKED:.*]] = stablehlo.concatenate %[[T0]], %[[EMPTY]], dim = 0 : (tensor<4x2xf32>, tensor<4x2xf32>) -> tensor<8x2xf32> + // CHECK: %[[A2A:.*]] = "stablehlo.all_to_all"(%[[PACKED]]) {{.*}} : (tensor<8x2xf32>) -> tensor<8x2xf32> + // CHECK: %[[R0:.*]] = stablehlo.slice %[[A2A]] [0:4, 0:2] : (tensor<8x2xf32>) -> tensor<4x2xf32> + // CHECK: %[[OUT:.*]] = stablehlo.concatenate %[[R0]], dim = 0 : (tensor<4x2xf32>) -> tensor<4x2xf32> + %result = torch.operator "torch._c10d_functional.all_to_all_single"(%arg0, %output_splits, %input_splits, %str) : (!torch.vtensor<[4,2],f32>, !torch.list, !torch.list, !torch.str) -> !torch.vtensor<[4,2],f32> - return %result : !torch.vtensor<[4],f32> + return %result : !torch.vtensor<[4,2],f32> }