【PyTorch】静态图与动态图机制

静态图( Tensorflow

TensorFlow 使用静态图,这意味着我们先定义计算图,然后不断使用它,中间是不能够改变它的计算图的,且定义静态图时需要使用新的特殊语法,这也意味着图设定时 无法使用if、while等结构,而是需要特殊的由框架专门设计的语法 (例如无法使用while,所以需要使用辅助函数 tf.while_loop 写成 TensorFlow 内部的形式 在构建图时,我们需要考虑到所有的情况(即各个if分支图结构必须全部在图中,即使不一定会在每一次运行时使用到),使得静态图异常庞大占用过多显存。

summary:占据的显存大,由于一次性构建了全部的计算图所以运行速度快;

TensorFlow 需要将整个图构建成静态的,换句话说, 每次运行的时候图都是一样的,是不能够改变的(这就是静态二字的来源),所以不能直接使用 Python 的 while 循环语句,需要使用辅助函数 tf.while_loop 写成 TensorFlow 内部的形式

import tensorflow as tf

first_counter = tf.constant(0)
second_counter = tf.constant(10)

def cond(first_counter, second_counter, *args):
    return first_counter < second_counter

def body(first_counter, second_counter):
    first_counter = tf.add(first_counter, 2)
    second_counter = tf.add(second_counter, 1)
    return first_counter , second_counter

c1, c2 = tf.while_loop(cond, body, [first_counter, second_counter])

with tf.Session() as sess:
    counter_1_res, counter_2_res = sess.run([c1,c2])
print(counter_1_res)
print(counter_2_res)

输出:
20
20

动态图(Pytorch)

而在 PyTorch 中,它兼容python的各种逻辑控制语法, 每次都会重新构建一个新的计算图

对于使用者来说,两种形式的计算图有着非常大的区别,同时静态图和动态图都有他们各自的优点,比如动态图比较方便debug,使用者能够用任何他们喜欢的方式进行debug,同时非常直观,而静态图是通过先定义后运行的方式,之后再次运行的时候就不再需要重新构建计算图,所以速度会比动态图更快。

summary:占据的显存小,易调试(debug),但是由于需要重新构建该分支的计算图所以运行速度慢;

PyTorch 的动态图机制,这使得我们能够使用 Python 的 while 写循环,非常方便。

import torch

first_counter = torch.Tensor([0])
second_counter = torch.Tensor([10])

while (first_counter < second_counter)[0]:
    first_counter += 2
    second_counter += 1

print(first_counter)
print(second_counter)

输出:
tensor([20.])
tensor([20.])

Original: https://blog.csdn.net/weixin_43135178/article/details/118354283
Author: 马鹏森
Title: 【PyTorch】静态图与动态图机制

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/520837/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球