TensorFlow 多 GPU 处理并行数据

简介: Multi-GPU processing with data parallelismIf you write your software in a language like C++ for a single cpu c...

Multi-GPU processing with data parallelism

If you write your software in a language like C++ for a single cpu core, making it run on multiple GPUs in parallel would require rewriting the software from scratch. But this is not the case with TensorFlow. Because of its symbolic nature, tensorflow can hide all that complexity, making it effortless to scale your program across many CPUs and GPUs.

Let’s start with the simple example of adding two vectors on CPU:

 import tensorflow as tf

with tf.device(tf.DeviceSpec(device_type='CPU', device_index=0)):
    a = tf.random_uniform([1000, 100])
    b = tf.random_uniform([1000, 100])
    c = a + b

tf.Session().run(c)

The same thing can as simply be done on GPU:

with tf.device(tf.DeviceSpec(device_type='GPU', device_index=0)):
    a = tf.random_uniform([1000, 100])
    b = tf.random_uniform([1000, 100])
    c = a + b
 ```

But what if we have two GPUs and want to utilize both? To do that, we can split the data and use a separate GPU for processing each half:
```python
split_a = tf.split(a, 2)
split_b = tf.split(b, 2)

split_c = []
for i in range(2):
    with tf.device(tf.DeviceSpec(device_type='GPU', device_index=i)):
        split_c.append(split_a[i] + split_b[i])

c = tf.concat(split_c, axis=0)
 ```

Let's rewrite this in a more general form so that we can replace addition with any other set of operations:




<div class="se-preview-section-delimiter"></div>

```python
def make_parallel(fn, num_gpus, **kwargs):
    in_splits = {}
    for k, v in kwargs.items():
        in_splits[k] = tf.split(v, num_gpus)

    out_split = []
    for i in range(num_gpus):
        with tf.device(tf.DeviceSpec(device_type='GPU', device_index=i)):
            with tf.variable_scope(tf.get_variable_scope(), reuse=i > 0):
                out_split.append(fn(**{k : v[i] for k, v in in_splits.items()}))

    return tf.concat(out_split, axis=0)


def model(a, b):
    return a + b

c = make_parallel(model, 2, a=a, b=b)

You can replace the model with any function that takes a set of tensors as input and returns a tensor as result with the condition that both the input and output are in batch. Note that we also added a variable scope and set the reuse to true. This makes sure that we use the same variables for processing both splits. This is something that will become handy in our next example.

Let’s look at a slightly more practical example. We want to train a neural network on multiple GPUs. During training we not only need to compute the forward pass but also need to compute the backward pass (the gradients). But how can we parallelize the gradient computation? This turns out to be pretty easy.

Recall from the first item that we wanted to fit a second degree polynomial to a set of samples. We reorganized the code a bit to have the bulk of the operations in the model function:

import numpy as np
import tensorflow as tf

def model(x, y):
    w = tf.get_variable("w", shape=[3, 1])

    f = tf.stack([tf.square(x), x, tf.ones_like(x)], 1)
    yhat = tf.squeeze(tf.matmul(f, w), 1)

    loss = tf.square(yhat - y)
    return loss

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

loss = model(x, y)

train_op = tf.train.AdamOptimizer(0.1).minimize(
    tf.reduce_mean(loss))

def generate_data():
    x_val = np.random.uniform(-10.0, 10.0, size=100)
    y_val = 5 * np.square(x_val) + 3
    return x_val, y_val

sess = tf.Session()
sess.run(tf.global_variables_initializer())
for _ in range(1000):
    x_val, y_val = generate_data()
    _, loss_val = sess.run([train_op, loss], {x: x_val, y: y_val})

_, loss_val = sess.run([train_op, loss], {x: x_val, y: y_val})
print(sess.run(tf.contrib.framework.get_variables_by_name("w")))

Now let’s use make_parallel that we just wrote to parallelize this. We only need to change two lines of code from the above code:

loss = make_parallel(model, 2, x=x, y=y)

train_op = tf.train.AdamOptimizer(0.1).minimize(
    tf.reduce_mean(loss),
    colocate_gradients_with_ops=True)

The only thing that we need to change to parallelize backpropagation of gradients is to set the colocate_gradients_with_ops flag to true. This ensures that gradient ops run on the same device as the original op.

更多教程:http://www.tensorflownews.com/

