TensorFlow1.15,多GPU-1-machine,batch_size怎么设置?

数据挖掘 深度学习 张量流 伯特 变压器
2022-02-19 10:37:22

输入功能代码:

    def input_fn(params):
        """The actual input function."""
        batch_size = FLAGS.train_batch_size

        name_to_features = {
            "input_ids":
                tf.FixedLenFeature([max_seq_length], tf.int64),
            "input_mask":
                tf.FixedLenFeature([max_seq_length], tf.int64),
            "segment_ids":
                tf.FixedLenFeature([max_seq_length], tf.int64),
            "masked_lm_positions":
                tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
            "masked_lm_ids":
                tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
            "masked_lm_weights":
                tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
            "next_sentence_labels":
                tf.FixedLenFeature([1], tf.int64),
        }

        # For training, we want a lot of parallel reading and shuffling.
        # For eval, we want no shuffling and parallel reading doesn't matter.
        if is_training:
            d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
            d = d.repeat()
            d = d.shuffle(buffer_size=len(input_files))

            # `cycle_length` is the number of parallel files that get read.
            cycle_length = min(num_cpu_threads, len(input_files))

            # `sloppy` mode means that the interleaving is not exact. This adds
            # even more randomness to the training pipeline.
            d = d.apply(
                tf.contrib.data.parallel_interleave(
                    tf.data.TFRecordDataset,
                    sloppy=is_training,
                    cycle_length=cycle_length))
            d = d.shuffle(buffer_size=100)
        else:
            d = tf.data.TFRecordDataset(input_files)
            # Since we evaluate for a fixed number of steps we don't want to encounter
            # out-of-range exceptions.
            d = d.repeat()

        # We must `drop_remainder` on training because the TPU requires fixed
        # size dimensions. For eval, we assume we are evaluating on the CPU or GPU
        # and we *don't* want to drop the remainder, otherwise we wont cover
        # every sample.
        d = d.apply(
            tf.contrib.data.map_and_batch(
                lambda record: _decode_record(record, name_to_features),
                batch_size=batch_size,
                num_parallel_batches=num_cpu_threads,
                drop_remainder=True))
        d = d.prefetch(10)
        return d

镜像策略代码:

    distribution = tf.contrib.distribute.MirroredStrategy(
        devices=["device:GPU:%d" % i for i in range(FLAGS.n_gpus)],
        # num_gpus=4,
        cross_tower_ops=tf.distribute.HierarchicalCopyAllReduce())
    run_config = RunConfig(
        train_distribute=distribution,
        # eval_distribute=dist_strategy,
        log_step_count_steps=log_every_n_steps,
        model_dir=FLAGS.output_dir,
        save_checkpoints_steps=FLAGS.save_checkpoints_steps)

    model_fn = model_fn_builder(
        bert_config=bert_config,
        init_checkpoint=FLAGS.init_checkpoint,
        learning_rate=FLAGS.learning_rate,
        num_train_steps=FLAGS.num_train_steps,
        num_warmup_steps=FLAGS.num_warmup_steps,
        use_tpu=FLAGS.use_tpu,
        use_one_hot_embeddings=FLAGS.use_tpu)

    # If TPU is not available, this will fall back to normal Estimator on CPU
    # or GPU.
    estimator = Estimator(
        model_fn=model_fn,
        params={},
        config=run_config)

问题是,如果我有 4 个 GPU。每个 GPU 可以运行 8 个批量大小。我设置batch_size = 8不是32。batch_size = 32会OOM。

我对吗?数据会以不同的批次分布到 4 个 GPU 上吗?

2个回答

如果您使用 Keras、Estimator 或自定义训练循环,Tensorflow 会在分配策略上以不同方式处理批次。

由于您在一个工作人员(1 台机器)中使用带有 MirroredStrategy 的 TF1.15 Estimator,因此每个副本(每个 GPU 一个)将收到FLAGS.train_batch_size. 因此,如果您有 4 个 GPU,那么全局批量大小将为4 * FLAGS.train_batch_size.

这是解释:

然而,在 Estimator 中,用户提供一个 input_fn 并完全控制他们希望如何在工作人员和设备之间分配数据。我们不会自动拆分批次,也不会自动将数据分片到不同的工作人员之间。每个工作人员调用一次提供的 input_fn,从而为每个工作人员提供一个数据集。然后将该数据集中的一批馈送到该工作人员上的一个副本,从而为 1 个工作人员上的 N 个副本消耗 N 个批次。换句话说,由 input_fn 返回的数据集应该提供大小为 PER_REPLICA_BATCH_SIZE 的批次。一个步骤的全局批量大小可以通过 PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync 获得。

资料来源:TF1.X 发行策略笔记本

根据BERT-GPU

代码没有问题。

适用于batch_size1 个 GPU。