id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st82068 | Found a solution myself:
There is as library called pytorch_scatter 102 that provides many different scatter operations (add, div, max, mean, min, mul, std). The scatter_max returns values and indices which allows to also directly use it for argmax operations. The operations also come with the according backwards paths.
7 |
st82069 | Solved by richard in post #4
x.nelement() == 0 works too. |
st82070 | Yes, it works
empty_tensor = Variable(torch.FloatTensor())
len(empty_tensor) ==0
True
,I mean if there are other ways like if pytorch keyword about it |
st82071 | Hmmm, if length is an issue then len(x)==0 wins.
Plus, it is pythonic, though not specifically pytorchic. |
st82072 | just beware that you can have a tensor with no elements and non-trivial size.
t = torch.zeros(size=(1,0))
t.nelement() # returns zero, empty in this sense
len(t.size()) # returns two, not empty in this sense!!
len(t) # returns one, not empty in this sense!!
t = torch.zeros(size=(0,1))
len(t) # returns zero for this one! |
st82073 | In the issue #24132 15 of PyTorch Github, what do boxed kernels and unboxed kernels mean? |
st82074 | Hi,
You can use the select method to get a single index on a given dimension and the narrow method to get a slice of a tensor on a given dimension |
st82075 | Thank you.
This is my way:
torch::Tensor score_text = score.slice(2,0,1,1).squeeze(2); |
st82076 | I have a batch x ndim tensor.
I want to add noise to each observation that pushes it either toward or away from the origin without flipping any of the signs.
Can anyone recommend a good approach? |
st82077 | I’m not sure I understand your use case properly.
If you would like to push a tensor to the origin (or away from it), you could subtract (or add) the same tensor multiplied by a factor in (0, 1) to it. The direction of this addition (or subtraction) will be towards to (away from) the origin.
However, I’m not sure, if that’s what you want. On the other hand you could add e.g. random Gaussian noise, but these changes won’t be applied with respect to the distance to the origin.
Could you clarify the use case a bit? |
st82078 | Thank you for your interest.
My specific use case is that I have an auto-encoder whose bottleneck embedding layer is hyperbolic. I’m adding noise to that embedding as a regularizer.
I have a specific kind of noise in mind which is very straight forward to describe. Grab a point, drag it either toward the middle of the disk or out toward the edge. Don’t change the angle or sign.
I’ve made progress on this problem in the two-dimensional case. I convert euclidian coordinates to polar coordinates, which give a radius and an angle. I then add/substract to the radius, and then convert back.
That was a very straightforward hack in 2d, but it may not have been the most efficient. I also don’t know how to generalize it to N-dimensions.
Here’s the functions I found for doing the conversion
github.com
PyAbel/PyAbel/blob/master/abel/tools/polar.py 5
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from scipy.ndimage import map_coordinates
from scipy.ndimage.interpolation import shift
from scipy.optimize import curve_fit, minimize
def reproject_image_into_polar(data, origin=None, Jacobian=False,
dr=1, dt=None):
"""
Reprojects a 2D numpy array (``data``) into a polar coordinate system.
"origin" is a tuple of (x0, y0) relative to the bottom-left image corner,
and defaults to the center of the image.
This file has been truncated. show original
def cart2polar(x, y):
r = torch.sqrt(x2 + y2).to(device)
theta = torch.atan2(y, x).to(device)
return r, theta
def polar2cart(r, theta):
y = r * torch.cos(theta).to(device) # θ referenced to vertical
x = r * torch.sin(theta).to(device)
return x, y
And here’s the code in the forward pass that applies the noise
if self.training:
new= cart2polar(x[:, 0], x[:, 1])
r=new[0]
angle=new[1]
distribution = torch.distributions.uniform.Uniform(torch.tensor([0.0]).to(device) , torch.tensor([1.0]).to(device) ) #reducing it to .5 noise
r_new = torch.sqrt( ( r - torch.t(distribution.sample(torch.Size([len(r)]))) ) **2).to(device)
converted = polar2cart(r_new,angle) #It returns x1 first and then x1
x_new=x.clone()
x_new[:,0]=converted[1] #these need to be inverted
x_new[:,1]=converted[0] |
st82079 | m = nn.ConvTranspose2d(1, 1, (2, 2), stride=(2, 2), padding=(1, 1), output_padding=(1,1))
output = m(input)
print(output)
tensor([[[[ 0.3960, 0.6212, 0.3960, 0.6212, 0.3960, 0.6212, 0.3960],
[-0.2565, 0.0108, -0.2565, 0.0108, -0.2565, 0.0108, -0.2565],
[ 0.3960, 0.6212, 0.3960, 0.6212, 0.3960, 0.6212, 0.3960],
[-0.2565, 0.0108, -0.2565, 0.0108, -0.2565, 0.0108, -0.2565],
[ 0.3960, 0.6212, 0.3960, 0.6212, 0.3960, 0.6212, 0.3960],
[-0.2565, 0.0108, -0.2565, 0.0108, -0.2565, 0.0108, -0.2565],
[ 0.3960, 0.6212, 0.3960, 0.6212, 0.3960, 0.6212, 0.3960]]]],
why output_padding not padding 0 to out?What number is pad?
How can I replace ConvTranspose2d(output_padding) with ConvTranspose2d(no output_padding)?I want to ConvTranspose2d with output_padding in MXNet ? |
st82080 | I have an NN output which has 3 neurons. These with a neuron control a program that outputs an integer in the range from 0 to target (say 45). For target, let’s say 70. I make MSELoss and get an error. And train the network. In this embodiment, NN is not trained. Have an understanding of why? |
st82081 | I am timing my backprop loop between epochs, and every epoch it gets slower and slower for the same sized minibatch. How can I debug this? I already ran a casual sweep over the code to check for tensors that are set outside of the training loop. I assume this is happening because the graph is not getting rebuilt from scratch each backprop loop. What is the rigorous way to debug this? |
st82082 | Has anyone experienced this issue?
python test/test_autograd.py -k test_deep_reentrant -v
test_deep_reentrant (main.TestAutograd) … Bus error: 10
Environment:
print(sys.version)
3.7.3 (default, Mar 27 2019, 16:54:48)
[Clang 4.0.1 (tags/RELEASE_401/final)]
platform.platform()
‘Darwin-18.7.0-x86_64-i386-64bit’
commit 60c4e74e49770ca7204b812006926ac0778d30df
Date: Fri Aug 30 20:57:45 2019 -0700
Build:
export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/…/"}
MACOSX_DEPLOYMENT_TARGET=10.9
CC=clang
CXX=clang++
USE_CUDA=0
USE_MKLDNN=0
python setup.py develop
Thanks! |
st82083 | Hi,
In my implementation, I need logsumexp to stabilize the computation. It works well in high dimension. But it seems like I still encounter numerical issues (nan) in 1-dimensional experiments.
However, I couldn’t find the source code for this function. How is it implemented? Thanks! |
st82084 | I am using torchvision.transforms.Lambda to apply noise to each input in my dataset:
torchvision.transforms.Lambda(lambda x: x + torch.rand(x.shape))
The problem is that each time a particular image is sampled, the noise that is added is different. I would like to apply the noise up front (not during training) so that every time I sample a particular image the noise is the same.
Thanks! |
st82085 | If you would like to apply the same random noise to the corresponding image tensor, you could initialize a noise tensor in your Dataset's __init__ function with the same length as the number of images, and add it to each tensor after the transformation.
class MyDataset(Dataset):
def __init__(self, image_paths, targets, transform=None):
self.image_paths = image_paths
self.targets = targets
self.transform = transform
self.noise = torch.randn(len(self.image_paths), 3, 224, 224)
def __getitem__(self, index):
x = Image.open(self.image_paths[index])
y = self.targets[index]
if transform is not None:
x = self.transform(x)
x = x + self.noise[index]
return x, y
def __len__(self):
return len(self.image_paths) |
st82086 | Thanks for the tip. Ended up going with:
class NoiseDataset(datasets.MNIST):
def __init__(self, *args, percent_noise=1, **kwargs):
super().__init__(*args, **kwargs)
self.percent_noise = percent_noise
self.noise = torch.randn(self.data.shape)
def __getitem__(self, index):
x, y = super().__getitem__(index)
noise = self.noise[index]
x = noise * self.percent_noise + x * (1 - self.percent_noise)
return x, y |
st82087 | That’s really an elegant approach to derive this class from the parent dataset.
Thanks for sharing! |
st82088 | I need to extract elements of a tensor (at present done using a boolean mask), do some operations on them, and replace in the original tensor. The basic operations look like this, where index is a boolean tensor.
new = out[index]
# Do some operations on new here
rt = out.clone()
rt[index] = new
Is there a faster way of doing this? In the test below, training time is roughly doubled (though depends on how many elements of index are True)
class test(nn.Module):
def __init__(self):
super(test, self).__init__()
self.a = nn.Parameter(torch.ones([100, 200]))
def forward(self, x, index=None):
out = torch.matmul(self.a, x)
if index is not None:
new = out[index]
rt = out.clone()
rt[index] = new
else:
rt = out
return rt
model = test()
opt = torch.optim.SGD(lr=0.01, params=model.parameters())
loss = torch.nn.MSELoss()
ixs = (torch.arange(100) > 50)
st = time.time()
for _ in range(1000):
x = torch.ones([200, 400]) + 10
target = torch.zeros([100, 400])
out = model(x, ixs)
l = loss(out, target)
l.backward()
opt.step()
model.zero_grad()
print(time.time() - st) |
st82089 | Hi,
I’m afraid this is expected.
Your original forward is only a matmul (the most optimized op we have) and you add 3 more operations.
You’ll get better performances if you use indices and index_select/index_copy or gather/scatter if the number of indices is small. |
st82090 | Thanks! Will have a go with index_select/index_copy and make a comparison. It’s the speed of extracting and re-inserting the elements of the tensor I’m interested in! Interesting that using indices is quicker with a small number. |
st82091 | Well the complexity of the operation with a mask is of the size of the Tensor. Because for every entry, it needs to check the mask value.
For the indices, it just reads the values at the given indices, so the complexity is the number of indices. |
st82092 | Makes sense - thanks a lot!
The other aspect I’m wondering about in the above e.g. is that if I change the line
ixs = (torch.arange(100) > 50)
to
ixs = (torch.arange(100) > 99)
I get back to the baseline speed. So it seems the slowdown is not the indexing directly, but due to a copy being made of the elements of the matmul output where the indices that are True, and operations on this copy (hence the difference depending on how many elements of ixs are True). Is that kind of correct?! |
st82093 | In your code sample, you actually clone the input, not only the element you index.
But anyway, the smaller the indexing, the faster it’s gonna be. |
st82094 | Hi,
My code wok fine on Colabolatory with CUDA.
Now I try to do on local environment.
My env is;
CUDA: 10.1
cuDNN: 7
and today I installed PyTorch follows instruction of pip3.
After the setting up I meet an error;
RuntimeError: expected device cpu and dtype Float but got device cuda:0 and dtype Float
Acutually my code set device(“cuda”), I want it run on NVIDIA GPU.
I can not understand reason why script try to run on CPU, while Colab has no error (indeed run on cpu).
In addition, I replaced operators with torch’s operators, but still I get the error.
Could you tell me reason and its solution? |
st82095 | Hi,
Thank you for your replying.
Error message is;
Traceback (most recent call last):
File "QNet.py", line 203, in <module>
out = model()
File "/home/syouyu/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 547, in __call__
result = self.forward(*input, **kwargs)
File "QNet.py", line 164, in forward
fw_prop(self)
File "QNet.py", line 70, in fw_prop
q_layer(self)
File "QNet.py", line 60, in q_layer
q_sel(self)
File "QNet.py", line 53, in q_sel
self.sel[index] = torch.sigmoid(torch.add(torch.mul(self.w_x[index], self.x[index]), torch.mul(self.w_h[index], self.h[index])))
RuntimeError: expected device cpu and dtype Float but got device cuda:0 and dtype Float
Tensors are defined as;
class Model(nn.Module):
def __init__(self):
self.w_x = [torch.randn((NUM_INPUT), requires_grad=True) for _ in range(NUM_HIDDEN)]
self.w_h = [torch.randn((NUM_INPUT), requires_grad=True) for _ in range(NUM_HIDDEN)]
self.sel = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
self.x = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
self.h = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)] |
st82096 | When you are converting your model with model.cuda(), the Tensor's you have will not be converted: only children Modules will be automatically converted.
You will have to manually specify the device of your tensors in the creation:
class Model(nn.Module):
def __init__(self, device):
super().__init__()
self.w_x = [torch.randn((NUM_INPUT), requires_grad=True, device=device) for _ in range(NUM_HIDDEN)]
self.w_h = [torch.randn((NUM_INPUT), requires_grad=True, device=device) for _ in range(NUM_HIDDEN)]
self.sel = [torch.zeros(NUM_INPUT, device=device) for _ in range(NUM_HIDDEN)]
self.x = [torch.zeros(NUM_INPUT, device=device) for _ in range(NUM_HIDDEN)]
self.h = [torch.zeros(NUM_INPUT, device=device) for _ in range(NUM_HIDDEN)]
so you pass it to your model as:
model = Model(device='cuda:0') |
st82097 | @spanev -san,
I do as follows;
device = device_("cuda" if cuda.is_available() else "cpu")
model = Model().to(device)
And the Model does not have argument of the device. |
st82098 | 111137:
device = device_(“cuda” if cuda.is_available() else “cpu”)
What is device_ here?
You cannot change the model __init__ and add a device argument? As done here:
spanev:
def init(self, device):
?
Also about the Colab you are running on, the default Tensor device might have been set with:
torch.set_default_tensor_type(torch.cuda.FloatTensor)
but I wouldn’t recommend relying on this. |
st82099 | spanev:
What is device_ here?
It is;
from torch import device as device_
And the Model does not have argument of the device.
I mean is when having the device as an argument, how using it in the init. |
st82100 | Since you are initializing the tensors with requires_grad=True, you should wrap them into nn.Parameter, so that they will be properly registered in the state_dict and will be automatically pushed to the device, if you call model.to(device).
Also, since you are storing these parameters in a list, use ParameterList 12, as a plain Python list won’t register the parameters properly.
This should work:
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.w_x = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.w_h = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.sel = nn.ParameterList([nn.Parameter(torch.zeros(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.x = nn.ParameterList([nn.Parameter(torch.zeros(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.h = nn.ParameterList([nn.Parameter(torch.zeros(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
model = Model()
model.cuda()
print(model.parameters()) |
st82101 | @ptrblck -san,
I updated code with your advices, and I got other error;
File "QNet.py", line 62, in q_sel
self.sel[index] = torch.sigmoid(torch.add(torch.mul(self.w_x[index], self.x[index]), torch.mul(self.w_h[index], self.h[index])))
RuntimeError: expected device cuda:0 and dtype Float but got device cpu and dtype Float
Does this mean that my setting on local PC is incorrect ? |
st82102 | I’m not sure, what went wrong, but try to check the device of all parameters after calling model.to('cuda'):
for name, param in model.named_parameters():
if param.device.type != 'cuda':
print('param {}, not on GPU'.format(name))
This should print, if a parameter is not on the GPU. |
st82103 | ptrblck:
This should print, if a parameter is not on the GPU.
Didn’t print parameters, so those are probably on GPU card.
Ah, simply
print(model.parameters())
also not worked. So, before the run the model, elaboration of function “q_sel” made the error, indeed. |
st82104 | 111137:
So, before the run the model, elaboration of function “q_sel” made the error, indeed.
I’m not sure, if I understand the sentence correctly, but is it working now? |
st82105 | Not work.
I use jupyter notebook. Running cell of class Model(), it calls the “q_sel” function of;
File "QNet.py", line 63, in q_sel
self.sel[index] = torch.sigmoid(self.w_x[index] * self.x[index] + self.w_h[index] * self.h[index])
Then makes the error. |
st82106 | If you initialize the model, this function is called?
Could you post a reproducible code snippet so that we can have a look? |
st82107 | Not reproducible;
#!/usr/bin/env python
# coding: utf-8
from torchvision import datasets, transforms, models
import torch
from torch import nn, optim, utils, device as device_, cuda
import numpy as np
# Architecture Hyper-Parameters
NUM_INPUT = 28
TIME_STEPS = 28
NUM_CLASS = 10
NUM_HIDDEN = 28
def q_sel (self):
for index in range(NUM_HIDDEN):
self.sel[index] = torch.sigmoid(self.w_x[index] * self.x[index] + self.w_h[index] * self.h[index])
def q_layer (self):
q_sel(self)
def fw_prop (self):
q_layer(self)
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
# Gate-Weight
self.w_x = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.w_h = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
# Gate-Selector
self.sel = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
# Input Vector
self.x = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
# Output Vector
self.h = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
def forward(self):
fw_prop(self)
model = Model()
model.cuda()
print(model.parameters())
for name, param in model.named_parameters():
if param.device.type != 'cuda':
print('param {}, not on GPU'.format(name))
output is
<generator object Module.parameters at 0x7fedc4fd9b48>
So properly works.
I identified where made the error with print() on original code.
Calling model() after model.train(), it also called function of
def q_sel (self):
for index in range(NUM_HIDDEN):
print("2")
self.sel[index] = torch.sigmoid(self.x[index] * self.w_x[index] + self.h[index] * self.w_h[index])
print("3")
After first print("2") getting error. So I think the code could not send data of self.x, self.w_x, self.h, and or self.w_h. |
st82108 | @ptrblck -san
I did it;
#!/usr/bin/env python
# coding: utf-8
from torchvision import datasets, transforms, models
import torch
from torch import nn, optim, utils, device as device_, cuda
import numpy as np
# Architecture Hyper-Parameters
NUM_INPUT = 28
TIME_STEPS = 28
NUM_CLASS = 10
NUM_HIDDEN = 28
BATCH_SIZE = 1024
EPOCH = 64
def one_hot_embedding (y, length):
out = torch.zeros(length)
out[y] = 1.0
def q_sel (self):
for index in range(NUM_HIDDEN):
self.sel[index] = torch.sigmoid(self.w_x[index] * self.x[index] + self.w_h[index] * self.h[index])
def q_layer (self):
q_sel(self)
def fw_prop (self):
q_layer(self)
dataset_train = datasets.MNIST(
'~/mnist',
train=True,
download=True,
transform=transforms.ToTensor())
dataloader_train = utils.data.DataLoader(dataset_train,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=4)
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
# Gate-Weight
self.w_x = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.w_h = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
# Gate-Selector
self.sel = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
# Input Vector
self.x = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
# Output Vector
self.h = [torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]
def forward(self):
fw_prop(self)
model = Model()
model.cuda()
print(model.parameters())
for name, param in model.named_parameters():
if param.device.type != 'cuda':
print('param {}, not on GPU'.format(name))
for epoch in range(EPOCH):
for x, t in dataloader_train:
y = one_hot_embedding(t, NUM_CLASS)
for time in range(TIME_STEPS):
model.x[0] = x[0][0][time]
model.h[0] = torch.zeros(NUM_INPUT)
model.zero_grad()
out = model()
makes error of;
File "test.py", line 24, in q_sel
self.sel[index] = torch.sigmoid(self.w_x[index] * self.x[index] + self.w_h[index] * self.h[index])
RuntimeError: expected device cuda:0 and dtype Float but got device cpu and dtype Float
So, lack of sending data makes the error, indeed. |
st82109 | sel, x and h are not wrapped in nn.Parameter and nn.ParameterList,
Have a look at my code snippet. |
st82110 | Code does;
model.x[0] = x[0][0][time]
model.h[0] = torch.zeros(NUM_INPUT)
self.sel , self.x , self.h are not parameters.
So, I think wrapping as parameter does not allow substitution.
It makes an error of;
in register_parameter
.format(torch.typename(param), name))
TypeError: cannot assign 'torch.FloatTensor' object to parameter '0' (torch.nn.Parameter or None required)
I triied to do;
self.sel = [torch.zeros(NUM_INPUT, device='cuda') for _ in range(NUM_HIDDEN)]
self.x = [torch.zeros(NUM_INPUT, device='cuda') for _ in range(NUM_HIDDEN)]
self.h = [torch.zeros(NUM_INPUT, device='cuda') for _ in range(NUM_HIDDEN)]
In training loop:
model.x[0] = torch.cuda.FloatTensor(x_)
model.h[0] = torch.cuda.FloatTensor(torch.zeros(NUM_INPUT))
Makes segmentation fault |
st82111 | Thanks for the information. I’ve missed that these tensors should not require gradients.
In that case, you could register them as buffers using:
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.w_x = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.w_h = nn.ParameterList([nn.Parameter(torch.randn(NUM_INPUT)) for _ in range(NUM_HIDDEN)])
self.register_buffer('sel', torch.stack([torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]))
self.register_buffer('x', torch.stack([torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)]))
self.register_buffer('h', torch.stack([torch.zeros(NUM_INPUT) for _ in range(NUM_HIDDEN)])) |
st82112 | I do it and makes;
model.x[0] = torch.cuda.FloatTensor(s)
Then segmentation fault is occurred on the line. |
st82113 | Hi,
I’ve just added a Maxpool1d into a CVAE, and the shape is changing from <x1,y1,z1> to <x2,y2> ie its changing from a 3D tensor to a 2D tensor, any ideas why this is?
Cheers,
Chaslie |
st82114 | Hi @chaslie
What is exactly the input shape and what are the arguments of MaxPool1d? |
st82115 | Hi Spanev,
the code line is
self.pool=nn.MaxPool1d(22,stride=1,padding=10,dilation=1)
The input shape is <2,128,66>
the output shape is <128,65>
the output shape is correct when i calculate, except it is now a 2D tensor and not 3D which gives:
RuntimeError: Expected 3-dimensional input for 3-dimensional weight 128 128, but got 2-dimensional input of size [128, 65] instead |
st82116 | Having adjustedf the maxpool line to:
self.pool=nn.MaxPool1d(22,stride=1,padding=10,dilation=1,return_indices=True)
and
def forward(self, data):
data,indices=self.pool(data)
return data, indices
Which is fed into a decoder using:
self.unpool=nn.MaxUnpool1d(22,stride=1,padding=10)
and
def forward(self, z2,indices):
z2=self.unpool(z2,indices, output_size=input.size())
I am now getting the error:
model(*x)
File "d:\Users\CHARLIE\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
TypeError: forward() missing 1 required positional argument: 'indices' |
st82117 | It might come from somewhere else in your model, since the input data shape and layer you give produces a [2, 128, 65] shaped output:
>>> pool=nn.MaxPool1d(22,stride=1,padding=10,dilation=1)
>>> t = torch.rand(2,128,66)
>>> pool(t).shape
torch.Size([2, 128, 65])
chaslie:
model(*x)
What is x here? |
st82118 | File “d:\xxxx\Anaconda3\lib\site-packages\torchsummary\torchsummary.py”, line 72, in summary
model(*x) |
st82119 | In the code for nn.Linear, initialisation occurs in the reset_parameters() method. This method calls init.kaiming_uniform_ (see below)
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
Looking at the kaiming_uniform_ function definition, by default it assumes a leaky relu activation, which affects one of the constants used in the initialisation distribution:
def kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu'):
r"""Fills the input `Tensor` with values according to the method
described in `Delving deep into rectifiers: Surpassing human-level
performance on ImageNet classification` - He, K. et al. (2015), using a
uniform distribution. The resulting tensor will have values sampled from
:math:`\mathcal{U}(-\text{bound}, \text{bound})` where
.. math::
\text{bound} = \sqrt{\frac{6}{(1 + a^2) \times \text{fan\_in}}}
Also known as He initialization.
Args:
tensor: an n-dimensional `torch.Tensor`
a: the negative slope of the rectifier used after this layer (0 for ReLU
by default)
mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'``
preserves the magnitude of the variance of the weights in the
forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the
backwards pass.
nonlinearity: the non-linear function (`nn.functional` name),
recommended to use only with ``'relu'`` or ``'leaky_relu'`` (default).
Examples:
>>> w = torch.empty(3, 5)
>>> nn.init.kaiming_uniform_(w, mode='fan_in', nonlinearity='relu')
"""
fan = _calculate_correct_fan(tensor, mode)
gain = calculate_gain(nonlinearity, a)
std = gain / math.sqrt(fan)
bound = math.sqrt(3.0) * std # Calculate uniform bounds from standard deviation
with torch.no_grad():
return tensor.uniform_(-bound, bound)
Looking in the calculate_gain function, we can confirm that the resulting gain is different for leaky relu vs other types of activations (including no activation):
def calculate_gain(nonlinearity, param=None):
r"""Return the recommended gain value for the given nonlinearity function.
The values are as follows:
================= ====================================================
nonlinearity gain
================= ====================================================
Linear / Identity :math:`1`
Conv{1,2,3}D :math:`1`
Sigmoid :math:`1`
Tanh :math:`\frac{5}{3}`
ReLU :math:`\sqrt{2}`
Leaky Relu :math:`\sqrt{\frac{2}{1 + \text{negative\_slope}^2}}`
================= ====================================================\
Args:
nonlinearity: the non-linear function (`nn.functional` name)
param: optional parameter for the non-linear function
Examples:
>>> gain = nn.init.calculate_gain('leaky_relu')
"""
Is this desired behaviour? Wouldn’t a more appropriate default activation be linear / identity? |
st82120 | The intent / original code doesn’t assume leaky relu, it does initialization according to the paper Efficient Backprop (Lecun et. al. 1998). It so happens that the initialization from that paper can also be implemented as a kaiming draw with leaky relu assumption.
The context is in the original github PR, but I guess it wouldn’t have hurt to write a github comment I guess, sorry for the misunderstanding. |
st82121 | I want to use LSTMCell so I can move them to gpu when I call model.to(). But the hidden state and cell state of LSTMCell had to be moved to the gpu for LSTMCell’s weights to be in the gpu. So I googled how I’m supposed to do it and found that I needed to use buffers with register_buffer(). But I don’t know how I’m supposed to save the output of LSTMCell to the buffers I initialized.
Here’s what I tried.
class Model(nn.Module):
def __init__(self, ...):
...
self.lstm = nn.LSTMCell(256, 256)
self.register_buffer('hidden', torch.zeros(batch, 256))
self.register_buffer('cell', torch.zeros(batch, 256))
...
def clear_lstm(self):
# update buffers to torch.zeros(batch, 256)
self.register_buffer('hidden', torch.zeros(batch, 256))
self.register_buffer('cell', torch.zeros(batch, 256))
pass
def forward(self, input):
...
self.hidden, self.cell = self.lstm(input, (self.hidden, self.cell))
...
I tried it without calling model.clear_lstm() before running and it worked, but after 3 runs, I ran out of memory(when I called .cuda() on each state, this didn’t happened). Running the model after calling model.clear_lstm() the buffers and LSTMCell wasn’t in gpu so I got an error:
RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'mat2' |
st82122 | Maybe a little stupid… Suppose that I have a neural network and the last layer is sigmoid. Pytorch will give the 0.5 as the initial value. So how can I initialize the output to 0.1? Is it correct to just subtract 0.4 at the forward process? Will that have a negative effect on the following training? Thanks! |
st82123 | The initial output depends on the input and parameter stats.
Usually you won’t get a perfect 0.5, but the mean value of your output might be approx. 0.5.
You could try to change the initialization of (some) layers and try to push the initial output downwards. |
st82124 | Thanks for your reply! But that is still hard to get the exact value(0.1) I want right? And if I just want the output to have the mean of 0.1, is it correct to just subtract 0.4 in the forward process? Because that’s much easier. |
st82125 | Subtracting a constant from your input won’t help much, as e.g. a relu might kill it after the first layer.
Maybe you could change the bias of the last linear layer to create a specific offset, but I doubt you will be able to create exactly 0.1 without zeroing the weights.
May I ask what your use case is, that you need a specific initial value? |
st82126 | I’m doing the reinforcement learning. The output of the agent is the probability. And the reward of the environment can only have a obvious change when the output is under 0.2. |
st82127 | Hi,
I test LSTM with a 2-category dataset with each dataset 800 data, I trained 100 epochs and try to make the model overfit and I expect to see a 100% accuracy for the training data prediction. However I failed and LSTM learn nothing, the taining accuracy is always 50% and the loss isn’t decreasing at all.
(When I try with each dataset 80k data with the same model, LSTM learn something and the prediction is around 70%.)
Anyone can tell me why? Thank you! |
st82128 | I tried the pytorch from conda built with CUDA 9 and 10, from pip built with CUDA9 and pytorch built from source within conda environment on training the MNIST: https://github.com/pytorch/examples/tree/master/mnist 2
The training time for the pip version with CUDA9 was around 71 seconds, for the conda version with CUDA 9 was around 90 seconds and for the conda version with CUDA 10 for the one built from source was around 118 seconds. Will Pytorch release the pytorch 1.2.0 built with CUDA 10 on pip? Or is there a way to build pytorch from source without conda?
The environment:
GPU: 1080Ti
Driver: 430.4
python version: 3.6.8
The torch.backends.cudnn.enabled is True.
Conda is installed with miniconda
Pip version of pytorch is installed in a virtual environment created by virtualenv |
st82129 | Hi,
You can install pytorch without conda from source (I never did it with conda actually).
For best performances, make sure you have the latest cuda and cudnn installed and OpenBLAS if you’re going to do some CPU stuff.
Thinking about it, the difference could come from a different cudnn version bundled in pip and in your conda install. |
st82130 | Hi,
Thank you for the answer. Could you tell me how you installed magma and let the setup.py find it? I tried to put the content from magma-cuda100 on anaconda cloud to the corresponding lib and include folders of the python folder, but in vain.
The cudnn and cuda version in my pip and conda install are the same: cudnn 7602 and cuda 10.0.130. |
st82131 | For magma, the way I did it was by installing it from source at the default location. Then it is found by default.
With the same cudnn versions, I’m not sure why you see that difference though… |
st82132 | As your timing differences are in the range of values I just measured to verify a fix of https://github.com/pytorch/pytorch/issues/25010 17 , you might want to try setting pin_memory=False in the main.py and see if that improves things for your slow cases…
My timings running the mnist train for the default 10 epochs. +/- 1 second is in the noise, there is obviously a big issue in 1.2 (and I see it in 1.1). I don’t see it in 1.0. Interestingly there is a diff btw 1.0 and 1.2 as 57 vs 63-64 is not in the measurement noise. I don’t have numbers across different cuda versions or pip vs conda though.
PyTorch 1.2 Conda, Python 3.7.3, Cuda 10.0.130, CUDNN 7.6.2
pin_memory=True, num_workers=1, no fix applied: 131.03s
pin_memory=True, num_workers=1, fix applied: 63.5s
pin_memory=False, num_workers=1: 63.25s
pin_memory=True, num_workers=0, no fix applied: 66.70s
pin_memory=True, num_workers=0, fix applied: 64.42s
pin_memory=False, num_workers=0: 64.03s
PyTorch 1.0, Conda, Python 3.6.8, Cuda 10.0.130, CUDNN 7.4.1
pin_memory=True, num_workers=1: 57.83
pin_memory=False, num_workers=1: 57.48
pin_memory=True, num_workers=0: 57.32
pin_memory=False, num_workers=0: 56.95 |
st82133 | Thank you very much! This is really the answer to the difference! After setting pin_memory=False, the performance of PyTorch 1.2 with CUDA 9 and of the one with CUDA 10 were the same. I didn’t test 1.0 and that’s really interesting to see 1.0 is even faster. |
st82134 | I’m trying to get a hessian vector product, but the following codes from DARTS 11 model don’t work as expected while self.named_parameters() is iterating over pairs n,p.
the error is: RuntimeError: One of the differentiated Tensors does not require grad
How can I fix this error? Thank you in advance.
def _hessian_vector_product(self, vector, input, target, r=1e-2):
R = r / _concat(vector).norm()
for p, v in zip(self.model.parameters(), vector):
p.data.add_(R, v)
loss = self.model._loss(input, target)
grads_p = torch.autograd.grad(loss, self.model.arch_parameters())
for p, v in zip(self.model.parameters(), vector):
p.data.sub_(2*R, v)
loss = self.model._loss(input, target)
grads_n = torch.autograd.grad(loss, self.model.arch_parameters())
for p, v in zip(self.model.parameters(), vector):
p.data.add_(R, v)
return [(x-y).div_(2*R) for x, y in zip(grads_p, grads_n)] |
st82135 | Hi,
This comes from the fact that you call autograd.grad on something that does not require gradient.
You should check where that happens and track down why this Tensor does not require gradients if it should. |
st82136 | Hello,
I am running PyTorch 1.2.0 with Conda on a remote Linux machine, but I built PyTorch from source using the CUDA toolkit 9.1. I checked whether the GPU is available with torch.cuda.is_available() and it is.
Using the Conda pre-built PyTorch was not a option for me, as the GPU drivers on the remote machine are too old for the CUDA toolkit 9.2 or 10, for which PyTorch binaries are provided.
I have a BxNxM tensor t on GPU, with B around 100000. I call torch.svd(t) and the GPU is idle, while the CPU starts running at 100% and more. At the end of the computation, the resulting decomposition is on GPU. In addition, trying to run on GPU is far slower than on CPU, basically unusable.
The weird thing is that, before to call torch.svd(t), I do computations on the GPU without any issue. It seems that the SVD computation is moved to the CPU and then the results moved back to the GPU.
My final goal is to compute the nuclear norm of each NxM matrix in my BxNxM tensor, therefore I tried to use also torch.norm(t, p='nuc', dim=(1, 2)), but the same scenario described above takes place.
Any guess? Thanks. |
st82137 | Hi,
Nothing within pytorch will move the data between CPU/GPU automatically. So the computations are definitely not done on the CPU.
I am not sure though that the batched version of svd exists. It may be doing a for-loop over the batch under the hood and call svd on each submatrix. If your NxM matrices are small, then you would see a very high cpu usage due to the launching of the kernels for each matrix while the GPU will stay almost idle as it has almost nothing to do.
Unfortunately, this is expected behavior for the GPU: unless you have large parallelizable operations, it will be less efficient than the CPU |
st82138 | I have an LSTM I am having it return one-hot vectors. I just use the vocabulary size. But now its randomly generating SOS tokens and PADD tokens when I don’t want it (like in the middle of a sentence or something like that).
How are LSTM models fixed to avoid this?
Note that just removing them from the indices list causes the problem that now the first token I pass my LSTM cannot be SOS
https://www.quora.com/unanswered/How-do-I-avoid-RNNs-LSTMS-from-producing-nonesense-tokens-like-SOS-and-PADD
Deep Learning Course Forums – 30 Aug 19
How to avoid RNNs/LSTMS from producing none-sense tokens like SOS and PADD?
I have an LSTM I am having it return one-hot vectors. I just use the vocabulary size. But now its randomly generating SOS tokens and PADD tokens when I don’t want it (like in the middle of a sentence or something like that). How are LSTM models... |
st82139 | Hi pinocchio,
That sounds like your LSTM may not be trained well. You may want to run your training longer to let LSTM learn how to make better sequences.
Another thing you could do if perform beam search in your sequence generation. This would enable you to explore what the sequence would look like if you feel the SOS/PAD token has popped up unnaturally. |
st82140 | Oh ok. So its normal to allow the network to output random SOS and PADD tokens? It just feels strange to me to leave them in the vocabulary, knowing that they are non-sense! |
st82141 | If it outputs SOS is the network usually just punished with the Cross Entropy loss? |
st82142 | I’m getting started with PyTorch and following the 60 minute Blitz tutorial on neural networks 6.
When defining a new Conv2d layer, one passes (input_channels, output_channels, kernel_size). But when accessing the layer’s parameters by calling .parameters(), the result is [output_channels, input_channels, kernel_dimensions]. What is the rationale behind putting the number of output channels first in the latter case? I found this to be very confusing. |
st82143 | This is the shape of the Tensor that represents the weights. You can think of the Conv2d operation as matrix multiplication (simplified):
(m x n) . (n x k) => (m x k)
replace m by output_channels, n by input_channels and k by n, and why output_channels is the first dim in the params should make sense to you. |
st82144 | Thank you for the quick response. Let’s take a look at a concrete example: I have an input tensor of shape (1,1,32,32), and a convolutional layer with weights of shape (6,1,3,3) as per .parameters(). By taking a look at the corresponding one-layer neural network I see that its output has shape (1,6,30,30). Ignoring image-dimensions and kernel-dimension, according to your heuristic one should get:
(6 x 1) . (1 x 1) => (6 x 1), but by looking at the output we can see that this is not the case, and instead the dimensions are interchanged. This is very unintuitive and confuses me. |
st82145 | Let us ignore the batch size for a moment (which is not part of the weight shape). Let us take something else than 1 for in the input_channel, 2. You have (2,32,32), you want (6,30,30). Omitting the data dimensions, what happens is: (6 x 2) . (2 x 1) => (6 x 1) . Note that the final 1 dim has been appended in the input shape, so you can remove it in the output shape and you end up with (6). |
st82146 | But by that line of reasoning, couldn’t we just as well do the following:
Again, I have (2,32,32) and want (6,30,30). I omit the data dimensions, append 1 in front and have (1 x 2) . (2 x 6) => (1 x 6). Again, I remove 1 and end up with (6). In this way we would’ve kept the order of input-dimension first, output-dimension second for the kernel/layer-weights, identical to when you actually define a layer. Why do it the other way around? |
st82147 | I have two datasets each of 142.000 images, one for training and one for validation. What I have implemented is that it goes through the train data set (batchsize 11) and trains.
But what I now want to do is the following:
train on the first images 11 images of the train set
validate the model on the first 11 images from the validation set
then train on the second 11 images of the train set
then validate the model on the second 11 images from the validation set
etc.
training_data_loader = DataLoader(dataset=train_set, num_workers=4, batch_size=11)
val_data_loader = DataLoader(dataset=val_set, num_workers=4, batch_size=11)
Here is my trainings code. Here I enumerate over the training_data_loader. Is there an efficient way to get the corresponding batch from the val_data_loader?
I tried a for loop that iterates through the val_data_loader and gets me the correct batch, but that’s too time consuming. I have to directly access the correct batch from the val_data_loader. I tried it with the function getitem, but I didn’t found a solution that worked.
for iteration, batch in enumerate(training_data_loader, 0):
input_train, target_train = Variable(batch[0]), Variable(batch[1])
if cuda:
input_train = input_train.cuda()
target_train = target_train.cuda()
optimizer.zero_grad()
output_model_train = model(input_train)
loss = criterion(output_model_train, target_train)
loss.backward()
optimizer.step() |
st82148 | Solved by ptrblck in post #3
If your Datasets have the same sizes, which seems to be the case, you could just iterate both DataLoaders in the for loop.
Note that the indices for each loader might be different if you use shuffling.
train_dataset = TensorDataset(torch.randn(100, 3, 24, 24))
val_dataset = TensorDataset(torch.ran… |
st82149 | First of all: Do you really need this? Usually The validation is done after each epoch (epoch = whole iteration over dataset) on the whole validation dataset.
if you really want to do it the way you did it you could define a Dataset 4 which handles train and validation data. If you do this you could use one dataloader and would get batches of always the same indices in train and validation set.
NOTE: This could lead to problems if the datasets have different sizes or you could validate the same images multiple times if you use shuffle=True (as usually done during training) |
st82150 | If your Datasets have the same sizes, which seems to be the case, you could just iterate both DataLoaders in the for loop.
Note that the indices for each loader might be different if you use shuffling.
train_dataset = TensorDataset(torch.randn(100, 3, 24, 24))
val_dataset = TensorDataset(torch.randn(100, 3, 24, 24))
train_loader = DataLoader(train_dataset, batch_size=11, shuffle=False)
val_loader = DataLoader(val_dataset, batch_size=11, shuffle=False)
for batch_idx, (train_data, val_data) in enumerate(zip(train_loader, val_loader)):
print('Batch idx {}\nTrain data shape {}\nVal data shape {}'.format(
batch_idx, train_data[0].shape, val_data[0].shape)) |
st82151 | Yes, in the paper I’m implementing they calculate the loss after each iteration in the data set. If I would do it each epoch it would take too long.
The train and validation datasets have the same size. Thanks for the tipp with shuffle. |
st82152 | Sorry to revive this old thread, but what is the solution if the Datasets don’t have the same size?
Currently I’m using this approach:
for epoch in range(epochs):
val_iter = itertools.cycle(validation_dataset_loader)
for i_batch, data in enumerate(training_dataset_loader, 0):
model.train()
#training happens here
model.eval()
val_sample = next(val_iter)
#evaluate performance on validation data
However I’m not sure if using the iterator here for the validation dataset is the best option, compared to the ‘enumerator’ approach, especially because the validation dataset is shuffled even when I explicitly set ‘shuffle=False’ when creating the validation DataLoader.
Thanks! |
st82153 | This approach seems to be valid for your use case.
The shuffling should not be changed, if you wrap the DataLoader into cycle:
class MyDataset(Dataset):
def __init__(self):
self.data = torch.arange(100).view(100, 1)
def __getitem__(self, index):
x = self.data[index]
return x
def __len__(self):
return len(self.data)
dataset = MyDataset()
loader = DataLoader(
dataset,
batch_size=5,
shuffle=False
)
my_iter = itertools.cycle(loader)
for _ in range(100):
x = next(my_iter)
print(x) |
st82154 | I was going through the optimizers available in Pytorch and I found that Sparse Adam optimizer doesn’t include weight decay. Is there a vital piece of theory I’m missing here or is it possible to implement this? |
st82155 | is VISME better then TensorBoard X ? for feature visualization and interpretability?
I am very intressed with a good weights and bias visibility
Thank you |
st82156 | I am following this tutorial: https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html 24
it’s quite nicely done, however I do not understand/see where you can know the expected image input size for the small network they have defined. They say that the images must be of size 32x32.
I know there is a formula (given in stanford CS231n 5 ) that states that ((N-K)/strideLen) +1 = , where N is the (padded) input size and K is the 2D convolution kernel size (e.g. 3x3).
But that does not seem to help me deduce what I want.
How can I know the expect input size ? I would be happy if someone whats to go in more details for the example of this simple PyTorch conv nn.
(Please note that for sizes significanlty different that 32x32 the net outputs an error message. Also, I don’t understand why it accepts inputs like 30x30 and 31x31, e.g. this is accepted:
input = torch.randn(1, 1, 31, 31)
out = net(input)
print(out)
The code is:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
It is not explained where from the shape (16 * 6 * 6, 120) comes from, for the linear layers, e.g. why 120 ? |
st82157 | Based on the description in CS231n, we know, that a conv layer with a kernel size of 3 and no padding will reduce the spatial size by ones pixel on each side.
Max pooling with a kernel size and stride of 2 will halve the spatial size.
Let’s have a look at the model and split the layers to calculate the shape based on these assumptions.
Have a look at the comments to see the output shape:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# assuming input is [N, 1, 32, 32]
x = F.relu(self.conv1(x)) # outputs [N, 6, 30, 30]
x = F.max_pool2d(x, (2, 2)) # outputs [N, 6, 15, 15]
x = F.relu(self.conv2(x)) # outputs [N, 16, 13, 13]
x = F.max_pool2d(x, 2) # outputs [N, 16, 6, 6]
x = x.view(-1, self.num_flat_features(x)) # flattens x to [N, 16*6*6]
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
Machupicchu:
Also, I don’t understand why it accepts inputs like 30x30 and 31x31
For an input of 31x31 and 30x30, we’ll get the following shapes:
# For x = [N, 1, 31, 31]:
[N, 6, 29, 29]
[N, 6, 14, 14]
[N, 16, 12, 12]
[N, 16, 6, 6 ]
# For x = [N, 1, 30, 30]:
[N, 6, 28, 28]
[N, 6, 14, 14]
[N, 16, 12, 12]
[N, 16, 6, 6 ]
So we got lucky, that the final result is the same.
As you can see, the reason for the equal output shapes is that the pooling layer uses floor for odd input shapes as described in the docs 4.
You can change it by setting ceil_mode=True, if necessary. |
st82158 | Great answer, thanks!
May I just also ask :
net = Net()
input = torch.randn(1, 1, 32, 32)
out = net(input)
Why is the method forward() not explicitely called? I mean how does just calling net(output) calls forward() ? (which is what happens as far as I understand)
By the way I dont understand what this line means:
super(Net, self).__init__()
I can imagine super() is calling the constructor of a parent class but …? |
st82159 | Machupicchu:
I mean how does just calling net(output) calls forward() ? (which is what happens as far as I understand)
Yes, you are right. If you directly call the nn.Module, its internal __call__ 2 method will be called, which makes sure to call hooks etc. and finally calls the forward method.
You should stick to this approach and not call model.forward manually.
Machupicchu:
I can imagine super() is calling the constructor of a parent class but …?
That’s again right. This call initializes the parent class as seen here 9 which then initializes all necessary dicts etc. for the parameters, buffers, … |
st82160 | Is that possible to load one specific layer of the model from the pretrained checkpoint? |
st82161 | Solved by ptrblck in post #2
If you just want to load a single layer, this code should work fine:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 10)
self.fc2 = nn.Linear(20, 20)
self.act = nn.ReLU()
def forward(self, x):
… |
st82162 | If you just want to load a single layer, this code should work fine:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 10)
self.fc2 = nn.Linear(20, 20)
self.act = nn.ReLU()
def forward(self, x):
x = self.act(self.fc1(x))
x = self.fc2(x)
return x
model = MyModel()
torch.save(model.state_dict(), 'tmp.pth')
state_dict = torch.load('tmp.pth')
model = MyModel()
with torch.no_grad():
model.fc1.weight.copy_(state_dict['fc1.weight'])
model.fc1.bias.copy_(state_dict['fc1.bias']) |
st82163 | I have one other question. I am using this method to load the layers. I see two weird things.
One is that loading one weight vs loading 8 weights don’t have much difference in terms of processing time. The second thing is that by changing the batch size, I see different computation time on loading parameters which should not be related. Do you have any idea on these issues? |
st82164 | Here is the psudue code of what I do:
Let’s say I am loading only three layers of the network and each has two sublayers called l1 and l2:
for i in range (3):
self.layer[i]…l1.weight.copy_(state_dict[“fc_{}.l1.weight”.format(i)], non_blocking=True)
self.layer[i].l2.weight.copy_(state_dict[“fc_{}.l2.weight”.format(i)], non_blocking=True)
This should not be related to batch size, but with different batch sizes, I get different timing. I use time.time from python time package to calculate the timing. Also, I am copying from cpu to gpu (my state_dict is on cpu and my model is on gpu). |
st82165 | Where is the batch size used in your code?
As you said, the batch size should be unrelated to the copying of parameters.
Since you are using non_blocking=True, make sure to call torch.cuda.synchronize() before starting and stopping the timer to get valid results. |
st82166 | Sorry for late response. Problem was cuda synchronization which was showing the wrong timing. It is solved by adding torch.cuda.synchronizae() |
st82167 | I am trying to plot a graph using tensorboard in pytorch and I use this after I create a model:
input_tensor = torch.Tensor(1,1,28,28)
if args.cuda:
input_tensor = input_tensor.cuda()
res = model(Variable(input_tensor), requires_grad=True))
tb.add_graph(model, lastVar=res)
but I get this error :
File “/usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py”, line 85, in forward
raise NotImplementedError
NotImplementedError
Thank you |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.