tf.estimator 错误:ResourceExhausted:打开的文件太多(TF 使 events.out.tfevents 文件保持打开状态)

2024-01-11

多次调用后出现以下错误train_model在下面的课程中:

terminate called after throwing an instance of 'std::system_error' what(): Resource temporarily unavailable

我希望能够打电话train_model多次固定num_steps和不同的model_dir实例化该类后。

(我认为某处存在内存泄漏,但我无法找出导致它的原因(每次调用后GPU内存使用量不会改变)train_model,但每次调用后 RAM 使用量都会略有增加。当我收到错误时,我的机器上仍然有大量可用的 RAM 和 GPU 内存。) --> Update: 不是内存泄漏而是打开了太多文件

Update:

我在另一台机器上运行了这个,错误更清楚:资源耗尽:打开的文件太多

我在看lsof并注意到 TF 一直在events.out.tfevents每次调用后打开文件train_model具有不同的检查点目录。知道如何关闭events.out.tfevents调用 tf.estimator 后的文件?

这是我的代码(一个简单的前馈神经网络,带有 dropout 和用于分类的批量归一化):

class Model:
def __init__(self):
    self.data_loaded = False
    self.train_data = None
    self.valid_data = None
    print('class created!')


def input_fn(self, mode, batch_size, num_epochs=None):
    if mode == 'train':
        features_cont = self.data_dict['x_train_cont']
        features_cat = self.data_dict['x_train_cat']
        labels = self.data_dict['y_train']
    elif mode == 'valid':
        features_cont = self.data_dict['x_valid_cont']
        features_cat = self.data_dict['x_valid_cat']
        labels = self.data_dict['y_valid']
        num_epochs = 1
    elif mode == 'test':
        features_cont = self.data_dict['x_test_cont']
        features_cat = self.data_dict['x_test_cat']
        labels = np.zeros([features_cont.shape[0], 1])
        num_epochs = 1

    features = np.concatenate([features_cont, features_cat], axis=1)

    shuffle = mode == 'train'

    return tf.estimator.inputs.numpy_input_fn(features, labels,
                                              batch_size=batch_size,
                                              num_epochs=num_epochs,
                                              shuffle=shuffle)


def model_fn(self, features, labels, mode, params):
    is_training = mode == tf.estimator.ModeKeys.TRAIN
    # concat cont and cat features
    l2_weights = params['l2_w']
    dropout_rates = params['dropout']
    n_classes = 2  # binary classification
    x_in = features #tf.concat(features, axis=1)
    hidden_layer = x_in

    for i, num_units in enumerate(params['num_units']):
        hidden_layer = tf.layers.dense(inputs=hidden_layer,
                                         units=num_units,
                                         name='hidden_{}'.format(i),
                                         kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=l2_weights[i]))

        hidden_layer = tf.layers.batch_normalization(hidden_layer, training=is_training)

        hidden_layer = tf.nn.relu(hidden_layer)

        hidden_layer = tf.layers.dropout(inputs=hidden_layer,
                                         rate=dropout_rates[i],
                                         name='hidden_drop_{}'.format(i),
                                         training=is_training)

    logits = tf.layers.dense(inputs=hidden_layer,
                             units=n_classes,
                             name='output')

    predictions = tf.nn.softmax(logits, name='probability_predictions')

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode,
                                          predictions={'predictions': predictions},
                                          # export_outputs=export_outputs
                                          )

    weights = tf.gather(tf.constant(self.class_weights), tf.cast(labels[:, 1], tf.int32))
    l2_loss = tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
    loss = tf.losses.softmax_cross_entropy(labels, logits, weights) + l2_loss

    auc = tf.metrics.auc(labels[:, 1], predictions[:, 1])
    eval_metric_ops = {'auc': auc}

    if mode == tf.estimator.ModeKeys.EVAL:
        return tf.estimator.EstimatorSpec(mode, loss=loss,
                                          eval_metric_ops=eval_metric_ops)

    assert mode == tf.estimator.ModeKeys.TRAIN
    # needed for batch norm layer
    extra_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    global_step = tf.train.get_global_step()
    optimizer = tf.train.AdamOptimizer(learning_rate=params['learning_rate'], epsilon=1e-07)
    with tf.control_dependencies(extra_ops):
        train_op = optimizer.minimize(loss, global_step=global_step)

    # Set logging hook for tf.estimator
    logging_hook = tf.train.LoggingTensorHook({'step': global_step,
                                               'loss': loss,
                                               #'auc': auc[1]
                                               },
                                              every_n_iter=1)
    return tf.estimator.EstimatorSpec(mode=mode,
                                      loss=loss,
                                      train_op=train_op,
                                      training_hooks=[logging_hook])

