Skip to content

init_tensor survives until VerifyLoweringToTensorsPass #8717

Description

@silvasean

Describe the bug

VerifyLoweringToTensorsPass diagnoses a linalg.init_tensor that should not be there

https://gist.github.com/silvasean/c5afa1a66af773f8ff590406a74907ca

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

  1. added
    bug 🐞
    help wanted
    on Mar 31, 2022
  2. benvanik commented on Mar 31, 2022

    @benvanik
    Collaborator
        %28 = linalg.init_tensor [0] : tensor<0xf32>
        return %27, %28, %28 : tensor<?x?x?xf32>, tensor<0xf32>, tensor<0xf32>
    

    @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.empty and be handled ok I believe.

  3. MaheshRavishankar commented on Mar 31, 2022

    @MaheshRavishankar
    Collaborator

    its again returning a tensor<0xf32> that is strange, also, returning an init_tensor this way is undefined behavior...

  4. silvasean commented on Apr 1, 2022

    @silvasean
    ContributorAuthor

    There is a batch norm op, and in inference mode it returns 0-size tensors:

    >>> import torch
    >>> t = torch.ops.aten.native_batch_norm(torch.rand(3, 4, 5), torch.rand(3, 4), torch.rand(3,  4), torch.rand(4), torch.rand(4), False, 0.001, 1e-6)
    >>> print(t[0].shape, t[1].shape, t[2].shape)
    torch.Size([3, 4, 5]) torch.Size([0]) torch.Size([0])
    

    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.empty op to linalg-on-tensors if not through init_tensor? https://pytorch.org/docs/stable/generated/torch.empty.html

    In 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) (or fill_ -- 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).

  5. benvanik commented on Apr 1, 2022

    @benvanik
    Collaborator

    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

  6. silvasean commented on Apr 1, 2022

    @silvasean
    ContributorAuthor

    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.

  7. benvanik commented on Apr 1, 2022

    @benvanik
    Collaborator

    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.

  8. silvasean commented on Apr 1, 2022

    @silvasean
    ContributorAuthor

    torch.empty returns a buffer with uninitialized data, it is not guaranteed to be zeroed.

  9. silvasean commented on Apr 1, 2022

    @silvasean
    ContributorAuthor

    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.

  10. benvanik commented on Apr 1, 2022

    @benvanik
    Collaborator

    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.

  11. silvasean commented on Apr 1, 2022

    @silvasean
    ContributorAuthor

    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.

  12. benvanik commented on Apr 1, 2022

    @benvanik
    Collaborator

    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 as create-new-with-filled-contents (hypothetical torch.uniform(sizes, ...)) and we handle that fine. This issue is the create-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 returning sizes and allocating if desired. We will make that work of course but I'd hesitate to expose gaping security holes for such behavior :)

  13. silvasean commented on Apr 1, 2022

    @silvasean
    ContributorAuthor

    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.

    if cond():
      x = torch.empty(10)
    else:
      x = torch.empty(20)
    return x
    

    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:

    def get_empty():
      return torch.empty(10)
    def uniform():
      return get_empty().uniform_(1.5, 3.5)
    
  14. 13 remaining items

  15. silvasean commented on Apr 5, 2022

    @silvasean
    ContributorAuthor

    I'm seeing if I can debug this. It looks like it might be pretty simple.

  16. MaheshRavishankar commented on Apr 5, 2022

    @MaheshRavishankar
    Collaborator

    Sorry about that. I did try the test you had, but maybe I changed something after that.

  17. silvasean commented on Apr 5, 2022

    @silvasean
    ContributorAuthor

    I'm not sure what the expected behavior is. The issue goes away if I replace

    flow.tensor.empty : tensor<1xf32>{%c1}
    

    with

    flow.tensor.empty : tensor<1xf32>
    

    -- is tensor<1xf32>{%c1} legal, or should it only be dynamic dims in the {...}?

  18. silvasean commented on Apr 5, 2022

    @silvasean
    ContributorAuthor

    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?

  19. benvanik commented on Apr 5, 2022

    @benvanik
    Collaborator

    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.

  20. silvasean commented on Apr 5, 2022

    @silvasean
    ContributorAuthor

    Okay, then the bug is in InitializeEmptyTensors. WIll send out a fix and add more verifiers.

  21. MaheshRavishankar commented on Apr 5, 2022

    @MaheshRavishankar
    Collaborator

    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.

  22. added a commit that references this issue on Apr 5, 2022
    fceda8f
  23. added a commit that references this issue on Apr 5, 2022
    fde35ef
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug 🐞compiler/dialects

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions