Skip to content

Memory leak in custom training loop + tf.function  #50765

Open

Description

Please make sure that this is an issue related to performance of TensorFlow.
As per our
GitHub Policy,
we only address code/doc bugs, performance issues, feature requests and
build/installation issues on GitHub. tag:performance_template

System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): yes
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 18 (google colab)
  • TensorFlow installed from (source or binary): pip
  • TensorFlow version (use command below): v2.5.0-0-ga4dfb8d1a71 2.5.0
  • Python version: 3.7
  • CUDA/cuDNN version: Build cuda_11.0_bu.TC445_37.28845127_0
  • GPU model and memory: Tesla T4 - 15109MiB

You can collect some of this information using our environment capture
script
You can also obtain the TensorFlow version with:

  1. TF 1.0: python -c "import tensorflow as tf; print(tf.GIT_VERSION, tf.VERSION)"
  2. TF 2.0: python -c "import tensorflow as tf; print(tf.version.GIT_VERSION, tf.version.VERSION)"

Describe the current behavior

I'm encountering a subtle memory leak, and unable to determine the source using tracemalloc. I run the code in google colab, which is meant to optimize hyperparameters for a custom ppo agent. Also, the speed at which the leak happens varies: sometimes it happens within 10-20 minutes of runtime / 5-10 iterations while on other times it may take up to an hour.

Describe the expected behavior

Memory usage should be constant over time, since there are no objects stored in memory intentionally as the training progresses.

Standalone code to reproduce the issue

Here's a colab notebook

Other info / logs

And here are the resulting memory snapshots at 15 consecutive iterations up to the crash, which do not show any particular red flags. Besides, by summing up the size column of the most recent snapshot, it totals 967249710 bytes ~= 1GB, which is weird because the available memory on colab ~= 12GB.

Here's a log after crashing:

   Timestamp                  Level    Message