def train_model(self, hps, model_dir=None, num_steps=None):
    max_steps = None
    num_epochs = None
    # get TF logger
    tf.logging.set_verbosity(tf.logging.INFO)
    if not os.path.exists(model_dir):
        os.makedirs(model_dir)
    self.setup_tf_logger(model_dir)
    config = tf.ConfigProto(allow_soft_placement=True,
                            log_device_placement=False)
    config.gpu_options.allow_growth = True
    run_config = tf.estimator.RunConfig(
        save_checkpoints_steps=1e10,
        keep_checkpoint_max=1,
        model_dir=model_dir,
        session_config=config
    )
    batch_size = hps['batch_size']

    if self.train_data is None:
        self.train_data =  self.input_fn(mode='train',
                                           batch_size=batch_size,
                                           num_epochs=num_epochs)
        self.valid_data =  self.input_fn(mode='valid',
                                           batch_size=100000,
                                           num_epochs=1)

    model = tf.estimator.Estimator(model_fn=self.model_fn,
                                   params=hps,
                                   config=run_config)
    model.train(input_fn=self.train_data,
                steps=num_steps,
                max_steps=None)
    eval_out = model.evaluate(input_fn=self.valid_data)
    return eval_out['auc']

更新2:

我不得不更改 TF 代码来解决这个问题。 目前在basic_session_run_hooks.py and estimator.py flush()在摘要编写器上调用,它仅转储数据但不关闭文件。

我将摘要编写器的调用更改为close()代替flush()。这些文件似乎在调用 tf.estimator 后关闭,我不再收到 ResourceExhausted 错误。

张量流团队使用一定有一个原因(可能是打开和关闭文件的成本)flush()代替close()关于摘要编写者,但这可能会导致类似于我在这里报告的问题。


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

