Skip to content

vulkan memory leak with pyiree #3381

Closed

Description

@hanhanW

Forking from #2948, since this is a python binding issue.

@lioujheyu reported that there is a memory leak issue on vulkan in python binding. the error is to take colab's low level invoke example. Put everything except the import in an infinite loop. Also, change the driver_name to "vulkan" and run it.

On his machine with Nvidia P100 GPU, the exception: "Check failed: m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!" always pops up in the iteration 83.

The issue cannot be reproduced in iree-translate/iree-benchmark-module. Think the issue is specific to the python binding.

===

Look into the example doc, I didn't find any import in an infinite loop. @lioujheyu could you post the code?
@ScottTodd could you help on this issue? I'm not familiar with using colab, so would be great if you can take the first round. I'm happy to learn it and debug, thanks!

Activity

  1. added
    integrations
    hal/vulkan
    on Oct 7, 2020
  2. lioujheyu commented on Oct 7, 2020

    @lioujheyu

    Sure, this is the code I modified from the colab example

    import numpy as np
    from pyiree.tf import compiler as ireec
    from pyiree import rt as ireert
    
    for i in range(10000):
        ctx = ireec.Context()
        input_module = ctx.parse_asm("""
          module @arithmetic {
            func @simple_mul(%arg0: tensor<4xf32>, %arg1: tensor<4xf32>) -> tensor<4xf32>
                  attributes { iree.module.export } {
                %0 = "mhlo.multiply"(%arg0, %arg1) {name = "mul.1"} : (tensor<4xf32>, tensor<4xf32>) -> tensor<4xf32>
                return %0 : tensor<4xf32>
            } 
          }
          """)
        blob = input_module.compile()
        m = ireert.VmModule.from_flatbuffer(blob)
    
        # Use the CPU interpreter (which has the most implementation done):
        # driver_name = "vmla"
        # Live on the edge and give the vulkan driver a try:
        driver_name = "vulkan"
        config = ireert.Config(driver_name)
        ctx = ireert.SystemContext(config=config)
        ctx.add_module(m)
    
        # Invoke the function and print the result.
        print("INVOKE simple_mul")
        arg0 = np.array([1., 2., 3., 4.], dtype=np.float32)
        arg1 = np.array([4., 5., 6., 7.], dtype=np.float32)
        f = ctx.modules.arithmetic["simple_mul"]
        results = f(arg0, arg1)
        print("Results:", results)
  3. ScottTodd commented on Oct 7, 2020

    @ScottTodd
    Member

    I remember seeing similar issues (particularly with Vulkan in Colab) a while ago, where reloading the notebook was the only way to get back to a good state. At the time I was hoping the instability would go away on its own as the Python bindings and Vulkan driver matured...

    Anyways, I'm trying to test now, but have some Windows/TF/Bazel build failures to get past first.

  4. ScottTodd commented on Oct 7, 2020

    @ScottTodd
    Member

    Cool, so after #3393 and working around #3394, I can repro this on my Windows machine (NVIDIA 2080 Ti).

    loop iteration 89

    F external/vulkan_memory_allocator/src\vk_mem_alloc.h:11175] Check failed: m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!"
    

    I remember errors happening much sooner before - like on the second compile/run, not this far delayed. Maybe that was for a larger model like mnist? Or maybe a different issue.


    @hanhanW if you want to try debugging in Colab yourself, see https://google.github.io/iree/using-iree/using-colab and https://github.com/google/iree/blob/main/colab/start_colab_kernel.py for how to get started.

    Once you've got a local kernel running (from that script), you can

    1. click one of the "Open in Colab" links at https://github.com/google/iree/tree/main/colab like https://colab.research.google.com/github/google/iree/blob/main/colab/low_level_invoke_function.ipynb
    2. "Connect to a local runtime" with the local URL/token from the kernel
    3. run each cell in order, copy/paste that repro code and run it, etc.
  5. lioujheyu commented on Oct 7, 2020

    @lioujheyu

    Not sure how people in IREE debug python code but I manually hook the additional path of the python binding into the code so I don't rely on colab. Like including the following code at the beginning

    import sys
    sys.path.append("<IREE_PATH>/bazel-out/k8-opt/bin/colab/everything_for_colab.runfiles/iree_core/bindings/python")
    sys.path.append("<IREE_PATH>/bazel-out/k8-opt/bin/colab/everything_for_colab.runfiles/iree_core/bindings/integrations/tensorflow/bindings/python")

    Then I can run/debug the above code as a native python script.

  6. ScottTodd commented on Oct 7, 2020

    @ScottTodd
    Member

    Another way to use IREE python code is from a standalone file built using Bazel with iree_py_binary or iree_py_test (see https://github.com/google/iree/blob/main/integrations/tensorflow/e2e/BUILD and https://github.com/google/iree/blob/main/integrations/tensorflow/e2e/math_test.py for some examples). That pulls in the right paths without needing to fiddle with runfiles.

  7. lioujheyu commented on Oct 7, 2020

    @lioujheyu

    Thanks for sharing @ScottTodd :) Nice to learn something.

  8. stellaraccident commented on Oct 7, 2020

    @stellaraccident
    Collaborator

    Just catching up on this thread - it seems interesting (to me anyway) that this is non-deterministic to the point that it shows up after ~90 iterations, Scott. Leaving aside more nefarious things, I wonder if there is a race with respect to freeing and then destroying the context. To my knowledge, there is nothing in the code that is enforcing any ordering there from the python reference perspective, and you know what happens in systems like this when there is no defined ordering :)

    Let's say for a second that, from the perspective of the gc, some number of these references were not collected immediately (reference loop, other things can cause this -- it is basically UB in Python). Then at some point, the gc would kick in and destroy them all. Order at that point is indeterminate: it is perfectly legal that the context gets destroyed before the arrays allocated against it.

    If this is the case, the answer is to introduce a keep_alive from the created arrays to owning context, which would ensure strict ordering. Unfortunately, my understanding at the time on how to lay out such code was somewhat less advanced than I understand now... You would want to ensure that keep alives are added:

    • Where we return python objects that may depend on the context. May be as simple as adding py::keep_alive<0, 1>() as an argument to def().
    • May also need a keep-alive from the FunctionAbi to the HalDevice but it seems that we do this with a C++ ref-count which should be sufficient.
    • HalDevice should already be capturing a reference to HalDriver so probably fine.

    I think the first bullet is where the ref-count chain is broken.

    You can probably repro this in the function_abi_test.py unit test if this is the culprit. A test that does one of the result allocations, then clears the class level driver/device, then calls gc.collect() should crash.

  9. ScottTodd commented on Oct 8, 2020

    @ScottTodd
    Member

    Per Stella's suggestion, replacing

    https://github.com/google/iree/blob/bf1f22a89923f2e6c223054385eb0fc934b77d69/bindings/python/pyiree/rt/function_abi.cc#L836-L839

    with

          .def(
              "unpack_results",
              [](FunctionAbi* self, VmVariantList& f_results) {
                return self->Unpack(absl::MakeConstSpan(self->raw_config().results),
                                    f_results);
              },
              py::keep_alive<0, 1>());

    appears to help (that repro is fine after 600 iterations on my machine)

  10. added
    bindings/python
    on Nov 22, 2020
  11. benvanik commented on Nov 22, 2020

    @benvanik
    Collaborator

    Fixed?

  12. ScottTodd commented on Nov 30, 2020

    @ScottTodd
    Member

    Fixed?

    No. The attempted fix had relevant test failures. Python bindings need more dedicated attention.

  13. added
    bug 🐞
    and removed on Nov 30, 2020
  14. added 3 commits that reference this issue on Feb 5, 2021
    0564ef8
    72a1c64
    e511e25
  15. added a commit that references this issue on Feb 9, 2021
    baa5d39
  16. GMNGeoffrey commented on Jul 28, 2022

    @GMNGeoffrey
    Member

    I'm hitting the same error in #9927 when trying to migrate to GitHub actions :-(

  17. allieculp commented on Jul 28, 2022

    @allieculp

    @ScottTodd Do you have time to look at this or should we assign to someone else? Let me know if you have an idea of priority.

  18. GMNGeoffrey commented on Jul 28, 2022

    @GMNGeoffrey
    Member

    @stellaraccident suggested opening a new issue instead. Opened #9936

  19. moved this to Done in IREEon Jul 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bindings/pythonbug 🐞hal/vulkanintegrations

Type

No type

Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions