Tensorflow和PyTorch的浅解

下文简称Tensorflow为TF,PyTorch为PT。TF出自Google之手(2015年),而PT是来自Facebook AI的一个python package(2016)。两者皆是基于Python的深度学习开发平台。其中,TF较早于PT出现,且是最广为使用的平台。然而,近年来PT大有赶超之势。本文浅谈TF和PT的异同。首先,PT是Torch的Python再开发版。Torch本是就是一个基于Lua语言的更早的平台,但考虑到Lua的偏门性,FAIR的研究人员将其移植到了python之上,有此得名Py + Torch。相比之下,TF更适合production因为它更稳定;PT更适合research因为它更自由(flexibility and speed)。PyTorch自身就是一个python package written in Python,但是同时支持如C或C++的API;而TF是用C++和CUDA写成的,通过python API来支持python coding。Fun fact,PT可以看做和Numpy是同样级别的python library,它们均是python package,都有一个C backend。相比之下,PT有更棒的GPU加速,而且PT跟适合搭建DNN。但是,仅用Numpy也可以实现基础的machine learning algorithms。从这个角度讲,PT和NP是python-oriented,而TF的初衷并不是针对python,而是提供了python API而已。Both TF and PT operate on tensors and view any models as a directed acyclic graph (DAG).

因为刚刚上手PyTorch,所以先来一小段PT的简介:

PT的两大核心特点:1. tensor computation with strong GPU acceleration(一个类似numpy的张量计算包);2. Building DNN on a tape-based autograd systems。

PT主要包含三大modules:1. Autograd module,自动求梯度进行back-propagation的机制;2. Optim Module,整合了所有的优化器;3. nn Module,搭建high-level的神经网络。

PT支持不同的back-end support:tensor backend TH for CPU and THC for GPU, NN backend THNN for CPU and THCUNN for GPU。

PT tensors:tensors are nothing but multidimensional arrays. Tensors in PT are similar to NP ndarrays, with the addition being tensors that can also be used on a GPU PT tensor与NP tensor的区别是PT tensor增加了GPU计算

 

1. Imperative(PT)& symbolic (TF) prgoraming:

Imperative与symbolic program的内涵有点类似解释性语言(Python)和编译性语言(C)。

所谓Imperative programing可以理解为是即编即run,无需等待,可以在程序之中写入类似for loop的操作或是on-the-fly地print中间变量(tensor)的值,and allows users to run and test part of the code in real time thus no need to wait for the entire code to be executed to check wether it works or not。而symbolic programing需要预先搭建一个computational graph一样的结构,在这个symbolic结构搭建的过程中并没有发生任何的计算。在搭建完成之后,基于这个symbolic graph实施compile(即tensorflow里的session.run())之后,才有真实的计算和值流入这个graph。

相比之下,symbolic programing更利于同样框架的复用,而imperative programing更直接,更易懂,编程更直观自由。

2. Dynamic computation graph(PT:Define-by-Run) & Static Computation Graph(TF:Define-then-run):

PT一边run一边搭建computation graph,run一行搭建一行或修改一行的network,TF是预先搭建好graph,之后再在这个搭好的graph上run。因为是预先设计的static graph,因此它只支持fixed-size networks如普通的feed forward或者CNN networks,这些网络不需要对网络结构进行动态调整。而对于RNN,当要在线调整cell的unroll次数,这就牵扯到了on-the-fly的for循环,那么这就用到了PT的imperative特性。总而言之,PT的dynamic属性让它可以支持变化的input output尺寸,而TF则需要padding来取齐 (举个例子,在做NLP的sentiment analysis时句子有长有短,那么TF就必须设定一个固定的input sequence长度为LSTM的unrollment次数,而短句子就必须zero padding to meet the length。PT则不用,可以用一个for loop over the length of each input来搞定)。相比之下,Static graph models跟快更memory efficient,更好地支持batching。对于TF而言,all communication between the graph and the outter world is via tf.Session obhect and tf.Placeholder which are tensors that will be substituted by external data at runtime.

3. Data Parallelism

Tensorflow和PyTorch的浅解_第1张图片

 

 

 

你可能感兴趣的:(Deep,Learning,机器学习)