相关实践学习
在云上部署ChatGLM2-6B大模型(GPU版)
ChatGLM2-6B是由智谱AI及清华KEG实验室于2023年6月发布的中英双语对话开源大模型。通过本实验,可以学习如何配置AIGC开发环境,如何部署ChatGLM2-6B大模型。
目录
相关文章
|
人工智能 负载均衡 算法
DeepSeek开源周第四弹之二!EPLB:专为V3/R1设计的专家并行负载均衡器,让GPU利用率翻倍!
EPLB 是 DeepSeek 推出的专家并行负载均衡器,通过冗余专家策略和负载均衡算法,优化大规模模型训练中的 GPU 资源利用率和训练效率。
1489 122
DeepSeek开源周第四弹之二!EPLB:专为V3/R1设计的专家并行负载均衡器,让GPU利用率翻倍!
|
人工智能 Linux iOS开发
exo:22.1K Star!一个能让任何人利用日常设备构建AI集群的强大工具,组成一个虚拟GPU在多台设备上并行运行模型
exo 是一款由 exo labs 维护的开源项目,能够让你利用家中的日常设备(如 iPhone、iPad、Android、Mac 和 Linux)构建强大的 AI 集群,支持多种大模型和分布式推理。
4721 101
|
数据挖掘 PyTorch TensorFlow
|
存储 并行计算 数据处理
使用GPU 加速 Polars:高效解决大规模数据问题
Polars 最新开发了 GPU 加速执行引擎,支持对超过 100GB 的数据进行交互式操作。本文详细介绍了 Polars 中 DataFrame(DF)的概念及其操作,包括筛选、数学运算和聚合函数等。Polars 提供了“急切”和“惰性”两种执行模式,后者通过延迟计算实现性能优化。启用 GPU 加速后,只需指定 GPU 作为执行引擎即可大幅提升处理速度。实验表明,GPU 加速比 CPU 上的懒惰执行快 74.78%,比急切执行快 77.38%。Polars 的查询优化器智能管理 CPU 和 GPU 之间的数据传输,简化了 GPU 数据处理。这一技术为大规模数据集处理带来了显著的性能提升。
1094 4
|
机器学习/深度学习 数据挖掘 TensorFlow
🔍揭秘Python数据分析奥秘,TensorFlow助力解锁数据背后的亿万商机
【9月更文挑战第11天】在信息爆炸的时代,数据如沉睡的宝藏,等待发掘。Python以简洁的语法和丰富的库生态成为数据分析的首选,而TensorFlow则为深度学习赋能,助你洞察数据核心,解锁商机。通过Pandas库,我们可以轻松处理结构化数据,进行统计分析和可视化;TensorFlow则能构建复杂的神经网络模型,捕捉非线性关系,提升预测准确性。两者的结合,让你在商业竞争中脱颖而出,把握市场脉搏,释放数据的无限价值。以下是使用Pandas进行简单数据分析的示例:
207 5
|
数据挖掘 PyTorch TensorFlow
Python数据分析新纪元:TensorFlow与PyTorch双剑合璧,深度挖掘数据价值
【7月更文挑战第30天】随着大数据时代的发展,数据分析变得至关重要,深度学习作为其前沿技术,正推动数据分析进入新阶段。本文介绍如何结合使用TensorFlow和PyTorch两大深度学习框架,最大化数据价值。
561 8
|
机器学习/深度学习 数据挖掘 TensorFlow
🔍揭秘Python数据分析奥秘,TensorFlow助力解锁数据背后的亿万商机
【7月更文挑战第29天】在数据丰富的时代,Python以其简洁和强大的库支持成为数据分析首选。Pandas库简化了数据处理与分析,如读取CSV文件、执行统计分析及可视化销售趋势。TensorFlow则通过深度学习技术挖掘复杂数据模式,提升预测准确性。两者结合助力商业决策,把握市场先机,释放数据巨大价值。
217 4
|
TensorFlow 算法框架/工具 异构计算
【Tensorflow 2】查看GPU是否能应用
提供了检查TensorFlow是否能应用GPU的方法。
381 2
|
机器学习/深度学习 数据挖掘 TensorFlow
数据界的“福尔摩斯”如何炼成?Python+TensorFlow数据分析实战全攻略
【7月更文挑战第30天】数据界的“福尔摩斯”运用Python与TensorFlow解开数据之谜。
331 2
|
机器学习/深度学习 数据挖掘 TensorFlow

热门文章

最新文章