00_PyTorch 0.4.0遷移指南以及代碼兼容
目錄- 一、概要
- 二、合并Tensor和Variable和類
- 2.1 Tensor中的type()改變了
- 2.2 什么時候autograd開始自動求導?
- 2.3 操作requires_grad標志
- 2.4 關于.data
- 三、現在一些操作回傳0維(標量)Tensors
- 3.1 積累損失
- 四、棄用volatile標簽
- 五、dtypes,devices和NumPy風格的創作功能
- 5.1 創建 Tensors
- 六、撰寫device-agnostic代碼
- 七、nn.Module中子模塊名稱,引數和緩沖區中的新邊界約束
- 7.1 代碼示例(將它們放在一起)
一、概要
Tensors并Variables已合并Tensors支持0維(標量)- 棄用
volatile標簽 dtypes,devices和NumPy風格的創作功能- 撰寫
device-agnostic代碼 nn.Module中子模塊名稱,引數和緩沖區中的新邊界約束
二、合并Tensor和Variable和類
torch.autograd.Variable和torch.Tensor現在類相同,確切地說,torch.Tensor能夠像Variable一樣自動求導; Variable繼續像以前一樣作業但回傳一個torch.Tensor型別的物件,意味著你在代碼中不再需要Variable包裝器,
2.1 Tensor中的type()改變了
type()不再反映張量的資料型別,使用isinstance()或x.type()替代:
>>> x = torch.DoubleTensor([1, 1, 1])
>>> print(type(x)) # was torch.DoubleTensor
"<class 'torch.Tensor'>"
>>> print(x.type()) # OK: 'torch.DoubleTensor'
'torch.DoubleTensor'
>>> print(isinstance(x, torch.DoubleTensor)) # OK: True
True
2.2 什么時候autograd開始自動求導?
equires_grad是autograd的核心標志,現在是Tensors上的一個屬性,讓我們看看在代碼中如何體現的,
autograd使用以前用于Variables的相同規則,當張量定義了requires_grad=True就可以自動求導了,例如,
>>> x = torch.ones(1) # create a tensor with requires_grad=False (default)
>>> x.requires_grad
False
>>> y = torch.ones(1) # another tensor with requires_grad=False
>>> z = x + y
>>> # both inputs have requires_grad=False. so does the output
>>> z.requires_grad
False
>>> # then autograd won't track this computation. let's verify!
>>> z.backward()
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
>>>
>>> # now create a tensor with requires_grad=True
>>> w = torch.ones(1, requires_grad=True)
>>> w.requires_grad
True
>>> # add to the previous result that has require_grad=False
>>> total = w + z
>>> # the total sum now requires grad!
>>> total.requires_grad
True
>>> # autograd can compute the gradients as well
>>> total.backward()
>>> w.grad
tensor([ 1.])
>>> # and no computation is wasted to compute gradients for x, y and z, which don't require grad
>>> z.grad == x.grad == y.grad == None
True
2.3 操作requires_grad標志
除了直接設定屬性之外,您可以使用my_tensor.requiresgrad(requires_grad=True)直接修改此標志,或者如上例所示,在創建時將其作為引數傳遞(默認為False),例如:
>>> existing_tensor.requires_grad_()
>>> existing_tensor.requires_grad
True
>>> my_tensor = torch.zeros(3, 4, requires_grad=True)
>>> my_tensor.requires_grad
True
2.4 關于.data
.data是從Variable中獲取Tensor的方法,合并后,呼叫y = x.data仍然具有類似的語意,因此y將是與x共享同的Tensor相資料,x與計算歷史無關,并具有requires_grad=False,
但是,.data在某些情況下可能不安全,x.data上的任何變化都不會被autograd跟蹤,并且x在向后傳遞中計算梯度將不正確,一種更安全的替代方法是使用x.detach(),它也回傳一個Tensor與requires_grad=False共享資料的資料,但是如果x需要反向傳播那就會使用autograd直接改變報告,
下面是一個.data和x.detach()(以及為什么我們建議detach一般使用)之間的區別的例子,
如果你使用Tensor.detach(),保證梯度計算是正確的,
>>> a = torch.tensor([1,2,3.], requires_grad = True)
>>> out = a.sigmoid()
>>> c = out.detach()
>>> c.zero_()
tensor([ 0., 0., 0.])
>>> out # modified by c.zero_() !!
tensor([ 0., 0., 0.])
>>> out.sum().backward() # Requires the original value of out, but that was overwritten by c.zero_()
RuntimeError: one of the variables needed for gradient computation has been modified by an
然而,使用Tensor.data可能是不安全的,并且當梯度計算需要張量但直接修改時可能容易導致不正確的梯度,
>>> a = torch.tensor([1,2,3.], requires_grad = True)
>>> out = a.sigmoid()
>>> c = out.data
>>> c.zero_()
tensor([ 0., 0., 0.])
>>> out # out was modified by c.zero_()
tensor([ 0., 0., 0.])
>>> out.sum().backward()
>>> a.grad # The result is very, very wrong because `out` changed!
tensor([ 0., 0., 0.])
三、現在一些操作回傳0維(標量)Tensors
以前,Tensor向量(1維張量)的索引回傳一個Python數字,但是Variable的索引向量回傳一個(1,)的向量!即tensor.sum()回傳一個Python數字,但variable.sum()會回傳一個大小為(1,)的向量,
幸運的是,此版本在PyTorch中引入了適當的標量(0維張量)支持!可以使用新torch.tensor函式來創建標量(稍后會對其進行更詳細的解釋;現在只需將它看作PyTorch中與numpy.array的等價物),現在你可以做這樣的事情:
>>> torch.tensor(3.1416) # create a scalar directly
tensor(3.1416)
>>> torch.tensor(3.1416).size() # scalar is 0-dimensional
torch.Size([])
>>> torch.tensor([3]).size() # compare to a vector of size 1
torch.Size([1])
>>>
>>> vector = torch.arange(2, 6) # this is a vector
>>> vector
tensor([ 2., 3., 4., 5.])
>>> vector.size()
torch.Size([4])
>>> vector[3] # indexing into a vector gives a scalar
tensor(5.)
>>> vector[3].item() # .item() gives the value as a Python number
5.0
>>> mysum = torch.tensor([2, 3]).sum()
>>> mysum
tensor(5)
>>> mysum.size()
torch.Size([])
3.1 積累損失
考慮到經常使用的total_loss += loss.data[0],0.4.0之前,loss是(1,)張量的Variable包裝器,但在0.4.0中loss現在是一個0尺寸標量,標量索引是沒有意義的(目前只提出一個警告,但在0.5.0中將會報錯),loss.item()用于從標量中獲取Python數字,
請注意,如果您在累積損失時未將其轉換為Python數字,則可能會發現程式中的記憶體使用量增加,這是因為上面運算式的右側曾經是一個Python浮點數,而現在它是一個0的張量,因此,總損失累積了張量和它們的歷史梯度,可能導致巨大的autograd圖形不必要的保存大量時間,
四、棄用volatile標簽
volatile標簽現在已被棄用,不起作用,以前,任何涉及Variablewith的計算volatile=True都不會被跟蹤autograd,這已經被換成了一套更加靈活的背景關系管理的,包括torch.no_grad(),torch.set_grad_enabled(grad_mode)及其他,
>>> x = torch.zeros(1, requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
>>>
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
... y = x * 2
>>> y.requires_grad
False
>>> torch.set_grad_enabled(True) # this can also be used as a function
>>> y = x * 2
>>> y.requires_grad
True
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
False
五、dtypes,devices和NumPy風格的創作功能
在以前的PyTorch版本中,我們用來指定的資料型別(例如float vs double),設備型別(cpu vs cuda)和layout(dense vs sparse)作為"張量型別",例如,torch.cuda.sparse.DoubleTensor是Tensor的double資料型別,在CUDA設備只能夠,以及配備COO稀疏張量layout,
在此版本中,我們引入torch.dtype,torch.device以及torch.layout類,允許通過NumPy的風格創建這些屬性的功能進行更好的管理,
具體內容參考:pytorch使用torch.dtype、torch.device和torch.layout管理資料型別屬性
5.1 創建 Tensors
創造一個方法Tensor,現在也可使用dtype,device,layout,和requires_grad選項來指定回傳所需的Tensor屬性,例如:
>>> device = torch.device("cuda:1")
>>> x = torch.randn(3, 3, dtype=torch.float64, device=device)
tensor([[-0.6344, 0.8562, -1.2758],
[ 0.8414, 1.7962, 1.0589],
[-0.1369, -1.0462, -0.4373]], dtype=torch.float64, device='cuda:1')
>>> x.requires_grad # default is False
False
>>> x = torch.zeros(3, requires_grad=True)
>>> x.requires_grad
True
具體可以參考:Pytorch0.4.0 中文檔案 Torch
六、撰寫device-agnostic代碼
以前版本的PyTorch撰寫device-agnostic代碼非常困難(即,在不修改代碼的情況下在CUDA可以使用或者只能使用CPU的設備上運行),
參考:Pytorch使用To方法撰寫代碼在不同設備(CUDA/CPU)上兼容(device-agnostic)
七、nn.Module中子模塊名稱,引數和緩沖區中的新邊界約束
name這是一個空字串或包含"."不再被允許進入module.add_module(name, value),module.add_parameter(name, value)或者module.add_buffer(name, value)因為這些名稱可能會在state_dict中導致資料丟失,如果您為包含這些名稱的模塊加載checkpoint,請在加載之前更新模塊定義并進行修補state_dict,
7.1 代碼示例(將它們放在一起)
為了方便對比0.4.0中整體推薦的變化的特征,我們來看一個0.3.1和0.4.0中常見代碼模式的簡單例子:
0.3.1(舊):
model = MyRNN()
if use_cuda:
model = model.cuda()
# train
total_loss = 0
for input, target in train_loader:
input, target = Variable(input), Variable(target)
hidden = Variable(torch.zeros(*h_shape)) # init hidden
if use_cuda:
input, target, hidden = input.cuda(), target.cuda(), hidden.cuda()
... # get loss and optimize
total_loss += loss.data[0]
# evaluate
for input, target in test_loader:
input = Variable(input, volatile=True)
if use_cuda:
...
...
0.4.0(新):
# torch.device object used throughout this script
device = torch.device("cuda" if use_cuda else "cpu")
model = MyRNN().to(device)
# train
total_loss = 0
for input, target in train_loader:
input, target = input.to(device), target.to(device)
hidden = input.new_zeros(*h_shape) # has the same device & dtype as `input`
... # get loss and optimize
total_loss += loss.item() # get Python number from 1-element Tensor
# evaluate
with torch.no_grad(): # operations inside don't track history
for input, target in test_loader:
...
感謝您的閱讀!有關更多詳細資訊,請參閱我們的檔案和發行說明,Pytorch 0.4.0中文檔案,
快樂的PyTorch-ing!
原創文章,轉載請注明 :PyTorch 0.4.0遷移指南以及代碼兼容 - pytorch中文網
原文出處: https://ptorch.com/news/190.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278758.html
標籤:其他
