当存在GPU时,如何在TensorFlow中的单个脚本中训练多个模型?

Cha*_*ker 22 python machine-learning neural-network tensorflow

假设我可以在一台机器上访问多个GPU(为了争论,假设8GPU,每台机器的最大内存为8GB,每台机器有一定数量的RAM和磁盘).我想在一个单独的脚本和一台机器中运行一个程序来评估TensorFlow中的多个模型(比如50或200),每个模型都有不同的超参数设置(比如,步长,衰减率,批量大小,时期/迭代等).在训练结束时假设我们只是记录它的准确性并摆脱模型(如果你想假设模型经常检查指向,那么它可以扔掉模型并从头开始训练.你也可以假设某些其他数据可能被记录,如特定的超级参数,列车,验证,列车错误被记录为我们训练等).

目前我有一个(伪)脚本,如下所示:

def train_multiple_modles_in_one_script_with_gpu(arg):
    '''
    trains multiple NN models in one session using GPUs correctly.

    arg = some obj/struct with the params for trianing each of the models.
    '''
    #### try mutliple models
    for mdl_id in range(100):
        #### define/create graph
        graph = tf.Graph()
        with graph.as_default():
            ### get mdl
            x = tf.placeholder(float_type, get_x_shape(arg), name='x-input')
            y_ = tf.placeholder(float_type, get_y_shape(arg))
            y = get_mdl(arg,x)
            ### get loss and accuracy
            loss, accuracy = get_accuracy_loss(arg,x,y,y_)
            ### get optimizer variables
            opt = get_optimizer(arg)
            train_step = opt.minimize(loss, global_step=global_step)
        #### run session
        with tf.Session(graph=graph) as sess:
            # train
            for i in range(nb_iterations):
                batch_xs, batch_ys = get_batch_feed(X_train, Y_train, batch_size)
                sess.run(fetches=train_step, feed_dict={x: batch_xs, y_: batch_ys})
                # check_point mdl
                if i % report_error_freq == 0:
                    sess.run(step.assign(i))
                    #
                    train_error = sess.run(fetches=loss, feed_dict={x: X_train, y_: Y_train})
                    test_error = sess.run(fetches=loss, feed_dict={x: X_test, y_: Y_test})
                    print( 'step %d, train error: %s test_error %s'%(i,train_error,test_error) )
Run Code Online (Sandbox Code Playgroud)

本质上它在一次运行中尝试了很多模型,但它在一个单独的图中构建每个模型,并在一个单独的会话中运行每个模型.

我想我的主要担心是我不清楚引擎盖下的张量流如何为GPU使用分配资源.例如,它是否仅在会话运行时加载(部分)数据集?当我创建图形和模型时,它是立即引入GPU还是何时插入GPU?每次尝试新模型时,是否需要清除/释放GPU?如果模型在多个GPU中并行运行(这可能是一个很好的补充),我实际上并不太在意,但我希望它首先连续运行所有内容而不会崩溃.我需要做些什么特别的工作吗?


目前我收到的错误如下:

I tensorflow/core/common_runtime/bfc_allocator.cc:702] Stats:
Limit:                   340000768
InUse:                   336114944
MaxInUse:                339954944
NumAllocs:                      78
MaxAllocSize:            335665152

W tensorflow/core/common_runtime/bfc_allocator.cc:274] ***************************************************xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
W tensorflow/core/common_runtime/bfc_allocator.cc:275] Ran out of memory trying to allocate 160.22MiB.  See logs for memory state.
W tensorflow/core/framework/op_kernel.cc:975] Resource exhausted: OOM when allocating tensor with shape[60000,700]
Run Code Online (Sandbox Code Playgroud)

它说:

ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[60000,700]
         [[Node: standardNN/NNLayer1/Z1/add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](standardNN/NNLayer1/Z1/MatMul, b1/read)]]

I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Tesla P100-SXM2-16GB, pci bus id: 0000:06:00.0)
Run Code Online (Sandbox Code Playgroud)

然而,在输出文件(它打印的地方)的下方,似乎可以打印出应该在训练过程中显示的错误/消息.这是否意味着它没有耗尽资源?或者它真的能够使用GPU?如果它能够使用CPU而不是CPU,那么为什么只有在即将使用GPU时才会发生错误?

