Skip to content

AsyncResult hangs in unexpected cases in fit_generator #34456

Closed

Description

@zaccharieramzi

System information

  • Have I written custom code: yes
  • OS Platform and Distribution: Linux Ubuntu 16.04
  • TensorFlow installed from: pip
  • TensorFlow version: 2.0.0b1
  • Python version: 3.6.8
  • CUDA/cuDNN version: V10.0.130
  • GPU model and memory: Quadro P5000 (16GB)

Describe the current behavior
I have a very complicated model solving an image-to-image problem. I also use a custom callback which at some point generates some noise using numpy.
When I use fit_generator on this model, it manages to do the first epoch, then on the second, third or fourth it hangs at the beginning of the epoch. I managed to see where the problem was happening, and it happens here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/utils/data_utils.py#L875
Basically, if I put a timeout on the second get it times out after a few successful epochs (sometimes just one). There is no error thrown out so I don't know why it hangs. Furthermore, if I debug at that point in code, I can just execute the function synchronously and everything will work just fine.

Describe the expected behavior
I would like fit_generator to complete even when I use my custom callback.

Code to reproduce the issue
I didn't manage to get a minimal example using fit_generator (basically it relies too much on me using my model which is complex). However, I have a minimal example which reproduces the bug when I mimic the model_iteration function.
You need to install the following to make it work: pip install tensorflow-gpu==2.0.0b1 numpy tqdm

# imports
import time

import numpy as np
import tensorflow as tf
from tensorflow.python.keras import callbacks as cbks
from tensorflow.keras.callbacks import Callback
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.engine import training_utils
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.utils import data_utils
from tensorflow.python.keras.utils import generic_utils
from tqdm import tqdm_notebook

# helper function (taken from https://github.com/tensorflow/tensorflow/blob/r2.0/tensorflow/python/keras/engine/training_generator.py#L500)
def _make_enqueued_generator(generator,
                             workers=1,
                              use_multiprocessing=False,
                             max_queue_size=10,
                             shuffle=False):    
    enqueuer = data_utils.OrderedEnqueuer(
        generator, use_multiprocessing=use_multiprocessing, shuffle=shuffle)
    enqueuer.start(workers=workers, max_queue_size=max_queue_size)
    output_generator = enqueuer.get()
    return output_generator, enqueuer

# My silly callback
class Noise(Callback):
     def on_batch_end(self, batch, logs={}):
        image_shape = [1, 2**7, 2**7, 1]
        noise = np.random.normal(scale=1.0, size=image_shape)

# My data
batch_size = 8
n_samples_train = 720
x = np.random.rand(n_samples_train, 256, 256, 1)
im_gen_train = ImageDataGenerator().flow(x, batch_size=batch_size)


# My training set up (to mimic https://github.com/tensorflow/tensorflow/blob/r2.0/tensorflow/python/keras/engine/training_generator.py#L41)
data = im_gen_train
steps_per_epoch = int(n_samples_train / batch_size)
epochs = 20
max_queue_size=35
workers=35
use_multiprocessing=True
shuffle=False
initial_epoch=0
mode=1
steps_name='steps'
noise_cb = Noise()
noise_cb.on_train_batch_end = noise_cb.on_batch_end
callbacks=[noise_cb]

generator, enqueuer = _make_enqueued_generator(
    im_gen_train,
    workers=workers,
    use_multiprocessing=use_multiprocessing,
    max_queue_size=max_queue_size,
    shuffle=shuffle)

callbacks = cbks.configure_callbacks(
    callbacks,
    Model(),
    do_validation=False,
    epochs=epochs,
    steps_per_epoch=steps_per_epoch,
    batch_size=batch_size,
    samples=n_samples_train,
    verbose=0,  # Handle ProgBar as part of Callbacks once hooks are ready.
    mode=mode,
)
callbacks._call_begin_hook(mode)

for epoch in tqdm_notebook(range(initial_epoch, epochs)):
    callbacks.on_epoch_begin(epoch, {})

    for step in tqdm_notebook(range(steps_per_epoch), leave=False):
        callbacks._call_batch_hook('train', 'begin', step, {})
        batch_data = next(generator)
        
        # I don't actually train a model, so I just sleep for this time, this would be the backprop
        time.sleep(0.1)
        callbacks._call_batch_hook('train', 'end', step, {})

If you leave it as such, it will hang after about 1, 2, 3, or 4 iterations.
You can comment out the noise = np.random.normal(scale=1.0, size=image_shape) line and see that it doesn't hang.

You can also modify tensorflow's source code and timeout here in the second get so you can debug.

Note also that if the sleeping time is not high enough, hanging doesn't appear.

I am still working on a minimal example involving fit_generator directly, but to me this example is enough to understand what's happening.

Activity

  1. zaccharieramzi commented on Nov 20, 2019

    @zaccharieramzi
    ContributorAuthor

    I finally managed to create an example involving fit_generator:

    # imports
    import time
    
    from keras_tqdm import TQDMNotebookCallback
    import numpy as np
    import tensorflow as tf
    from tensorflow.keras.callbacks import Callback
    from tensorflow.keras.layers import Input, Conv2D, Lambda, concatenate
    from tensorflow.python.keras.models import Model
    from tensorflow.keras.preprocessing.image import ImageDataGenerator
    from tensorflow.keras.utils import  Sequence
    
    
    # My silly callback
    class Noise(Callback):
         def on_batch_end(self, batch, logs={}):
            image_shape = [1, 2**7, 2**7, 1]
            noise = np.random.normal(scale=1.0, size=image_shape)
            
    # my metrics
    def keras_psnr(y_true, y_pred):
        max_pixel = tf.math.reduce_max(y_true)
        min_pixel = tf.math.reduce_min(y_true)
        return tf.image.psnr(y_true, y_pred, max_pixel - min_pixel)
    
    def keras_ssim(y_true, y_pred):
        max_pixel = tf.math.reduce_max(y_true)
        min_pixel = tf.math.reduce_min(y_true)
        return tf.image.ssim(y_true, y_pred, max_pixel - min_pixel)
    
    # My data
    class MergedGenerators(Sequence):
        def __init__(self, *generators):
            self.generators = generators
            # TODO add a check to verify that all generators have the same length
    
        def __len__(self):
            return len(self.generators[0])
    
        def __getitem__(self, index):
            return tuple([generator[index] for generator in self.generators])
    
    batch_size = 8
    n_samples_train = 720
    size = 256
    x = np.random.rand(n_samples_train, size, size, 1)
    im_gen_train_1 = ImageDataGenerator().flow(x, batch_size=batch_size, seed=0)
    im_gen_train_2 = ImageDataGenerator().flow(x, batch_size=batch_size, seed=0)
    im_gen_train = MergedGenerators(im_gen_train_1, im_gen_train_2)
    
    # my fake model
    im = Input((None, None, 1))
    conv = Conv2D(256, 3, padding='same')(im)
    conv = Conv2D(256, 3, padding='same')(conv)
    conv = Conv2D(1, 3, padding='same')(conv)
    ident = Lambda(lambda x: x)(conv)
    model = Model(im, ident)
    model.compile(loss='mse', optimizer='adam', metrics=[keras_psnr, keras_ssim])
    print(model.summary(line_length=150))
    
    # My training set up
    noise_cb = Noise()
    noise_cb.on_train_batch_end = noise_cb.on_batch_end
    tqdm_cb = TQDMNotebookCallback(metric_format="{name}: {value:e}")
    tqdm_cb.on_train_batch_begin = tqdm_cb.on_batch_begin
    tqdm_cb.on_train_batch_end = tqdm_cb.on_batch_end
    model.fit_generator(
        im_gen_train,
        steps_per_epoch=int(n_samples_train / batch_size), 
        epochs=20,
        max_queue_size=35,
        workers=35,
        use_multiprocessing=True,
        shuffle=False,
        callbacks=[noise_cb, tqdm_cb],
        verbose=0,
    )

    It's not bare yet, but at least it reproduces the error, and you just need to install keras-tqdm to get it working (= hanging).

    Note that I needed the lambda layer and the metrics to get it to hang.

    EDIT

    I also posted all of this issue on SO.

  2. self-assigned this
    on Nov 22, 2019
  3. added
    TF 2.0
    comp:keras
    on Nov 22, 2019
  4. ravikyram commented on Nov 22, 2019

    @ravikyram
    Contributor

    I have tried on colab with TF version 2.0 beta,2.0,2.1.0-dev20191121 and was able to reproduce the issue.Please, find the gist here.Thanks!

  5. zaccharieramzi commented on Nov 27, 2019

    @zaccharieramzi
    ContributorAuthor

    Thanks to discussions with @tomMoral, we now think that this is actually caused by numpy/numpy#9248. At least, the lock is coming from numpy's random module.

  6. added
    stat:awaiting tensorflower
    on Dec 17, 2019
  7. zaccharieramzi commented on Jan 29, 2020

    @zaccharieramzi
    ContributorAuthor

    I think the issue is resolved in version 2.1.

    Another fix would be to use the new random number generation API of numpy as advised here. That changes the line noise = np.random.normal(scale=1.0, size=image_shape) to noise = np.random.default_rng().normal(scale=1.0, size=image_shape). This fix works even in version 2.0.

  8. tensorflow-bot commented on Jan 29, 2020

    @tensorflow-bot

    Are you satisfied with the resolution of your issue?
    Yes
    No

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

Metadata

Metadata

Assignees

Labels

TF 2.0comp:kerasstat:awaiting tensorflowertype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions