Repository navigation
Labels
Description
Describe the bug
VerifyLoweringToTensorsPass diagnoses a linalg.init_tensor that should not be there
To Reproduce
iree-compile --iree-hal-target-backends=dylib-llvm-aot core-input.mlir
#map0 = affine_map<(d0, d1, d2) -> (d0, d1, d2)>
#map1 = affine_map<(d0, d1, d2) -> (0, d1, 0)>
module attributes {torch.debug_module_name = "NativeBatchNorm1DModule"} {
func @forward(%arg0: tensor<?x?x?xf32>, %arg1: tensor<?xf32>, %arg2: tensor<?xf32>, %arg3: tensor<?xf32>, %arg4: tensor<?xf32>) -> (tensor<?x?x?xf32>, tensor<0xf32>, tensor<0xf32>) {
%c1 = arith.constant 1 : index
%c2 = arith.constant 2 : index
%c0 = arith.constant 0 : index
%c0_i64 = arith.constant 0 : i64
%c3_i64 = arith.constant 3 : i64
%c1_i64 = arith.constant 1 : i64
%cst = arith.constant 1.000000e-05 : f64
%0 = arith.addi %c1_i64, %c3_i64 : i64
%1 = arith.cmpi sge, %c1_i64, %c0_i64 : i64
%2 = arith.select %1, %c1_i64, %0 : i64
%3 = arith.cmpi sge, %2, %c0_i64 : i64
cf.assert %3, "dim must be greater or equal to zero"
%4 = arith.cmpi slt, %2, %c3_i64 : i64
cf.assert %4, "dim must be smaller than inputRank"
%5 = tensor.expand_shape %arg3 [[0, 1, 2]] : tensor<?xf32> into tensor<1x?x1xf32>
%6 = tensor.expand_shape %arg4 [[0, 1, 2]] : tensor<?xf32> into tensor<1x?x1xf32>
%7 = tensor.dim %arg0, %c0 : tensor<?x?x?xf32>
%8 = tensor.dim %arg0, %c1 : tensor<?x?x?xf32>
%9 = tensor.dim %arg0, %c2 : tensor<?x?x?xf32>
%10 = tensor.dim %arg3, %c0 : tensor<?xf32>
%11 = arith.cmpi eq, %8, %10 : index
cf.assert %11, "mismatched size for broadcast"
%12 = linalg.init_tensor [%7, %8, %9] : tensor<?x?x?xf32>
%13 = linalg.generic {indexing_maps = [#map0, #map1, #map0], iterator_types = ["parallel", "parallel", "parallel"]} ins(%arg0, %5 : tensor<?x?x?xf32>, tensor<1x?x1xf32>) outs(%12 : tensor<?x?x?xf32>) {
^bb0(%arg5: f32, %arg6: f32, %arg7: f32):
%29 = arith.sitofp %c1_i64 : i64 to f32
%30 = arith.mulf %arg6, %29 : f32
%31 = arith.subf %arg5, %30 : f32
linalg.yield %31 : f32
} -> tensor<?x?x?xf32>
%14 = tensor.dim %arg4, %c0 : tensor<?xf32>
%15 = linalg.init_tensor [1, %14, 1] : tensor<1x?x1xf32>
%16 = linalg.generic {indexing_maps = [#map1, #map0], iterator_types = ["parallel", "parallel", "parallel"]} ins(%6 : tensor<1x?x1xf32>) outs(%15 : tensor<1x?x1xf32>) {
^bb0(%arg5: f32, %arg6: f32):
%29 = arith.truncf %cst : f64 to f32
%30 = arith.sitofp %c1_i64 : i64 to f32
%31 = arith.mulf %29, %30 : f32
%32 = arith.addf %arg5, %31 : f32
linalg.yield %32 : f32
} -> tensor<1x?x1xf32>
%17 = linalg.generic {indexing_maps = [#map1, #map0], iterator_types = ["parallel", "parallel", "parallel"]} ins(%16 : tensor<1x?x1xf32>) outs(%15 : tensor<1x?x1xf32>) {
^bb0(%arg5: f32, %arg6: f32):
%29 = math.rsqrt %arg5 : f32
linalg.yield %29 : f32
} -> tensor<1x?x1xf32>
%18 = arith.cmpi eq, %8, %14 : index
cf.assert %18, "mismatched size for broadcast"
%19 = linalg.generic {indexing_maps = [#map0, #map1, #map0], iterator_types = ["parallel", "parallel", "parallel"]} ins(%13, %17 : tensor<?x?x?xf32>, tensor<1x?x1xf32>) outs(%12 : tensor<?x?x?xf32>) {
^bb0(%arg5: f32, %arg6: f32, %arg7: f32):
%29 = arith.mulf %arg5, %arg6 : f32
linalg.yield %29 : f32
} -> tensor<?x?x?xf32>
%20 = tensor.expand_shape %arg1 [[0, 1, 2]] : tensor<?xf32> into tensor<1x?x1xf32>
%21 = tensor.dim %arg1, %c0 : tensor<?xf32>
%22 = arith.cmpi eq, %8, %21 : index
cf.assert %22, "mismatched size for broadcast"
%23 = linalg.generic {indexing_maps = [#map0, #map1, #map0], iterator_types = ["parallel", "parallel", "parallel"]} ins(%19, %20 : tensor<?x?x?xf32>, tensor<1x?x1xf32>) outs(%12 : tensor<?x?x?xf32>) {
^bb0(%arg5: f32, %arg6: f32, %arg7: f32):
%29 = arith.mulf %arg5, %arg6 : f32
linalg.yield %29 : f32
} -> tensor<?x?x?xf32>
%24 = tensor.expand_shape %arg2 [[0, 1, 2]] : tensor<?xf32> into tensor<1x?x1xf32>
%25 = tensor.dim %arg2, %c0 : tensor<?xf32>
%26 = arith.cmpi eq, %8, %25 : index
cf.assert %26, "mismatched size for broadcast"
%27 = linalg.generic {indexing_maps = [#map0, #map1, #map0], iterator_types = ["parallel", "parallel", "parallel"]} ins(%23, %24 : tensor<?x?x?xf32>, tensor<1x?x1xf32>) outs(%12 : tensor<?x?x?xf32>) {
^bb0(%arg5: f32, %arg6: f32, %arg7: f32):
%29 = arith.sitofp %c1_i64 : i64 to f32
%30 = arith.mulf %arg6, %29 : f32
%31 = arith.addf %arg5, %30 : f32
linalg.yield %31 : f32
} -> tensor<?x?x?xf32>
%28 = linalg.init_tensor [0] : tensor<0xf32>
return %27, %28, %28 : tensor<?x?x?xf32>, tensor<0xf32>, tensor<0xf32>
}
}
Activity
benvanik commentedon Mar 31, 2022
@MaheshRavishankar would know the real intent, but AFAIK this isn't an intended way of using init tensors. If this were an arith.constant instead it would be converted to a
flow.tensor.emptyand be handled ok I believe.MaheshRavishankar commentedon Mar 31, 2022
its again returning a
tensor<0xf32>that is strange, also, returning aninit_tensorthis way is undefined behavior...silvasean commentedon Apr 1, 2022
There is a batch norm op, and in inference mode it returns 0-size tensors:
We decompose the last two return value into "torch.empty" which creates an uninitialized tensor, which then gets lowered to init_tensor. I know we've discussed in the past that init_tensor is one of multiple things -- how would you suggest that we lower the
torch.emptyop to linalg-on-tensors if not through init_tensor? https://pytorch.org/docs/stable/generated/torch.empty.htmlIn this specific case, since we know they are 0-size, it wouldn't harm to turn them into "zeros" instead of "empty", but generally patterns like
torch.empty(sizes).uniform_(low, high)(orfill_-- the trailing _ means "in place") are pretty common, and it seems like an arbitrary and (difficult to describe for users) restriction to say that "torch.empty cannot be returned from a function" (which might only happen through multiple levels of inlining and simplification).benvanik commentedon Apr 1, 2022
torch.empty is fine - we can support that lowering through flow.tensor.empty - I think the issue here is the lowering of torch.empty to linalg.init_tensor
silvasean commentedon Apr 1, 2022
flow.tensor.empty seems to be "metadata-only", but torch.empty is not metadata-only -- it has an allocated buffer, just with uninitialized data. So if a user returns
torch.empty(10)from a function, they should be able to write 10 elements into what is returned.We discussed at length in https://discourse.llvm.org/t/rfc-promoting-linalg-init-tensor-to-the-bufferize-dialect/5000 and weren't able to come up with an op on builtin.tensor (i.e. value semantics) that had the"intuitive" properties we wanted (besides init_tensor's sketchiness). Can IREE turn these init_tensor's into empty allocs at an appropriate point during compilation? Based on that thread, I don't think we are going to be able to define a well-defined op on tensors that meaningfully improves on init_tensor.
benvanik commentedon Apr 1, 2022
oh, so empty means zeroed? I thought we were talking about 0-length tensors - which by virtue of having 0 elements have no associated buffer. Having a zeroed tensor is flow.tensor.splat 0.
silvasean commentedon Apr 1, 2022
torch.empty returns a buffer with uninitialized data, it is not guaranteed to be zeroed.
silvasean commentedon Apr 1, 2022
In this particular case, the empty tensor also happens to be of size 0, but that's an independent thing specific to this particular situation. If a user writes
torch.empty(10)they will get 10 allocated but uninitialized elements.benvanik commentedon Apr 1, 2022
That's an insanely dangerous user-level API, and I can't imagine why someone would want it when operating at that level ;)
We can do that with a
stream.resource.alloc uninitialized, but that's just a hint and the runtime may decide to zero it. I'm not sure we care too much about optimizing returns of uninitialized tensors - that feels like an overoptimization. If you want it to be faster to return garbage data then don't return it.silvasean commentedon Apr 1, 2022
I agree, it's a pretty low-level API, but it is a common pattern in PyTorch to do things like
torch.empty(sizes).uniform_(low, high)(in fact, there is no variant of "uniform" that returns uniform random values -- it has to be done in-place via this pattern)I don't expect it to be use-case load-bearing that we match the performance characteristics of "allocated but uninitialized" in all cases[1]. However, it's quite difficult to identify ahead of time which of these "empty" are going to be written to as outs of a subsequent linalg operation, or returned (e.g. IREE might later inline a function and recognize that this is an operand to an outs, or fold a tensor.empty hidden by control flow to the value directly). I think the request here is that IREE just does something with it, and materializes an appropriate buffer (much like we have to materialize tensor.dim ops around ops that aren't shape carrying).
[1] I don't think PyTorch can realistically guarantee 'no work done initializing the buffer' either -- e.g. if you ask for a large
torch.empty, and have to request more memory from the OS, then the OS will probably have to zero it out anyway for security reasons before giving it to your process, negating the "uninitialized" performance benefit.benvanik commentedon Apr 1, 2022
I'm not sure I follow the pytorch details, but I'm also not sure I need to :)
By the time we see it in IR
create-empty-and-fill-contents-in-place(torch.empty(sizes).uniform_(...)) is the same ascreate-new-with-filled-contents(hypotheticaltorch.uniform(sizes, ...)) and we handle that fine. This issue is thecreate-empty-with-uninitialized-memory(torch.empty(sizes)), and I'm not sure what (reasonable) use there is to supporting that as uninitialized data that can escape the program - sounds like just a programmer using pytorch to allocate for them instead of returningsizesand allocating if desired. We will make that work of course but I'd hesitate to expose gaping security holes for such behavior :)silvasean commentedon Apr 1, 2022
Is there a point in the IREE compilation pipeline where "we've handled all the create-empty-and-fill-contents-in-place and now we know that any other init_tensor's are from create-empty-with-uninitialized-memory"? I'd be fine with converting all such remaining init_tensor's to zero-filled buffers (good point about security).
The problem is that we can't really reliably tell at the frontend level which init_tensor's will or will not end up escaping (without being unnecessarily conservative IMO). E.g.
One can imagine arbitrarily complex variants of that where the escaping torch.empty is hidden behind control flow, calls, etc. (or conversely, where arbitrarily complex control flow leads to a subsequent
x.uniform_(...)call).I also want to preserve the ability of the user to write code like this and compile it without having to inline it for correctness:
13 remaining items
silvasean commentedon Apr 5, 2022
I'm seeing if I can debug this. It looks like it might be pretty simple.
MaheshRavishankar commentedon Apr 5, 2022
Sorry about that. I did try the test you had, but maybe I changed something after that.
silvasean commentedon Apr 5, 2022
I'm not sure what the expected behavior is. The issue goes away if I replace
with
-- is
tensor<1xf32>{%c1}legal, or should it only be dynamic dims in the {...}?silvasean commentedon Apr 5, 2022
btw, @benvanik I noticed that we don't have any verifiers for this IR construct -- e.g. I can change it to
tensor<1xf32>{%c1, %c1}and nothing complains. Can we improve that?benvanik commentedon Apr 5, 2022
it should only be dynamic values in there
I have those verifiers for the stream types - they just need to be copied out to the flow types.
silvasean commentedon Apr 5, 2022
Okay, then the bug is in InitializeEmptyTensors. WIll send out a fix and add more verifiers.
MaheshRavishankar commentedon Apr 5, 2022
Ok, Thats how I had it initially, and the example above compiled. I mis-understood Ben's comment on the PR and changed it to have all shapes (instead of just dynamic).
@silvasean if you havent gotten to it already, I can take a look.
Fix for InitializeEmptyTensors
Fix for InitializeEmptyTensors (#8772)
Translate flow.tensor.empty to stream.tensor.empty.
Translate flow.tensor.empty to stream.tensor.empty.
Translate flow.tensor.empty to stream.tensor.empty.
Translate flow.tensor.empty to stream.tensor.empty. (#11131)