奇怪的是,数据集真的不是那么大(所有60K点都是24.5M),当我在自己的计算机上本地运行单个模型时,似乎该过程使用的不到5GB.GPU至少有8GB,带有它们的计算机有足够的RAM和磁盘(至少16GB).因此,张量流向我投掷的错误令人费解.它试图做什么,为什么会发生?有任何想法吗?


在阅读了建议使用多处理库的答案后,我想出了以下脚本:

def train_mdl(args):
    train(mdl,args)

if __name__ == '__main__':
    for mdl_id in range(100):
        # train one model with some specific hyperparms (assume they are chosen randomly inside the funciton bellow or read from a config file or they could just be passed or something)
        p = Process(target=train_mdl, args=(args,))
        p.start()
        p.join()
    print('Done training all models!')
Run Code Online (Sandbox Code Playgroud)

老实说,我不确定为什么他的回答建议使用池,或者为什么有奇怪的元组括号,但这对我来说是有意义的.每次在上面的循环中创建新进程时,是否会重新分配tensorflow的资源?

Yuv*_*mon 20

我认为在一个单一的脚本中运行所有模型从长远来看可能是不好的做法(请参阅下面的建议以获得更好的替代方案).但是,如果您想这样做,这里有一个解决方案:您可以将TF会话封装到具有multiprocessing模块的进程中,这将确保TF在进程完成后释放会话内存.这是一段代码:

from multiprocessing import Pool
import contextlib
def my_model((param1, param2, param3)): # Note the extra (), required by the pool syntax
    < your code >

num_pool_worker=1 # can be bigger than 1, to enable parallel execution 
with contextlib.closing(Pool(num_pool_workers)) as po: # This ensures that the processes get closed once they are done
     pool_results = po.map_async(my_model,
                                    ((param1, param2, param3)
                                     for param1, param2, param3 in params_list))
     results_list = pool_results.get()
Run Code Online (Sandbox Code Playgroud)

OP注意:如果您选择使用随机数生成器种子,则不会使用多处理库自动重置.详细信息:对每个进程使用带有不同随机种子的python多处理

关于TF资源分配:通常TF分配的资源比它需要的多得多.很多时候,您可以限制每个进程使用总GPU内存的一小部分,并通过反复试验发现脚本所需的分数.

您可以使用以下代码段执行此操作

gpu_memory_fraction = 0.3 # Choose this number through trial and error
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction,)
session_config = tf.ConfigProto(gpu_options=gpu_options)
sess = tf.Session(config=session_config, graph=graph)
Run Code Online (Sandbox Code Playgroud)

请注意,有时TF会增加内存使用量以加快执行速度.因此,减少内存使用量可能会使模型运行速度变慢.

您编辑/评论中的新问题的答案:

  1. 是的,每次创建新流程时都会重新分配Tensorflow,并在流程结束后清除.

  2. 编辑中的for循环也应该完成这项工作.我建议使用Pool,因为它可以让你在一个GPU上同时运行多个模型.请参阅我关于设置gpu_memory_fraction和"选择最大进程数"的说明.另请注意:(1)Pool map为您运行循环,因此一旦使用它就不需要外部for循环.(2)在你的例子中,你应该mdl=get_model(args)在调用train()之前有类似的东西

  3. 奇怪的元组括号:Pool只接受一个参数,因此我们使用一个元组来传递多个参数.有关更多详细信息,请参阅multiprocessing.pool.map和带有两个参数的函数.正如一个答案中所建议的那样,你可以使它更具可读性

    def train_mdl(params):
        (x,y)=params
        < your code >
    
    Run Code Online (Sandbox Code Playgroud)
  4. 正如@Seven建议的那样,您可以使用CUDA_VISIBLE_DEVICES环境变量来选择要用于您的进程的GPU.你可以在你的python脚本中使用以下过程函数(train_mdl)的开头来完成它.

    import os # the import can be on the top of the python script
    os.environ["CUDA_VISIBLE_DEVICES"] = "{}".format(gpu_id)
    
    Run Code Online (Sandbox Code Playgroud)