Jul 14, 2021, 11:07:41 AM | WARNING | WARNING:root:kernel a3ecdd9e-1765-4f67-af0e-60c198c896ec restarted
Jul 14, 2021, 11:07:41 AM | INFO | KernelRestarter: restarting kernel (1/5), keep random ports
Jul 14, 2021, 10:22:16 AM | WARNING | 2021-07-14 08:22:16.518184: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcublasLt.so.11
Jul 14, 2021, 10:22:13 AM | WARNING | 2021-07-14 08:22:13.939377: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcublas.so.11
Jul 14, 2021, 10:21:50 AM | WARNING | 2021-07-14 08:21:50.140299: I tensorflow/stream_executor/cuda/cuda_dnn.cc:359] Loaded cuDNN version 8004
Jul 14, 2021, 10:21:47 AM | WARNING | 2021-07-14 08:21:47.841310: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudnn.so.8
Jul 14, 2021, 10:21:44 AM | WARNING | 2021-07-14 08:21:44.642335: I tensorflow/core/platform/profile_utils/cpu_utils.cc:114] CPU Frequency: 2199995000 Hz
Jul 14, 2021, 10:21:44 AM | WARNING | 2021-07-14 08:21:44.559306: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2)
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.355834: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1418] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 13837 MB memory) -> physical GPU (device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5)
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.355771: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0.
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.354979: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.354000: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.352104: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.351844: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1277] 0: N
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.351828: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1264] 0
Jul 14, 2021, 10:21:30 AM | WARNING | 2021-07-14 08:21:30.351772: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1258] Device interconnect StreamExecutor with strength 1 edge matrix:
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.206565: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.203344: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1871] Adding visible gpu devices: 0
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.202526: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.201577: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:25 AM | WARNING | coreClock: 1.59GHz coreCount: 40 deviceMemorySize: 14.75GiB deviceMemoryBandwidth: 298.08GiB/s
Jul 14, 2021, 10:21:25 AM | WARNING | pciBusID: 0000:00:04.0 name: Tesla T4 computeCapability: 7.5
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.201438: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1733] Found device 0 with properties:
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.200536: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.199581: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1871] Adding visible gpu devices: 0
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.195723: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.194598: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.194398: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudnn.so.8
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.190679: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcusparse.so.11
Jul 14, 2021, 10:21:25 AM | WARNING | 2021-07-14 08:21:25.144200: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcusolver.so.10
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.851273: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcurand.so.10
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.832903: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcufft.so.10
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.660570: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcublasLt.so.11
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.660379: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcublas.so.11
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.533359: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0
Jul 14, 2021, 10:21:24 AM | WARNING | coreClock: 1.59GHz coreCount: 40 deviceMemorySize: 14.75GiB deviceMemoryBandwidth: 298.08GiB/s
Jul 14, 2021, 10:21:24 AM | WARNING | pciBusID: 0000:00:04.0 name: Tesla T4 computeCapability: 7.5
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.533253: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1733] Found device 0 with properties:
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.532176: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
Jul 14, 2021, 10:21:24 AM | WARNING | 2021-07-14 08:21:24.461038: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcuda.so.1
Jul 14, 2021, 10:21:07 AM | WARNING | 2021-07-14 08:21:07.977292: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0
Jul 14, 2021, 10:20:27 AM | INFO | Adapting to protocol v5.1 for kernel a3ecdd9e-1765-4f67-af0e-60c198c896ec
Jul 14, 2021, 10:20:26 AM | INFO | Kernel started: a3ecdd9e-1765-4f67-af0e-60c198c896ec
Jul 14, 2021, 10:20:20 AM | INFO | Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
Jul 14, 2021, 10:20:20 AM | INFO | http://172.28.0.12:9000/
Jul 14, 2021, 10:20:20 AM | INFO | The Jupyter Notebook is running at:
Jul 14, 2021, 10:20:20 AM | INFO | Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
Jul 14, 2021, 10:20:20 AM | INFO | 0 active kernels
Jul 14, 2021, 10:20:20 AM | INFO | http://172.28.0.2:9000/
Jul 14, 2021, 10:20:20 AM | INFO | The Jupyter Notebook is running at:
Jul 14, 2021, 10:20:20 AM | INFO | Serving notebooks from local directory: /
Jul 14, 2021, 10:20:20 AM | INFO | 0 active kernels
Jul 14, 2021, 10:20:20 AM | INFO | Serving notebooks from local directory: /
Jul 14, 2021, 10:20:20 AM | INFO | google.colab serverextension initialized.
Jul 14, 2021, 10:20:20 AM | INFO | google.colab serverextension initialized.
Jul 14, 2021, 10:20:20 AM | INFO | Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
Jul 14, 2021, 10:20:20 AM | INFO | Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret

