[MLIR][Linalg] ND tensor.extract vectorization reads an excluded column of a strided subview
Summary
Applying transform.structured.vectorize with vectorize_nd_extract changes the result of the valid program below from 20 to 99.
The program allocates and initializes a row-major memref<2x3xf32>, then uses memref.subview to select its first two columns. The resulting 2x2 view has strides [3, 1]. A linalg.generic reads the first column of the corresponding tensor and should produce [10, 20]. After vectorization, the second lane instead reads the excluded third column of the first row, which contains 99.
This reproduces with standalone mlir-opt and mlir-runner, using only standard MLIR dialects. Both compilation commands and both executions succeed; applying the vectorization transform is the only difference between the two pipelines.
Reproducer
Save as repro.mlir:
module attributes {transform.with_named_sequence} {
func.func @main() -> f32 {
%c0 = arith.constant 0 : index
%c1 = arith.constant 1 : index
%c2 = arith.constant 2 : index
%c3 = arith.constant 3 : index
%f10 = arith.constant 10.0 : f32
%f11 = arith.constant 11.0 : f32
%f99 = arith.constant 99.0 : f32
%f20 = arith.constant 20.0 : f32
%f21 = arith.constant 21.0 : f32
// [10, 11, 99]
// [20, 21, 99]
%storage = memref.alloc() : memref<2x3xf32>
memref.store %f10, %storage[%c0, %c0] : memref<2x3xf32>
memref.store %f11, %storage[%c0, %c1] : memref<2x3xf32>
memref.store %f99, %storage[%c0, %c2] : memref<2x3xf32>
memref.store %f20, %storage[%c1, %c0] : memref<2x3xf32>
memref.store %f21, %storage[%c1, %c1] : memref<2x3xf32>
memref.store %f99, %storage[%c1, %c2] : memref<2x3xf32>
%source = memref.subview %storage[0, 0] [2, 2] [1, 1]
: memref<2x3xf32> to memref<2x2xf32, strided<[3, 1]>>
%tensor = bufferization.to_tensor %source restrict
: memref<2x2xf32, strided<[3, 1]>> to tensor<2x2xf32>
%empty = tensor.empty() : tensor<2xf32>
%result = linalg.generic {
indexing_maps = [affine_map<(i) -> (i)>],
iterator_types = ["parallel"]
} outs(%empty : tensor<2xf32>) {
^bb0(%unused: f32):
%i = linalg.index 0 : index
%value = tensor.extract %tensor[%i, %c0] : tensor<2x2xf32>
linalg.yield %value : f32
} -> tensor<2xf32>
%second = tensor.extract %result[%c1] : tensor<2xf32>
return %second : f32
}
transform.named_sequence @__transform_main(
%root: !transform.any_op {transform.readonly}) {
%target = transform.structured.match ops{["linalg.generic"]} in %root
: (!transform.any_op) -> !transform.any_op
transform.structured.vectorize %target vectorize_nd_extract
: !transform.any_op
transform.yield
}
}
Commands
The commands below use the existing LLVM build in ~/llvm-project. Run them in Bash from the directory containing repro.mlir:
lowering=(
--test-transform-dialect-erase-schedule
--one-shot-bufferize=bufferize-function-boundaries
--convert-linalg-to-loops
--convert-vector-to-scf
--expand-strided-metadata
--lower-affine
--convert-scf-to-cf
--convert-vector-to-llvm
--finalize-memref-to-llvm
--convert-arith-to-llvm
--convert-func-to-llvm
--convert-cf-to-llvm
--reconcile-unrealized-casts
)
# Baseline: erase the transform sequence without applying vectorization.
~/llvm-project/build/bin/mlir-opt repro.mlir "${lowering[@]}" -o baseline-llvm.mlir
~/llvm-project/build/bin/mlir-runner baseline-llvm.mlir -e main -entry-point-result=f32 -O0
# Vectorized: apply the transform, then use the identical lowering pipeline.
~/llvm-project/build/bin/mlir-opt repro.mlir --transform-interpreter "${lowering[@]}" -o vectorized-llvm.mlir
~/llvm-project/build/bin/mlir-runner vectorized-llvm.mlir -e main -entry-point-result=f32 -O0
Actual behavior
All four commands exit with code 0, with no diagnostics on stderr. The executions print:
| Pipeline | Output |
|---|---|
| Without vectorization | 2.000000e+01 |
| With vectorization | 9.900000e+01 |
The vectorized program returns 99 from storage[0, 2] instead of 20 from storage[1, 0].
Why the original program is valid
All six elements of the backing allocation are initialized:
Storage coordinate: [0,0] [0,1] [0,2] [1,0] [1,1] [1,2]
Storage offset: 0 1 2 3 4 5
Stored value: 10 11 99 20 21 99
^ ^
excluded columns
The source allocation has shape [2, 3] and row-major strides [3, 1]. The subview has offsets [0, 0], sizes [2, 2], and subview stride parameters [1, 1]. These parameters multiply the source strides, so the resulting view retains strides [3, 1]; the stride parameters do not make it contiguous.
The subview selects valid rows 0..1 and columns 0..1. Its largest backing element offset is 1 * 3 + 1 = 4, within the six-element allocation. Its logical contents are:
[[10, 11],
[20, 21]]
The linalg.generic has exactly two iterations and reads tensor coordinates [0, 0] and [1, 0], corresponding to backing offsets 0 and 3. Both accesses are in bounds. The body does not use the initial contents of %empty and overwrites both output elements, producing [10, 20]; main returns the second element.
The storage is initialized before bufferization.to_tensor, remains unchanged afterward, and has a single to_tensor conversion marked restrict.
Incorrect access introduced by vectorization
For the extraction tensor[i, 0], vectorization computes a linear index using the tensor's dimension size:
index = i * 2 + 0
index vector = [0, 2]
The generated gather still uses the original tensor<2x2xf32> as its base, with base coordinates [0, 0] and an all-true mask. Its relevant operation is shown below with SSA names changed for readability; %indices is the computed vector [0, 2]:
%gathered = vector.gather %tensor[%c0, %c0] [%indices], %mask, %pass_thru
: tensor<2x2xf32>, vector<2xindex>, vector<2xi1>, vector<2xf32>
into vector<2xf32>
Under the documented vector.gather semantics, each lane's index is added only to the innermost base coordinate. An active lane with an out-of-bounds coordinate has undefined behavior. The second lane therefore accesses [0, 2], outside the last dimension of size 2, instead of [1, 0]. This invalid access is introduced by the transform.
Bufferization preserves the subview and its layout [3, 1]. The gather after bufferization still has a multidimensional base:
%gathered = vector.gather %source[%c0, %c0] [%indices], %mask, %pass_thru
: memref<2x2xf32, strided<[3, 1]>>, vector<2xindex>, vector<2xi1>,
vector<2xf32> into vector<2xf32>
The final LLVM dialect IR contains an llvm.getelementptr using the vector offsets [0, 2], followed by llvm.intr.masked.gather. Thus the observed accesses differ as follows:
| Lane | Original tensor coordinate | Correct backing offset | Generated gather coordinate | Emitted backing offset | Correct / actual value |
|---|---|---|---|---|---|
| 0 | [0, 0] |
0 | [0, 0] |
0 | 10 / 10 |
| 1 | [1, 0] |
3 | [0, 2] |
2 | 20 / 99 |
The erroneous gather reads offset 2, which is inside the fully initialized backing allocation but outside the logical subview. The excluded third column makes the incorrect address observable as a deterministic result mismatch in this execution.
Expected behavior
Both pipelines should return 2.000000e+01. Vectorization must preserve the source tensor's logical elements and their relationship to the backing memref layout.
Root cause
calculateGatherOffset linearizes all extraction coordinates using tensor dimension sizes. In this example it computes row * 2 + column.
The gather branch of vectorizeTensorExtract then passes extractOp.getTensor() directly to vector::GatherOp::create, with one zero base coordinate per original dimension. It does not reshape the base to match the linearized index.
The computed index describes a position in a logically flattened tensor, while vector.gather applies it to the innermost dimension of the unchanged multidimensional base. For this subview, the logical flat index 2 corresponds to tensor coordinate [1, 0] and backing offset 3; treating it as an innermost coordinate instead produces [0, 2] and backing offset 2.
Candidate fix
Use an explicitly flattened logical tensor as the gather base, or retain the original multidimensional accesses. For a strided backing memref, flattening must preserve logical element order; directly reinterpreting the backing allocation as a contiguous buffer would still expose the excluded columns. Vectorization can decline unsupported cases when it cannot construct a valid access representation.
Regression coverage should include a memref.subview with a padded source layout such as [3, 1] and verify the executed result, in addition to checking the generated base shape, indices, and active masks.
No compiler fix was implemented or tested with a rebuilt compiler.
Environment
- Tools:
~/llvm-project/build/bin/mlir-optand~/llvm-project/build/bin/mlir-runnerfrom the same standalone LLVM/MLIR build. - Tool version:
LLVM version 24.0.0git, optimized build with assertions. - Build revision recorded in the generated
llvm/Support/VCSRevision.h:7c599160d26cd7d690d7c166f1b390086a71452b. - CMake configuration:
RelWithDebInfo,LLVM_ENABLE_ASSERTIONS=ON,LLVM_ENABLE_PROJECTS=mlir. - The reproducer was compiled and executed using the existing tools. No compiler source modification or compiler rebuild was performed.
@llvm/issue-subscribers-mlir
Author: Cerulime
Applying transform.structured.vectorize with vectorize_nd_extract changes the result of the valid program below from 20 to 99.
The program allocates and initializes a row-major memref<2x3xf32>, then uses memref.subview to select its first two columns. The resulting 2x2 view has strides [3, 1]. A linalg.generic reads the first column of the corresponding tensor and should produce [10, 20]. After vectorization, the second lane instead reads the excluded third column of the first row, which contains 99.
This reproduces with standalone mlir-opt and mlir-runner, using only standard MLIR dialects. Both compilation commands and both executions succeed; applying the vectorization transform is the only difference between the two pipelines.
Reproducer
Save as repro.mlir:
module attributes {transform.with_named_sequence} {
func.func @<!-- -->main() -> f32 {
%c0 = arith.constant 0 : index
%c1 = arith.constant 1 : index
%c2 = arith.constant 2 : index
%c3 = arith.constant 3 : index
%f10 = arith.constant 10.0 : f32
%f11 = arith.constant 11.0 : f32
%f99 = arith.constant 99.0 : f32
%f20 = arith.constant 20.0 : f32
%f21 = arith.constant 21.0 : f32
// [10, 11, 99]
// [20, 21, 99]
%storage = memref.alloc() : memref<2x3xf32>
memref.store %f10, %storage[%c0, %c0] : memref<2x3xf32>
memref.store %f11, %storage[%c0, %c1] : memref<2x3xf32>
memref.store %f99, %storage[%c0, %c2] : memref<2x3xf32>
memref.store %f20, %storage[%c1, %c0] : memref<2x3xf32>
memref.store %f21, %storage[%c1, %c1] : memref<2x3xf32>
memref.store %f99, %storage[%c1, %c2] : memref<2x3xf32>
%source = memref.subview %storage[0, 0] [2, 2] [1, 1]
: memref<2x3xf32> to memref<2x2xf32, strided<[3, 1]>>
%tensor = bufferization.to_tensor %source restrict
: memref<2x2xf32, strided<[3, 1]>> to tensor<2x2xf32>
%empty = tensor.empty() : tensor<2xf32>
%result = linalg.generic {
indexing_maps = [affine_map<(i) -> (i)>],
iterator_types = ["parallel"]
} outs(%empty : tensor<2xf32>) {
^bb0(%unused: f32):
%i = linalg.index 0 : index
%value = tensor.extract %tensor[%i, %c0] : tensor<2x2xf32>
linalg.yield %value : f32
} -> tensor<2xf32>
%second = tensor.extract %result[%c1] : tensor<2xf32>
return %second : f32
}
transform.named_sequence @<!-- -->__transform_main(
%root: !transform.any_op {transform.readonly}) {
%target = transform.structured.match ops{["linalg.generic"]} in %root
: (!transform.any_op) -> !transform.any_op
transform.structured.vectorize %target vectorize_nd_extract
: !transform.any_op
transform.yield
}
}
Commands
The commands below use the existing LLVM build in ~/llvm-project. Run them in Bash from the directory containing repro.mlir:
lowering=(
--test-transform-dialect-erase-schedule
--one-shot-bufferize=bufferize-function-boundaries
--convert-linalg-to-loops
--convert-vector-to-scf
--expand-strided-metadata
--lower-affine
--convert-scf-to-cf
--convert-vector-to-llvm
--finalize-memref-to-llvm
--convert-arith-to-llvm
--convert-func-to-llvm
--convert-cf-to-llvm
--reconcile-unrealized-casts
)
# Baseline: erase the transform sequence without applying vectorization.
~/llvm-project/build/bin/mlir-opt repro.mlir "${lowering[@]}" -o baseline-llvm.mlir
~/llvm-project/build/bin/mlir-runner baseline-llvm.mlir -e main -entry-point-result=f32 -O0
# Vectorized: apply the transform, then use the identical lowering pipeline.
~/llvm-project/build/bin/mlir-opt repro.mlir --transform-interpreter "${lowering[@]}" -o vectorized-llvm.mlir
~/llvm-project/build/bin/mlir-runner vectorized-llvm.mlir -e main -entry-point-result=f32 -O0
Actual behavior
All four commands exit with code 0, with no diagnostics on stderr. The executions print:
| Pipeline | Output |
|---|---|
| Without vectorization | 2.000000e+01 |
| With vectorization | 9.900000e+01 |
The vectorized program returns 99 from storage[0, 2] instead of 20 from storage[1, 0].
Why the original program is valid
All six elements of the backing allocation are initialized:
Storage coordinate: [0,0] [0,1] [0,2] [1,0] [1,1] [1,2]
Storage offset: 0 1 2 3 4 5
Stored value: 10 11 99 20 21 99
^ ^
excluded columns
The source allocation has shape [2, 3] and row-major strides [3, 1]. The subview has offsets [0, 0], sizes [2, 2], and subview stride parameters [1, 1]. These parameters multiply the source strides, so the resulting view retains strides [3, 1]; the stride parameters do not make it contiguous.
The subview selects valid rows 0..1 and columns 0..1. Its largest backing element offset is 1 * 3 + 1 = 4, within the six-element allocation. Its logical contents are:
[[10, 11],
[20, 21]]
The linalg.generic has exactly two iterations and reads tensor coordinates [0, 0] and [1, 0], corresponding to backing offsets 0 and 3. Both accesses are in bounds. The body does not use the initial contents of %empty and overwrites both output elements, producing [10, 20]; main returns the second element.
The storage is initialized before bufferization.to_tensor, remains unchanged afterward, and has a single to_tensor conversion marked restrict.
Incorrect access introduced by vectorization
For the extraction tensor[i, 0], vectorization computes a linear index using the tensor's dimension size:
index = i * 2 + 0
index vector = [0, 2]
The generated gather still uses the original tensor<2x2xf32> as its base, with base coordinates [0, 0] and an all-true mask. Its relevant operation is shown below with SSA names changed for readability; %indices is the computed vector [0, 2]:
%gathered = vector.gather %tensor[%c0, %c0] [%indices], %mask, %pass_thru
: tensor<2x2xf32>, vector<2xindex>, vector<2xi1>, vector<2xf32>
into vector<2xf32>
Under the documented vector.gather semantics, each lane's index is added only to the innermost base coordinate. An active lane with an out-of-bounds coordinate has undefined behavior. The second lane therefore accesses [0, 2], outside the last dimension of size 2, instead of [1, 0]. This invalid access is introduced by the transform.
Bufferization preserves the subview and its layout [3, 1]. The gather after bufferization still has a multidimensional base:
%gathered = vector.gather %source[%c0, %c0] [%indices], %mask, %pass_thru
: memref<2x2xf32, strided<[3, 1]>>, vector<2xindex>, vector<2xi1>,
vector<2xf32> into vector<2xf32>
The final LLVM dialect IR contains an llvm.getelementptr using the vector offsets [0, 2], followed by llvm.intr.masked.gather. Thus the observed accesses differ as follows:
| Lane | Original tensor coordinate | Correct backing offset | Generated gather coordinate | Emitted backing offset | Correct / actual value |
|---|---|---|---|---|---|
| 0 | [0, 0] |
0 | [0, 0] |
0 | 10 / 10 |
| 1 | [1, 0] |
3 | [0, 2] |
2 | 20 / 99 |
The erroneous gather reads offset 2, which is inside the fully initialized backing allocation but outside the logical subview. The excluded third column makes the incorrect address observable as a deterministic result mismatch in this execution.
Expected behavior
Both pipelines should return 2.000000e+01. Vectorization must preserve the source tensor's logical elements and their relationship to the backing memref layout.
Root cause
calculateGatherOffset linearizes all extraction coordinates using tensor dimension sizes. In this example it computes row * 2 + column.
The gather branch of vectorizeTensorExtract then passes extractOp.getTensor() directly to vector::GatherOp::create, with one zero base coordinate per original dimension. It does not reshape the base to match the linearized index.
The computed index describes a position in a logically flattened tensor, while vector.gather applies it to the innermost dimension of the unchanged multidimensional base. For this subview, the logical flat index 2 corresponds to tensor coordinate [1, 0] and backing offset 3; treating it as an innermost coordinate instead produces [0, 2] and backing offset 2.
Candidate fix
Use an explicitly flattened logical tensor as the gather base, or retain the original multidimensional accesses. For a strided backing memref, flattening must preserve logical element order; directly reinterpreting the backing allocation as a contiguous buffer would still expose the excluded columns. Vectorization can decline unsupported cases when it cannot construct a valid access representation.
Regression coverage should include a memref.subview with a padded source layout such as [3, 1] and verify the executed result, in addition to checking the generated base shape, indices, and active masks.
No compiler fix was implemented or tested with a rebuilt compiler.
Environment
- Tools:
~/llvm-project/build/bin/mlir-optand~/llvm-project/build/bin/mlir-runnerfrom the same standalone LLVM/MLIR build. - Tool version:
LLVM version 24.0.0git, optimized build with assertions. - Build revision recorded in the generated
llvm/Support/VCSRevision.h:7c599160d26cd7d690d7c166f1b390086a71452b. - CMake configuration:
RelWithDebInfo,LLVM_ENABLE_ASSERTIONS=ON,LLVM_ENABLE_PROJECTS=mlir. - The reproducer was compiled and executed using the existing tools. No compiler source modification or compiler rebuild was performed.
I've been looking at this. I was initially thinking of tensor.collapse_shape, but for non-contiguous layouts that can copy the whole source tensor. So I went looking for alternatives, which at this time can be summed up as below:
- Use
vector.transfer_readfor regular accesses such as this column, possibly through a rank reduced slice. That avoids the copy, but doesn't cover arbitrary index vectors and may still lower to scalar loads. - Emit conditional
tensor.extractfor the active lanes of ND gathers to handle irregular accesses without a source copy, with the downside of scalarizing the loads.
I believe they could also be combined, e.g. by having transfers on recognized regular accesses and falling back to conditional scalar loads for irregular ones. So far I've checked the two approaches above as IR prototypes only.
Would love some feedback, I'll follow up anyway after looking into this a bit more.
Follow up: I looked into some related works: namely #187215 and #194395.
I think this miscompile might be addressed independently of the broader gather/scatter semantics discussion there and in the related RFC, but I'm considering rejecting the ND extract cases that cannot be represented correctly with the current gather as another option. Regular accesses like this column could then be handled with vector.transfer_read, either in the same patch or separately.
Hi @splicer3, sorry for the delay, but the backlog on the Vector dialect has been really heavy these past few weeks.
I just wanted to let you know that, ASAP, I'll look into the issue and your comments to start a discussion aimed at resolving it.
Sorry, and thanks for your interest! 🙏
Hi @splicer3, thanks for digging into this, and sorry again for the wait.
I agree this can be fixed independently of #187215 and the RFC around #194395. The vector.gather the vectorizer emits is already wrong at the tensor level. On tensor<2x2xf32> the lane index 2 is out of bounds, and that's UB before bufferization even runs. The strided memref only makes it observable. It's a vectorizer bug rather than a vector.gather semantics issue.
I think that (i) we shouldn't bail out here, (ii) collapse the source with tensor.collapse_shape and gather from the result, and (iii) keep the vector.transfer_read path for regular accesses as follow-up.
Does it makes sense?
Thanks @FedericoBruzzone, no worries!
Makes sense to me too, I’ll put together a patch that collapses the source before the gather. I think we can leave the vector.transfer_read path for regular accesses to a follow-up after that one fix lands.