tf.estimator 错误:ResourceExhausted:打开的文件太多(TF 使 events.out.tfevents 文件保持打开状态) 的相关文章

  • Keras 通过设置种子获得不同的结果[重复]

    这个问题在这里已经有答案了 在keras中 每次运行都有很高的方差和不稳定的性能 为了解决这个问题 根据https keras io getting started faq how can i obtain reproducible res
  • 用于分布式计算的 Tensorflow 设置

    任何人都可以提供有关如何设置张量流以在网络上的许多CPU上工作的指导吗 到目前为止 我发现的所有示例最多只使用一个本地盒子和多个 GPU 我发现我可以在 session opts 中传递目标列表 但我不确定如何在每个盒子上设置张量流来侦听网
  • 在不同的 GPU 上同时训练多个 keras/tensorflow 模型

    我想在 Jupyter Notebook 中同时在多个 GPU 上训练多个模型 我正在使用 4GPU 的节点上工作 我想将一个 GPU 分配给一个模型并同时训练 4 个不同的模型 现在 我通过 例如 为一台笔记本选择 GPU import
  • 张量流和线程

    下面是来自 Tensorflow 网站的简单 mnist 教程 即单层 softmax 我尝试通过多线程训练步骤对其进行扩展 from tensorflow examples tutorials mnist import input dat
  • 张量流如何处理无法存储在一个盒子中的大变量

    我想通过训练超过十亿特征维度的数据来训练 DNN 模型 因此第一层权重矩阵的形状将为 1 000 000 000 512 这个权重矩阵太大 无法存储在一个盒子中 目前有没有什么解决方案来处理这么大的变量 例如将大的权重矩阵划分为多个框 Up
  • PIL.Image.open和tf.image.decode_jpeg返回值的区别

    我使用 PIL Image open 和 tf image decode jpeg 将图像文件解析为数组 但发现PIL Image open 中的像素值与tf image decode jpeg不一样 为什么会出现这种情况 Thanks 代
  • Tensorflow中通过字符串选择不同的模式

    我正在尝试构建一个 VAE 网络 我希望模型在不同的模式下做不同的事情 我有三种模式 训练 相同 和 不同 以及一个名为 interpolation mode 的函数 它根据模式执行不同的操作 我的代码如下所示 import tensorf
  • 带有 CUDA 的 Tensorflow:导入错误

    我已经按照 NVIDIA 教程中的说明一步步安装了 TensorFlow Ubuntu 16 04 桌面版 GTX 970 http www nvidia com object gpu accelerated applications te
  • 阻止 TensorFlow 访问 GPU? [复制]

    这个问题在这里已经有答案了 有没有一种方法可以纯粹在CPU上运行TensorFlow 我机器上的所有内存都被运行 TensorFlow 的单独进程占用 我尝试将 per process memory fraction 设置为 0 但未成功
  • Tensorflow 中的自定义资源

    由于某些原因 我需要为 Tensorflow 实现自定义资源 我试图从查找表实现中获得灵感 如果我理解得好的话 我需要实现3个TF操作 创建我的资源 资源的初始化 例如 在查找表的情况下填充哈希表 执行查找 查找 查询步骤 为了促进实施 我
  • 在相同任务上,Keras 比 TensorFlow 慢

    我正在使用 Python 运行斩首 DCNN 本例中为 Inception V3 来获取图像特征 我使用的是 Anaconda Py3 6 和 Windows7 使用 TensorFlow 时 我将会话保存在变量中 感谢 jdehesa 并
  • TensorFlow:在训练时更改变量

    如果我将输入管道从 feed dict 更改为 tf data dataset 如何在每次迭代后的训练期间更改网络内参数的值 澄清一下 旧代码看起来像这样 Define Training Step model is some class t
  • 如何将张量流模型部署到azure ml工作台

    我在用Azure ML Workbench执行二元分类 到目前为止 一切正常 我有很好的准确性 我想将模型部署为用于推理的 Web 服务 我真的不知道从哪里开始 azure 提供了这个doc https learn microsoft co
  • tf.gather_nd 直观上是做什么的?

    你能直观地解释一下或者举更多例子吗tf gather nd用于在 Tensorflow 中索引和切片为高维张量 我读了API https www tensorflow org api docs python tf gather nd 但它保
  • TensorFlow HVX 加速支持

    我成功构建并运行了测试应用程序https github com tensorflow tensorflow tree master tensorflow contrib hvx https github com tensorflow ten
  • Tensorflow 与 Keras 的兼容性

    我正在使用 Python 3 6 和 Tensorflow 2 0 并且有一些 Keras 代码 import keras from keras models import Sequential from keras layers impo
  • 使用 tf.estimator.Estimator 加载检查点和微调

    我们正在尝试将旧的训练代码转换为更符合 tf estimator Estimator 的代码 在初始代码中 我们针对目标数据集微调原始模型 在使用以下组合进行训练之前 仅从检查点加载一些层要恢复的变量 and init fn与监控培训课程
  • 无法使用tensorflow 2.0.0 beta1保存模型

    我已尝试了文档中描述的所有选项 但没有一个允许我将模型保存在tensorflow 2 0 0 beta1中 我还尝试升级到 也不稳定 TF2 RC 但这甚至破坏了我在测试版中工作的代码 所以我很快就回滚到测试版 请参阅下面的最小复制代码 我
  • 将 tf.contrib.layers.xavier_initializer() 更改为 2.0.0

    我该如何改变 tf contrib layers xavier initializer tf 版本 gt 2 0 0 所有代码 W1 tf get variable W1 shape self input size h size initi
  • 如何从 Pandas DataFrame 转换为 Tensorflow BatchDataset 以进行 NLP?

    老实说 我想弄清楚如何转换数据集 格式 pandasDataFrame或 numpy 数组 转换为简单文本分类张量流模型可以训练用于情感分析的形式 我使用的数据集类似于 IMDB 包含文本和标签 正面或负面 我看过的每个教程要么以不同的方式

随机推荐