Activity

  1. ghost added
    type:performance
    on Jul 14, 2021
  2. added
    TF 2.5
    comp:tf.function
    on Jul 14, 2021
  3. tilakrayal commented on Jul 14, 2021

    @tilakrayal
    Contributor

    @jvishnuvardhan ,
    I was able to reproduce the issue in tensorflow 2.11.0-dev20220829 it is giving error.Please find the gist here.

  4. added
    stat:awaiting tensorflower
    on Jul 14, 2021
  5. added
    TF 2.9
    and removed
    TF 2.5
    on Aug 30, 2022
  6. bgLeon commented on Oct 4, 2022

    @bgLeon

    Hi, I am having this issue as well in 2.8,2.9 and 2.10. Ram usage keeps growing everytime I call a tf. function, which is quite problematic for RL. This didn't happen with tf 2.5. The issue is very simple to reproduce, just use the code below and monitor the Ram, it'll increase quite quickly.

    The ram usage if we remove the tf.function wrapper, but that solutions makes everything very slow

    import tensorflow as tf
    
    @tf.function
    def operate(img):
        return img
    
    img = tf.zeros((6,6,7))
    for i in range (100000000):
        s= operate(img)
    
  7. tnybny commented on Apr 17, 2023

    @tnybny

    this is reproducible on tf 2.11.

  8. DanielWicz commented on May 16, 2023

    @DanielWicz

    Noticed that it happens if:

    @tf.function
    def traced_function(data)
    
    ... something changes inside, that is not due to the traced function, e.g. external tf.Variable
    
    

    then the memory leak happens

  9. Avelina9X commented on Jun 22, 2023

    @Avelina9X

    Can confirm, this is reproducible in 2.11

  10. plliao commented on Jun 26, 2023

    @plliao

    The leak seems to be fixed in TF 2.12. The leaked object is IntraProcessRendezvous from Eager context.
    Here is the traced results from valgrind when running the above example.

    ==91097== 57,652,608 bytes in 277,176 blocks are still reachable in loss record 263,534 of 263,534
    ==91097==    at 0x4C2CA43: operator new[](unsigned long) (vg_replace_malloc.c:714)
    ==91097==    by 0x3EC2BEB7: tensorflow::RefCountedIntraProcessRendezvous::RefCountedIntraProcessRendezvous(tensorflow::DeviceMgr const*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/libtensorflow_framework.so.2)
    ==91097==    by 0x18C20985: tensorflow::EagerContext::LocalRendezvousTable::FindOrCreate(long, tensorflow::DeviceMgr*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x17B6A2A9: tensorflow::EagerContext::CreateRendezvous(long) const (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18C28A04: tensorflow::KernelAndDeviceFunc::PrepareForRun(tensorflow::ScopedStepContainer*, std::vector<std::variant<tensorflow::Tensor, tensorflow::TensorShape>, std::allocator<std::variant<tensorflow::Tensor, tensorflow::TensorShape> > >*, tsl::CancellationManager*, std::optional<tensorflow::EagerFunctionParams> const&, std::optional<tensorflow::ManagedStackTrace> const&, tensorflow::CoordinationServiceAgent*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18C2B0AD: tensorflow::KernelAndDeviceFunc::Run(tensorflow::ScopedStepContainer*, tensorflow::EagerKernelArgs const&, std::vector<std::variant<tensorflow::Tensor, tensorflow::TensorShape>, std::allocator<std::variant<tensorflow::Tensor, tensorflow::TensorShape> > >*, tsl::CancellationManager*, std::optional<tensorflow::EagerFunctionParams> const&, std::optional<tensorflow::ManagedStackTrace> const&, tensorflow::CoordinationServiceAgent*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18BED950: tensorflow::EagerKernelExecute(tensorflow::EagerContext*, absl::lts_20220623::InlinedVector<tensorflow::TensorHandle*, 4ul, std::allocator<tensorflow::TensorHandle*> > const&, std::optional<tensorflow::EagerFunctionParams> const&, std::unique_ptr<tensorflow::KernelAndDevice, tsl::core::RefCountDeleter> const&, tensorflow::GraphCollector*, tsl::CancellationManager*, absl::lts_20220623::Span<tensorflow::TensorHandle*>, std::optional<tensorflow::ManagedStackTrace> const&) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18BEE546: tensorflow::ExecuteNode::Run() (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x2030FDFB: tensorflow::EagerExecutor::SyncExecute(tensorflow::EagerNode*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18BE8590: tensorflow::(anonymous namespace)::EagerLocalExecute(tensorflow::EagerOperation*, tensorflow::TensorHandle**, int*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18BE92A1: tensorflow::EagerExecute(tensorflow::EagerOperation*, tensorflow::TensorHandle**, int*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    ==91097==    by 0x18BD3585: tensorflow::EagerOperation::Execute(absl::lts_20220623::Span<tensorflow::AbstractTensorHandle*>, int*) (in /home/pliao/Desktop/feed-spr-modeling/build/feed-spr-global-model/environments/development-venv/lib/python3.10/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so)
    

    Commit that fixed the leak in TF 2.12 rc0:
    3c9f4a6

    Also, I noticed another fix against the IntraProcessRendezvous was merged in TF 2.13 rc0. It seems the IntraProcessRendezvous can be leaked from different code path (different from PrepareForRun).
    Although the leak can not be observed in the above example provided by bgLeon, it is worth upgrading to TF 2.13 when it is available.
    272a147

  11. TheFantasticWarrior commented on Jul 13, 2023

    @TheFantasticWarrior

    The leak still persists in 2.12.0 with custom model overriding train_step and calling fit

    import tensorflow as tf 
    import os, psutil
    process = psutil.Process(os.getpid())
    from tensorflow.keras import Model
    x=tf.constant([0])
    class model(Model):
        def __init__(self):
            super(model, self).__init__()
            super().compile()
            
        @tf.function
        def train_step(self,x):
            return x
            
            
    m=model()
    m.fit(x)
    for i in range(10):
        m.fit(x,verbose=0)
        print(process.memory_info().rss)

    output:

    953192448
    953700352
    954253312
    954785792
    955330560
    955400192
    955412480
    955674624
    956133376
    956530688
    
  12. RHTNT commented on Oct 24, 2023

    @RHTNT

    So is there a solution to this? I am experiencing a leak currently in the same situation and badly need this to run. I use tf 2.14

  13. champagnefloppie commented on Apr 17, 2024

    @champagnefloppie

    Also having the same issue, with a TF function updating state of variable outside of function.

  14. testhowtest commented on May 29, 2024

    @testhowtest

    It probably has something in common with #35010 and #29027, right?

  15. testhowtest commented on May 29, 2024

    @testhowtest

    It probably has something in common with #395 and #68196, right?

  16. mfide commented on Oct 3, 2024

    @mfide

    I'm trying to use TF 2.17 (uses CPU only) with Python 3.12 in my linux system has 256GB RAM and 512GB swap memory.
    I create a model, fit and evaluate and keep repeating the same thing in a loop.
    It fails after 3 days because of lack of memory :)

  17. AtticusBeachy commented on Oct 18, 2024

    @AtticusBeachy

    I create a model, fit and evaluate and keep repeating the same thing in a loop. It fails after 3 days because of lack of memory :)

    It's a deeply ugly hack, but you can set up an outer Python script to relaunch your inner Python script whenever it crashes. The outer loop looks like this:

    import os
    import time
    
    exit_code = 1
    i = 0
    MAX_RUNS = 100
    
    while exit_code and i < MAX_RUNS:
        i+=1
        print(f"Step {i} of maximum {MAX_RUNS}")
        exit_code = os.system("python3 main_leaky_script.py")
        print("Exit code: ", exit_code)
        time.sleep(1)
    
    print(f"Ended on run number {i} ({i+bool(exit_code)-1} crashes)")

    Then your inner loop file (named main_leaky_script.py in the code above) would look something like this:

    try:
        model = tf.keras.models.load_model("model.keras")
    except:
        # initialize your model from scratch (will be called on the first run, 
        # when there isn't anything to load yet).
        model = create_nn_model()
    
    # Compile model
    # Do training inside a loop, stopping and saving your model every few epochs. 
    # To save, use the command:
    model.save("model.keras")
    # (Alternatively, set up checkpoints and save and load weights instead of entire models)

    However, constantly writing to swap for multiple days is a great way to wear out your SSD. Perhaps the better option would be switching to PyTorch.

  18. ohilo12 commented on Nov 4, 2024

    @ohilo12

    I'm trying to use TF 2.17 (uses CPU only) with Python 3.12 in my linux system has 256GB RAM and 512GB swap memory. I create a model, fit and evaluate and keep repeating the same thing in a loop. It fails after 3 days because of lack of memory :)

    Same problem. I was hoping it was my mistake, but it doesn't seem to be. How are you supposed to use tf at all if you run out of RAM during hyperparameter optimization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

TF 2.9comp:tf.functionstat:awaiting tensorflowertype:performance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions