Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CNTK out of memory error when model.fit() is called second time

Tags:

python

keras

cntk

I am using Keras and CNTK(backend)

my code is like this:

def run_han(embeddings_index, fname, opt)
    ...
    sentence_input = Input(shape=(MAX_SENT_LENGTH,), dtype='int32')
    embedded_sequences = embedding_layer(sentence_input)
    l_lstm = Bidirectional(GRU(GRU_UNITS, return_sequences=True, kernel_regularizer=l2_reg, 
                           implementation=GPU_IMPL))(embedded_sequences)
    l_att = AttLayer(regularizer=l2_reg)(l_lstm)            
    sentEncoder = Model(sentence_input, l_att)

    review_input = Input(shape=(MAX_SENTS, MAX_SENT_LENGTH), dtype='int32')
    review_encoder = TimeDistributed(sentEncoder)(review_input)
    l_lstm_sent = Bidirectional(GRU(GRU_UNITS, return_sequences=True, kernel_regularizer=l2_reg, 
                                implementation=GPU_IMPL))(review_encoder)
    l_att_sent = AttLayer(regularizer=l2_reg)(l_lstm_sent) 
    preds = Dense(n_classes, activation='softmax', kernel_regularizer=l2_reg)(l_att_sent)
    model = Model(review_input, preds)

    model.compile(loss='categorical_crossentropy',
          optimizer=opt, #SGD(lr=0.1, nesterov=True),
          metrics=['acc'])
   ...
   model.fit(x_train[ind,:,:], y_train[ind,:], epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, shuffle=False, 
          callbacks=[cr_result, history, csv_logger], 
          verbose=2,validation_data=(x_test, y_test), class_weight = class_weight)
   ...
    %xdel model
    gc.collect()

I call the above model several times as I change optimizer. like this:

opt = optimizers.RMSprop(lr=0.0001, rho=0.9, epsilon=1e-08, decay=0.0, clipvalue=0.5)
run_han(embeddings_index, 'w2v_100_all_rms_cw', opt, class_weight)

opt = optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0, clipvalue=0.5)
run_han(embeddings_index, 'w2v_100_all_adadelta_cw', opt, class_weight)

opt =  optimizers.Adagrad(lr=0.01, epsilon=1e-08, decay=0.0, clipvalue=0.5)
run_han(embeddings_index, 'w2v_100_all_adagrad_cw', opt, class_weight)

When the model.fit() is called second time, out of memory error is showing

 RuntimeError: CUDA failure 2: out of memory ; GPU=0 ; hostname=USER-PC ; expr=cudaMalloc((void**) &deviceBufferPtr, sizeof(AllocatedElemType) * AsMultipleOf(numElements, 2))
[CALL STACK]
> Microsoft::MSR::CNTK::CudaTimer::  Stop
- Microsoft::MSR::CNTK::CudaTimer::  Stop (x2)
- Microsoft::MSR::CNTK::GPUMatrix<float>::  Resize
- Microsoft::MSR::CNTK::Matrix<float>::  Resize
- Microsoft::MSR::CNTK::DataTransferer::  operator= (x4)
- CNTK::Internal::  UseSparseGradientAggregationInDataParallelSGD
- Microsoft::MSR::CNTK::DataTransferer::  operator=
- CNTK::Internal::  UseSparseGradientAggregationInDataParallelSGD
- CNTK::Function::  Forward
- CNTK::  CreateTrainer
- CNTK::Trainer::  TotalNumberOfSamplesSeen
- CNTK::Trainer::  TrainMinibatch

I thought it is because the memory of the first run was not released from gpu, So I added this after model.fit()

%xdel model

gc.collect()

However, the error is same. I cannot figure out the cause of error. Is it because of my Keras code or CNTK?

(GTX 1080ti, Window 7, Python 2.7, CNTK 2.2, Jupyter)

like image 205
Kjyong Avatar asked Oct 17 '22 03:10

Kjyong


1 Answers

This is a really annoying problem and it arises from the fact that for some reason a code compiled to be executed on CPU is not garbage-collected properly. So even though you are running a garbage collector - a compiled model is still on GPU. In order to overcome this, you may try a solution presented here (TLDR: run training in a separate process - as when process is finished - memory is cleared)

like image 94
Marcin Możejko Avatar answered Oct 19 '22 22:10

Marcin Możejko