memory - 如何确定 Keras 模型所需的内存?

标签 memory keras

我正在使用 Keras 2.0.0,我想在 GPU 上训练一个具有大量参数的深度模型。 使用太大的图像,我的内存不足 (OOM)。 使用太低的图像,模型的准确性会比可能的差。 因此,我想找到适合我的 GPU 的图像的最大可能输入大小。 给定模型和输入数据,是否有任何计算内存的功能(例如,与 model.summary() 相当)?

感谢您的帮助。

最佳答案

我根据 Fabrício Pereira 的回答创建了一个完整的函数。

def get_model_memory_usage(batch_size, model):
    import numpy as np
    try:
        from keras import backend as K
    except:
        from tensorflow.keras import backend as K

    shapes_mem_count = 0
    internal_model_mem_count = 0
    for l in model.layers:
        layer_type = l.__class__.__name__
        if layer_type == 'Model':
            internal_model_mem_count += get_model_memory_usage(batch_size, l)
        single_layer_mem = 1
        out_shape = l.output_shape
        if type(out_shape) is list:
            out_shape = out_shape[0]
        for s in out_shape:
            if s is None:
                continue
            single_layer_mem *= s
        shapes_mem_count += single_layer_mem

    trainable_count = np.sum([K.count_params(p) for p in model.trainable_weights])
    non_trainable_count = np.sum([K.count_params(p) for p in model.non_trainable_weights])

    number_size = 4.0
    if K.floatx() == 'float16':
        number_size = 2.0
    if K.floatx() == 'float64':
        number_size = 8.0

    total_memory = number_size * (batch_size * shapes_mem_count + trainable_count + non_trainable_count)
    gbytes = np.round(total_memory / (1024.0 ** 3), 3) + internal_model_mem_count
    return gbytes

更新 2019.10.06:增加了对包含其他模型作为层的模型的支持。

UPDATE 2020.07.17:函数现在可以在 TensorFlow v2 中正常工作。

关于memory - 如何确定 Keras 模型所需的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137288/

相关文章:

c - GCC:为什么常量变量没有放在 .rodata 中

memory - Cuda:如果我只使用 .x 的 block 和线程,它是否仍会使用 GPU 中的所有可用线程,还是必须使用 .y 和 .z 的线程和 block ?

java - 静态数组如何存储在 Java 内存中?

Tcl 包装器中的内存泄漏

keras - 在keras model.summary中连接的图层的 "[0][0]"是什么意思?

python - 序列上的 LSTM 自动编码器 - 什么损失函数?

python - 为什么我的 keras 模型需要 3D 列表来预测?

deep-learning - Keras 中的 CNN-LSTM : Dimension Error

python - keras 中 softmax 输出的一个热输入

memory - 固定内存 OpenCL,有人成功使用过吗?