执行实验的更好方法是将训练/评估代码与超参数/模型搜索代码隔离开来.例如,有一个名为的脚本train.py,它接受超参数的特定组合和对数据的引用作为参数,并对单个模型执行训练.

然后,要遍历所有可能的参数组合,您可以使用简单的任务(作业)队列,并将所有可能的超参数组合作为单独的作业提交.任务队列将一次向您的计算机提供一个作业.通常,您还可以将队列设置为同时执行多个进程(请参阅下面的详细信息).

具体来说,我使用任务假脱机程序,它非常容易安装和少数(不需要管理员权限,详情如下).

基本用法是(请参阅下面有关任务假脱机程序使用情况的说明):

ts <your-command>
Run Code Online (Sandbox Code Playgroud)

在实践中,我有一个单独的python脚本来管理我的实验,设置每个特定实验的所有参数并将作业发送到ts队列.

以下是我的实验经理的python代码的一些相关摘要:

run_bash 执行bash命令

def run_bash(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, executable='/bin/bash')
    out = p.stdout.read().strip()
    return out  # This is the stdout from the shell command
Run Code Online (Sandbox Code Playgroud)

下一个代码段设置要运行的并发进程数(请参阅下面有关选择最大进程数的说明):

max_job_num_per_gpu = 2
run_bash('ts -S %d'%max_job_num_per_gpu)
Run Code Online (Sandbox Code Playgroud)

下一个片段迭代了超级参数/模型参数的所有组合的列表.列表的每个元素都是一个字典,其中键是train.py脚本的命令行参数

for combination_dict in combinations_list:

    job_cmd = 'python train.py ' + '  '.join(
            ['--{}={}'.format(flag, value) for flag, value in combination_dict.iteritems()])

    submit_cmd = "ts bash -c '%s'" % job_cmd
    run_bash(submit_cmd)
Run Code Online (Sandbox Code Playgroud)

关于选择最大进程数的说明:

如果您缺少GPU,可以使用gpu_memory_fraction找到的,将进程数设置为max_job_num_per_gpu=int(1/gpu_memory_fraction)

有关任务假脱机程序(ts)的说明:

  1. 您可以使用以下命令设置要运行的并发进程数("slots"):

    ts -S <number-of-slots>

  2. 安装ts不需要管理员权限.您可以从源代码下载并编译它make,只需将其添加到您的路径中即可完成.

  3. 您可以设置多个队列(我将它用于多个GPU)

    TS_SOCKET=<path_to_queue_name> ts <your-command>

    例如

    TS_SOCKET=/tmp/socket-ts.gpu_queue_1 ts <your-command>

    TS_SOCKET=/tmp/socket-ts.gpu_queue_2 ts <your-command>

  4. 有关更多用法示例,请参见此处

关于自动设置路径名和文件名的注意事项: 将主代码与实验管理器分开后,您需要一种有效的方法来生成文件名和目录名,给定超级参数.我通常将我的重要超级参数保存在字典中,并使用以下函数从字典键值对生成单个链式字符串.以下是我用来执行此操作的函数:

def build_string_from_dict(d, sep='%'):
    """
     Builds a string from a dictionary.
     Mainly used for formatting hyper-params to file names.
     Key-value pairs are sorted by the key name.

    Args:
        d: dictionary

    Returns: string
    :param d: input dictionary
    :param sep: key-value separator

    """

    return sep.join(['{}={}'.format(k, _value2str(d[k])) for k in sorted(d.keys())])


def _value2str(val):
    if isinstance(val, float): 
        # %g means: "Floating point format.
        # Uses lowercase exponential format if exponent is less than -4 or not less than precision,
        # decimal format otherwise."
        val = '%g' % val
    else:
        val = '{}'.format(val)
    val = re.sub('\.', '_', val)
    return val
Run Code Online (Sandbox Code Playgroud)

  • 就像一个评论(不确定它在你的答案中是否值得一提)但我发现(仅在运行我的实验几周后)是随机数生成器种子如果你选择使用它就不会自动重置过程库.在浪费数月的实验和计算之前,请检查http://stackoverflow.com/questions/9209078/using-python-multiprocessing-with-different-random-seed-for-each-process. (2认同)

归档时间:

查看次数:

9793 次

最近记录:

6 年,7 月 前