id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st102500 | As far as I understand this function 23 applies one feature map to every image in mini batch ? How can I apply, for example, 5 feature maps for one image, with feature maps having their own sets of shared weights and biases ? |
st102501 | Solved by rasbt in post #2
It’s just a regular convolution function (i.e., the default convolution operation that is used in typical convnets on 2d images). So, yes, you will use one kernel to generate the feature maps for every image in a mini batch. Basically, you will get one feature map per kernel. Hence, if you want 5 fe… |
st102502 | It’s just a regular convolution function (i.e., the default convolution operation that is used in typical convnets on 2d images). So, yes, you will use one kernel to generate the feature maps for every image in a mini batch. Basically, you will get one feature map per kernel. Hence, if you want 5 feature maps for one image, you need 5 kernels. Here’s an illustration:
Unknown.png825×413 43 KB
If you look at the function definition of the function:
torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) → Tensor
the kernels are called weight here and have the dimensions
Hence, you can simply provide a tensor with 5 out_channels |
st102503 | Hi.
I have a Network which should do the following task.
It gets an Images as Input. Now it should give me 2 Outputs.The first output is the cords where the mouse should move, the second output ist if it should click or not. First i thougth it could be overfitting. But through the fact that there is far more “click” (1) as “no click” (0) values I am wondering why it still always puts out 0.
My code:
import torch
import torchvision
import torchvision.transforms as transforms
import os
from PIL import Image
from CustomDataset import CustomMouseDataset,Rescale
def load_data():
# transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
#
# #Load Recoreded Data
# with h5py.File('data/video_data_22_7_2018_17_46','r') as data:
# video = data['video'][()]
# mouse = data['mouse'][()]
# video = video[:50]
# mouse = mouse[:50]
transform = transforms.Compose([transforms.ToTensor()])
train_data = CustomMouseDataset('data/video_data_22_7_2018_17_46',transform)
train_loader = torch.utils.data.DataLoader(train_data,batch_size=10,shuffle=True)
return train_loader
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 3, 1, 1)
self.pool1 = nn.MaxPool2d(2)
self.fc1 = nn.Linear(6*16*16, 20)
self.fc2a = nn.Linear(20, 2) # Regression
self.fc2b = nn.Linear(20, 1) # Classification
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x1 = self.fc2a(x)
x2 = F.log_softmax(self.fc2b(x), dim=1)
return x1, x2
def main():
pass
if __name__ == "__main__":
net = Net()
train_data = load_data()
import torch.optim as optim
criterion = nn.MSELoss()
criterion2 = nn.NLLLoss()
optimizer = optim.SGD(net.parameters(), lr = 0.001, momentum = 0.9)
#Train the Network
for epoch in range(10):
running_loss = 0.0
for i,data in enumerate(train_data,0):
inputs = data['frame']
labels = data['mouse']
target_1 = labels[:,:2]
target_2 = labels[:,2].unsqueeze(1)
# print(type(target_2))
# print(target_2.shape)
#Zero gradients Parameter
optimizer.zero_grad()
#forward + backward +optimize
output1,output2 = net(inputs)
loss1 = criterion(output1,target_1)/2000
loss2 = criterion(output2,target_2)
loss = loss1 + loss2
loss.backward()
optimizer.step()
running_loss = loss
if i % 300 == 0: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 5))
print(output1,output2)
running_loss = 0.0
try:
torch.save(net.state_dict(),'Model/model_save')
except:
os.mkdir("Model")
torch.save(net.state_dict(),'Model/model_save')
print('Finished Training')
Example Output:
tensor([[ 500.9624, 829.2684],
[ 442.0272, 770.7896],
[ 534.6215, 858.7812],
[ 465.2378, 793.0269],
[ 516.5006, 844.0679],
[ 512.5015, 837.9688],
[ 469.4029, 797.4636],
[ 462.6033, 787.3254],
[ 453.6012, 784.0760],
[ 503.6086, 833.6633]]) tensor([[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.],
[ 0.]]) |
st102504 | Your classification path has just one output, i.e. one class.
If you use F.log_softmax(x, dim=1) on it, it will “normalize” your single prediction to be always 0.
Change it to self.fc2d = nn.Linear(20, 2) for a two-class classification as suggested here 110.
Alternatively, you could use nn.BCELoss with a single output and F.sigmoid. |
st102505 | Is there a page or way how to learn what kind of Loss Function/optimizer or Activation Function i have to use?
I used different tutorials but they didnt explained this point |
st102506 | You can find the different loss functions in the docs 32.
I assume you’ve already found the PyTorch tutorials 16 and would like to get started creating your own models.
There are a lot of good resources to learn more, e.g. Stanford’s CS231n for Visual Recognition 10 (with free Lecture videos), fast.ai’s course 6 (they use a high-level wrapper built on top of PyTorch) or Andrew NG’s coursera course 9.
For the beginning you could stick to the following (this is my biased opinion and the recommendations might not be the best for your use case!):
For regression, try nn.MSELoss() and no non-linearity for your model output. Also normalizing the target to [0, 1] or [-1, 1] might help.
For classification use F.log_softmax + nn.NLLLoss or no non-linearity + nn.CrossEntropyLoss.
Try optim.Adam as the default optimizer.
Try nn.ReLU as your default non-linearity between layers.
Once your models converge you can tweak your code in a fancy way and e.g. use skip connections, cyclic learning rates etc. The deeplearningbook 12 is also a great resource. |
st102507 | One last question i have. If i now add New Layer to the Network. How can i calculated the input of the first Linear Layer? |
st102508 | Have a look at the output formula for nn.Conv2d and nn.MaxPool2d.
E.g. for a kernel_size=3 you will “lose” 2 pixel in height and width if you don’t pad. Adding padding=1 will keep the same shape.
MaxPool2d with a kernel_size=2 and stride=2 will reduce the spatial dimensions by 2.
These are just common values for these layers and you can design your model as you wish.
For the last layer you would have to multiply the channels by the height and width.
In your example you have 6 channels and a spatial size of 16x16. |
st102509 | super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 3, 1, 1)
self.conv2 = nn.Conv2d(6,12,3,1,1)
self.pool1 = nn.MaxPool2d(2)
self.fc1 = nn.Linear(12*32*32, 20)
self.fc2a = nn.Linear(20, 2) # Regression
self.fc2b = nn.Linear(20, 1) # Classification
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x = self.pool1(x)
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x1 = self.fc2a(x)
#x2 = F.log_softmax(self.fc2b(x), dim=1)
x2 = F.sigmoid(self.fc2b(x))
return x1, x2
With the Calculation i get always 32x32 so whats wrong in there? |
st102510 | Since you are pooling twice, the spatial dimensions will be 32/2/2=8. Your linear layer should thus take 12*8*8 input features.
If you don’t want to calculate it, you could also print the shape of your tensor before the view operation and just use this sizes. |
st102511 | I cannot solve the following mystery for hours:
class Convolution(nn.Module):
def __init__(self, args):
super(Convolution, self).__init__()
self.windows = [1,2,3,4,5]
self.window_convolutions = \
nn.ModuleList( [nn.Conv1d(args.cov_dim, args.mem_dim, i) for i in self.windows ])
def forward(self, input, args):
for window in self.windows:
print("input shape", input.shape)
print("params ", args.cov_dim, args.mem_dim, window)
input = input.view(1, input.size()[0], input.size()[1]).transpose(1, 2)
print("input shape", input.shape)
conv_model = self.window_convolutions[window]
convolved = conv_model(input)[0].transpose(0, 1)
print("convolved shape ", convolved.shape)
Gives the following output:
input shape torch.Size([97, 150])
params 150 150 1
input after view torch.Size([1, 150, 97])
convolved shape torch.Size([96, 150])
Notice that convolved shape is one less on zero dim. Why?
Some mystery for me… |
st102512 | You are dropping one dimension, because you are indexing the batch dimension in this line:
convolved = conv_model(input)[0].transpose(0, 1) |
st102513 | That is not the case. I removed [0].transpose(0,1)
so now I have only
convolved = conv_model(input)
and my output is
input shape torch.Size([171, 150])
params 150 150 1
input after view torch.Size([1, 150, 171])
convolved shape torch.Size([1, 150, 170])
Any other ideas what it might be? |
st102514 | output of convolution for stride=1 is input - kernel_size + 1. This is a valid convolution, not same convolution.
If you want output width to be same as input width, you need to add additional implcit padding to input, given by Conv1d’s padding argument: https://pytorch.org/docs/stable/nn.html#conv1d 18 |
st102515 | I tried to implement my own custom loss based on the tutorial in extending autograd 3.0k.
Here is the implementation outline:
class MyCustomLoss(Function):
def forward(self, input, target):
... # implementation
return loss # a single number (averaged loss over batch samples)
def backward(self, grad_output):
... # implementation
return grad_input
The forward function take an input from the previous layer and target which contains array of labels (categorical, possible value = {0,…,k-1}, k is the number of class).
In the backward function I write a gradient of the loss with respect to the input. When I run, I got an error says that it needs one more gradient. I assume that pytorch also require to also write the gradient of the loss with respect to the target, which in this case does not really make sense (target is a categorical variable), and we do not need that to backpropagate the gradient.
Here’s my code to run the implementation
inp = Variable(torch.randn(10,10).double(), requires_grad=True)
target = Variable(torch.randperm(10), requires_grad=False)
loss = MyCustomLoss()(inp, target)
loss.backward()
And here is the error message I get:
RuntimeError: MyCustomLoss returned an invalid number of gradient tensors (expected 2, but got 1)
Is there anything that I missed? How to correctly implement a custom loss?
Thank you. |
st102516 | Return None for the gradient of values that don’t actually need gradients. So return grad_input, None. |
st102517 | can i confirm that there are two ways to write customized loss function:
using nn.Moudule
Build your own loss function in PyTorch 8.6k
Write Custom Loss Function 4.8k
Here you need to write functions for init() and forward().
backward is not requied. But how do I indicate that the target does not need to compute gradient?
2)using Functional (this post)
[Solved] What is the correct way to implement custom loss function?
I tried to implement my own custom loss based on the tutorial in extending autograd.
Here is the implementation outline:
class MyCustomLoss(Function):
def forward(self, input, target):
... # implementation
return loss # a single number (averaged loss over batch samples)
def backward(self, grad_output):
... # implementation
return grad_input
The forward function take an input from the previous layer and target which contains array of labels (categoric…
Here you need to write functions for both forward() and backward() |
st102518 | I need to also implement backward because I use some operations that autograd’s automatic gradient won’t work. In the case that you just use standard operation, I think you do not need to extend backward method. |
st102519 | Hi, I’m attempting to write my own custom loss function, for the log likelihood of a Gaussian, ie. least squares.
I’ve written the following:
> class LSE_loss(torch.autograd.Function):
> @staticmethod
> def forward(ctx, mu, sigma, x):
> detsig = linalg.det(sigma.numpy())
> invsig = linalg.inv(sigma.numpy())
> result = 0.5*np.log(detsig) -0.5 * np.transpose(x - mu.numpy(),(0,2,1)).matmul(invsig.matmul(x- mu.numpy()))
> ctx.save_for_backward(mu,sigma, x)
> return torch.FloatTensor(result)
> @staticmethod
> def backward(ctx, grad_output):
> x, mu, sigma = ctx.saved_variables
> invsig = linalg.pinv(sigma.numpy())
> grad_mu = invsig.matmul(x-mu.numpy())
> grad_sig = -0.5*(invsig - (invsig.matmul(x-mu.numpy())).matmul((x-mu.numpy()).matmul(invsig)))
> return torch.FloatTensor(grad_mu), torch.FloatTensor(grad_sig), None
But when I make an instance of the loss, and call loss.backward(), I get the error "TypeError: backward() takes exactly 2 arguments (0 given).
What am I doing wrong?
ref for formulae: http://www.notenoughthoughts.net/posts/normal-log-likelihood-gradient.html 135 , I know calculating inverse s isn’t ideal, open to suggestions for alternatives…
Cheers. |
st102520 | Here’s my example for how to create a custom loss function (along with several other important things in PyTorch). See if going through it is of any help!
GitHub
Spandan-Madan/A-Collection-of-important-tasks-in-pytorch 3.2k
A-Collection-of-important-tasks-in-pytorch - Everyday things people use in Pytorch. No need to spend hours reading Pytorch forums trying to find them! |
st102521 | Hi George,
Have you solved your problem? I guess it may be because of the type of the variables in your forward method are all numpy arrays. The error message effectively said there were no input arguments to the backward method, which means, both ctx and grad_output are None. This then means ‘ctx.save_for_backward(mu, signa, x)’ method did nothing during forward call. Maybe change mu, sigma and x to torch tensors or Variable could solve your problem.
Cheers,
Shuokai |
st102522 | It is perhaps too late but for static class you should not make an instance by LSE_loss() instead you should call apply:
loss = LSE_loss.apply |
st102523 | I’m trying to get pytorch working on my ubuntu 14.04 machine with my GTX 970.
It’s been stated that you don’t need to have previously installed CUDA to use pytorch so my first questions are: Why are there options to install for CUDA 7.5 and CUDA 8.0? How do I tell which is appropriate for my machine and what is the difference between the two options?
I selected the Ubuntu -> pip -> cuda 8.0 install and it seemed to complete without issue. However if I load python and run
import torch
torch.cuda.is_available()
I get False.
Other cuda operations fail as well.
Second question: How is this determined?
Is there something I need in my environment for my device to be detected?
It would be great if there were a post-install checklist to help diagnose these issues. If there is one and I’ve missed it, please let me know! |
st102524 | I think you don’t need to install CUDA to use the cpu part of pytorch even you install the cuda version of pytorch.
However, if you want to use gpu, then you need to install cuda. |
st102525 | You should select the CUDA install based on which CUDA version you have. You can do this via nvcc --version in a terminal; it’ll tell you what version you’re running.
PyTorch checks your ‘/usr/local/cuda’ directory for a CUDA installation, as well as the CUDA_HOME global variable (source code here 222). You don’t need to set the CUDA_HOME manually unless your CUDA installation is somewhere non-standard. |
st102526 | I have the same question as well. Since it was stated that installing pytorch binary is the only thing needed to run cuda vesion of pytorch. Refer to this answer: https://discuss.pytorch.org/t/newbie-question-what-are-the-prerequisites-for-running-pytorch-with-gpu/698/3?u=houjing_huang 216 |
st102527 | I think you do not need to install CUDA separately because it is included in the binary pytorch distribution, but:
you need to have to proper NVIDIA driver installed for your GPU (I think it will probably have to be the latest NVIDIA proprietary driver, not the the default open-source neveau driver)
your GPU must be supported by the CUDA version which is included in the python binary installation. If the GPU is an older model, it may be that an older CUDA version still supports it but a newer version not anymore
I think the pytorch pages could make all this a bit clearer, when I first looked at the installation instructions I thought the cuda version to specify is the one pytorch expects to be installed, when in reality it is the one included in the binary distribution. |
st102528 | I’m trying to estimate a PDF from data to calculate KL divergence or entropy. Does anyone know how to do KDE in pytorch? I’d like to be able to do it on my tensors and not transfer to numpy.
Thanks! |
st102529 | Hi guys, can you plz tell me how to deal with the following problem? Cheers!
RuntimeError: cuda runtime error (2) : out of memory at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/THCTensorRandom.cu:25 |
st102530 | Your GPU does not have enough memory left to run the operation.
If this GPU is used by other processes, try to stop them.
Otherwise if that’s not the case, your code just needs too much memory.
You could try to e.g. lower the batch size. If you are already at batch_size=1, you could try to make your model smaller until it fits.
The reason for this error is hard to guess without code. You could also have a potential memory leak, e.g. by storing the computation graph with something like total_loss += loss in your training procedure. |
st102531 | If you can’t figure out the reason, you could post your code so that we could have a look at it. |
st102532 | Let me try now according to your nice advice. Had any problem, I will do accordingly. |
st102533 | Hi ptrblck,
Now the code is running smoothly without any modification. What’s up? |
st102534 | Well, I can just speculate without code. Maybe a process was not killed properly and was still using the GPU?
You can check it’s memory with nvidia-smi in your terminal. |
st102535 | Hi ptrblck,
Sorry to give you so late reply -
Yes, you are correct. At that time a process was actually not killed properly and was still using the GPU.
Thanks again! |
st102536 | I just updated to pyTorch 0.4.1 and my code that was running fine on 0.4.0 is now throwing this runtime error.
<ipython-input-9-c1a4924f6dbc> in init_freq_alias_matrix(self, swapped)
167 n = n + 1
168 alias_op = sparse.coo_matrix((temp[0:n], (ii[0:n], jj[0:n])), shape=(np.prod(M), np.prod(N)))
--> 169 self.alias_op = sparse_mx_to_torch_sparse_tensor(alias_op).cuda()
170
171
RuntimeError: torch.cuda.sparse.DoubleTensor is not enabled.
How do I enable them? |
st102537 | HI, I found a wired bug:
In [1]: import torch
In [2]: a=torch.tensor([2], requires_grad=True)
In [3]: b=a.to('cuda')
In [4]: a.requires_grad
Out[4]: True
In [5]: b.requires_grad
Out[5]: False
Why b do NOT keep requires_grad info from a ?
Besides, torch.to() seemingly not a in-place operation, which means, it’s different from .cuda(), So i feel confused since the migration guide told us to us .to() to replace .cuda()? |
st102538 | Solved by gchanan in post #4
Oh, I see the issue. The tensor you created is not floating point, if you create a floating point tensor torch.tensor([2.], requires_grad=True) it works as expected. We recently merged some code that makes non-floating-point tensor calculations not require grad (I don’t know if that changed this s… |
st102539 | Hi,
I think the issue is just when it’s a scalar:
In [1]: import torch
In [2]: a = torch.rand(10, requires_grad=True)
In [3]: a.requires_grad
Out[3]: True
In [4]: b = a.to("cuda")
In [5]: b.requires_grad
Out[5]: True
@smth is that expected behaviour? |
st102540 | I’m looking into it; it doesn’t look to just be with scalars (I think you mean 1-element tensors, since the above isn’t 0-dim), because I get the correct behavior if I pass 1 to torch.rand instead of 10. |
st102541 | Oh, I see the issue. The tensor you created is not floating point, if you create a floating point tensor torch.tensor([2.], requires_grad=True) it works as expected. We recently merged some code that makes non-floating-point tensor calculations not require grad (I don’t know if that changed this specific code path or not, I have to check). I agree the result here is unintuitive and we’ll improve it. |
st102542 | The issue occurs also for float tensors. Despite the fact that requires_grad flag is retained. Proof:
import torch
device = torch.device("cuda")
x = torch.randn(5, 3, requires_grad=True).to(device)
x.sum().backward()
print(x.grad, x.requires_grad) # (None, True) |
st102543 | The example you just showed works as expected.
Here x does not contain the leaf Variable for which gradients are computed, but the result of the operation .to(device).
@gchanan yes I think it’s because torch.tensor([2]) creates an integer typed tensor. Shouldn’t the constructor just fail if we ask for requires_grad=True? |
st102544 | @albanD I made it throw an error in https://github.com/pytorch/pytorch/pull/7185 7, although I think it should probably be just be warning (and not set requires_grad to True). |
st102545 | Here x does not contain the leaf Variable for which gradients are computed, but the result of the operation .to(device).
I am a bit of newbie. Could you elaborate on this a bit more. Isn’t the result of the .to(device) operation the same leaf variable but just in the GPU? Thanks. |
st102546 | No it’s a new variable, that is on the gpu and that contains the same thing as the original cpu tensor.
Is the following sample making it clearer?
import torch
a = torch.rand(1, requires_grad=True)
b = a.cuda()
c = 3*b
c.sum().backward()
print(c.grad) # None: Not a leaf
print(b.grad) # None: Not a leaf
print(a.grad) # tensor([3]): A leaf
b = torch.rand(1, requires_grad=True).cuda()
c = 3*b
c.sum().backward()
print(c.grad) # None: Not a leaf
print(b.grad) # None: Not a leaf |
st102547 | @albanD, Thanks.
Could you explain the second question for me?
Besides, torch.to() seemingly not a in-place operation, which means, it’s different from .cuda(), So i feel confused since the migration guide told us to us .to() to replace .cuda()?
in pytorch 0.3, we can write
a = torch.Tensor(...)
a.cuda()
but in python 0.4, we need
a = torch.Tensor(...)
a = a.to(device)
So .to() is not in-place operation? |
st102548 | a.cuda() is not inplace either.
If you do that in 0.3, a is still on CPU, only the returned value is on GPU |
st102549 | How then should we make a tensor.to() output to be a leaf of the graph? I get why it behaves this way, but not sure how to implement the case where GPU tensors are on the graph to calculate gradients. Thanks! |
st102550 | My test code:
import torch as t
from torchnet import meter
loss_meter = meter.AverageValueMeter()
a = t.Tensor([10])
loss_meter.add(a)
b = t.Tensor([10])
loss_meter.add(b)
print(loss_meter.mean)
but I get a wrong result:
tensor([ 15.]) |
st102551 | The code for AverageValueMeter is a bit buggy if you are using tensors.
TLDR: You can use a.item() and b.item() and the code should work.
Long version:
There are no type checks in the method, so a tensor will be handled like an int or float.
Using .item() will return the pure Python float, so the code will work as intended.
However, if you pass tensors, you can see that the code holds a reference to the passed tensor in:
self.sum += value
(value is the passed tensor).
Now if we want to see what happens if we pass another tensor to it, we can add a print statement into the top of the else branch in add():
...
else:
print(self.mean, self.mean_old, value, n)
self.mean = self.mean_old + ...
Although we just passed the new value (torch.tensor([10.])) to the method, self.mean will return 20! The reason for this error is because self.mean was assigned to self.sum, which was inplace modified by the last tensor, which in the end modifies self.mean.
A simple fix would be to add these lines at the beginning of add:
def add(self, value, n=1):
if isinstance(value, torch.Tensor):
value = value.item()
self.val = value
... |
st102552 | Hi I have a couple questions and I am inexperienced so please bear with me.
I am trying to make a progressive autoencoder and I have thought a couple ways of growing my network during training. However, I am always stuck on this one part where I don’t know if changing the input(encoder) and output(decoder) channel would affect my network. See the example below.
X = torch.randn( 8, 1, 4, 4,) # A batch of 8 grayscale images of 4x4 pixels in size
Encoder = nn.Sequential( Conv2D( 1, 16, 3, 1, 1 ), nn.ReLU() ) # starting setup 16 3x3 kernels
if I print the above weights from the network I would get a size of [ 1, 16, 3, 3 ], 16 kernels each of size 3x3
if I want to grow the network I would need to do save those weight because hopefully its already well trained on those 4x4 image inputs.
X = torch.randn( 8, 1, 8, 8) # increase the image size from 4x4 to 8x8
...
new_model = nn.Sequential()
then do...
# copy the previous layer and its weights from the original encoder
# BTW My issue starts here.
# Add/grow the new_model with new layers concat with the old layer, also modify the input channela so they can link correctly
# Final result would be like something below.
new_model = nn.Sequential( Conv2D( **1**, 8, 3, 1, 1 ), nn.ReLU(), Conv2D( **8**, 16, 3, 1, 1 ), nn.ReLU() )
Encoder = new_model
# Repeat
Okay everything looks good however because I change the input channel the size of the weights changed as well, and this is the issue that I have been stuck on for a while now. You can simply check this by running,
foo_1 = nn.Conv2d(1, 1, 3, 1, 1) # You can think this as the starting Conv2D from the starting encoder
foo_2 = nn.Conv2d(3, 1, 3, 1, 1) # You can think this as the modfiied starting Conv2D with an outer layer outputting 3 channels connecting to it
print(foo_1.weight.size()) # torch.Size([1, 1, 3, 3])
print(foo_2.weight.size()) # torch.Size([1, 3, 3, 3])
Initially, I thought foo_1 and foo_2 would both have the same weight size, as in both would only use one 3x3 kernel but it doesn’t see to be the case. I hope you can see my dilemma now, after x amount of epochs I need to grow another convolution and I have to mess with the input size to make new layers chain properly but if I change the input size the shape of the weight is different and I don’t know how pasting the old state would work. I have been looking at pro gan implementations in pytorch and IMO they are not easy to read, so please someone more knowledge please help me build more institutions on how to properly progressively grow your network? Thank you in advance! |
st102553 | Solved by inkplay in post #3
Hi ptrblck I actually posted this question to stackoverflow and some one helped me solve it. I neglected an important concept in progressive networks and that is fading in the channels. Eg toRGB and FromRGB in the progan paper. Here is the answer that helped me build more intuitions.
Second, this … |
st102554 | The kernel size is defined as [out_channels == number of kernels, input_channels, height, width]. In your example you are returning 1 output channel in foo_1, which means foo_2 should have in_channels=1.
A simple approach for your problem could be to just append the modules to a nn.ModuleList:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.features = nn.ModuleList(
[nn.Conv2d(1, 3, 3, 1, 1),
nn.ReLU()]
)
def forward(self, x):
for feat in self.features:
x = feat(x)
return x
model = MyModel()
x = torch.randn(1, 1, 24, 24)
output = model(x)
# Add new layer
model.features.append(nn.Conv2d(3, 6, 3, 1, 1))
model.features.append(nn.ReLU())
output = model(x)
Let me know, if this fits your use case. |
st102555 | Hi ptrblck I actually posted this question to stackoverflow and some one helped me solve it. I neglected an important concept in progressive networks and that is fading in the channels. Eg toRGB and FromRGB in the progan paper. Here is the answer that helped me build more intuitions.
Second, this isn’t really about implementation but theory. You cannot magically convert a convolution layer from accepting 1 channels to 8 channels. There are numbers of ways to expand your convolution filter like appending random weights but I think it is not what you wanted.
From the second paper (It is a GAN, but the idea is the same), it does not expand any filters. Instead, the filters maintain their shape in the entire training process. Meaning that, you would have a
Conv2D(8, 16, 3, 1, 1)
from the very beginning (assuming you only have those two layers). An obvious problem pops out – your grayscale image is a 1-channel input, but your convolution requires a 8-channel input in the first stage of training. In the second paper, it uses an extra 1x1 convolution layer to map RGB <-> feature maps. In your case, that would be
Conv2D(1, 8, 1)
which maps 1-channel input to 8-channel output. This can be thrown away after you are done with first stage.
There are other techniques like gradually fading in using a weight term stated in the paper. I suggest you read them, especially the second one.
So in the end I don’t have to manually switch channels I can keep a predefine conv layer and convert my image into a multi channel object then discard the 1x1 conv block. I am going to read the pro gan paper again since a lot of things are clearer now. Thanks for the help. |
st102556 | Hi, let’s see a typical case:
class MyLayer(nn.Module):
def __init__(self)
super(...)
self.a = nn.Parameters(...)
self.b = nn.Linear()
I wonder how can nn.Module :
add self.a into self.named_parameters() and
self.b to self.named_children and self.named_module.
Could anyone introduce the magic behind nn.Module.
Everytime I use nn.Module, I felt worried since I dnt understand what nn.Module DID for me. |
st102557 | Basically if you assign some member in nn.Module the internal __setattr__ method is called.
Have a look at the source code 19.
Based on the type you try to assign, the conditions call the appropriate method to register the parameter or buffer etc. |
st102558 | Hi, for pytorch < 0.4, we can easily do:
a = Variable(b.data, requires_grad=True)
However, since .data is not recommeneded in 0.4, we can
a = b.detach()
a.requires_grad_()
a = b.detach().clone()
a.requires_grad_()
a = b.clone().detach()
a.requires_grad_()
I wonder what’s the difference among 1, 2, 3. |
st102559 | Solved by justusschock in post #3
That’s not entirely true since the detached tensor shares the storage with the original one. If you want to modify them independent from each other you have to clone them. Saying that, approaches 2 and 3 are indeed equivalent, but in approach 1 a would still share the same storage with b which is no… |
st102560 | detach() will create a new tensor so there is no need to clone() after or before detach(). They are all the same.
Yes only detach() is not right, the document has it. |
st102561 | That’s not entirely true since the detached tensor shares the storage with the original one. If you want to modify them independent from each other you have to clone them. Saying that, approaches 2 and 3 are indeed equivalent, but in approach 1 a would still share the same storage with b which is not the case in the other approaches due to the clone() operation |
st102562 | Hi,
If what you want is exactly the old a = Variable(b.data, requires_grad=True) then the equivalent is a = b.detach().requires_grad_(). In both cases, a and b share the same storage and won’t use extra memory. The new version is better though because the autograd engine will properly detect if you do inplace operations on a while b's original value was needed for something else. So the gradients will be computed properly and if it can’t be done, it will raise an error.
If such error occurs, then you will need to add a clone to make sure that you won’t change b by side effect. The best way to do it I think is a = b.detach().clone().requires_grad_(). |
st102563 | How do I work with sparse ATen tensors in C++? They seem to at::Tensor like everything else. |
st102564 | I meet this error with pytorch 0.4 and python 3.5, when I try to train and then evaluate the network every epoch. After several epoches, it throws this error and can not free the GPU memory.
Anyone to help figure out what is the problem? |
st102565 | Hi,
Could you provide a small code sample (20-50 lines) that reproduces this problem so that we can investigate it please? |
st102566 | I am afraid I couldn’t provide the code currently. Actually the same code run in another machine is just fine. This error always happens when the code run into evaluation mode on the validation dataset. I am trying to stop the evaluation part to see what happes. |
st102567 | I am trying to write a custom backwards function using the CUDAExtension support in PyTorch, but the kernel always gets gradient values as 0 (except for the first location), while printing out the gradient before dispatching it to the kernel prints the correct gradient values.
Here are my CUDA kernels:
#include <iostream>
#include <torch/torch.h>
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <ATen/cuda/detail/CUDAHooks.h>
#include <THC/THC.h>
#include <THC/THCAtomics.cuh>
#include <THC/THCDeviceUtils.cuh>
template <typename T>
__global__ void CoolForward(const int nthreads, const T* input, T* output,
const int batch_size, const int channels,
const int height, const int width)
{
int index = (blockIdx.x * blockDim.x) + threadIdx.x;
if (index < nthreads){
int w = index % width;
int h = (index / width) % height;
int c = (index / width / height) % channels;
int n = index / width / height / channels;
output[index] = input[index] + 1;
}
}
template <typename T>
__global__ void CoolBackward(const int nthreads, const T* grad,
const int batch_size, const int channels,
const int height, const int width, T* grad_input)
{
int index = (blockIdx.x * blockDim.x) + threadIdx.x;
if (index < nthreads){
int w = index % width;
int h = (index / width) % height;
int c = (index / width / height) % channels;
int n = index / width / height / channels;
// print the gradient values
printf("index=%d, n=%d, c=%d, h=%d, w=%d, value=%f \n", index, n, c, h, w, grad[index]);
// copy the gradient values
grad_input[index] = grad[index];
}
}
This is my cpp-extension code:
at::Tensor cool_forward_cuda(const at::Tensor &input)
{
int n = input.size(0);
int c = input.size(1);
int h = input.size(2);
int w = input.size(3);
auto output_size = n * c * h * w;
dim3 grid(1);
dim3 block(512);
at::Tensor output = at::zeros({n, c, h, w}, input.type());
at::cuda::CUDAStream stream = at::cuda::getCurrentCUDAStream();
AT_DISPATCH_ALL_TYPES(input.type(), "cool_forward", ([&] {
CoolForward<scalar_t><<<grid, block, 0, stream>>>(
output_size,
input.data<scalar_t>(),
output.data<scalar_t>(),
n,
c,
h,
w);
}));
THCudaCheck(cudaGetLastError());
return output;
}
at::Tensor cool_backward_cuda(const at::Tensor &grad,
const int batch_size,
const int channels,
const int height,
const int width)
{
std::cout << "gradient:\n " << grad << std::endl; // this prints the gradients correctly
at::Tensor grad_input = at::zeros({batch_size, channels, height, width}, grad.type());
dim3 grid(1);
dim3 block(10); // block size is 10 to help with debugging
at::cuda::CUDAStream stream = at::cuda::getCurrentCUDAStream();
AT_DISPATCH_FLOATING_TYPES(grad.type(), "cool_backward", ([&] {
CoolBackward<scalar_t><<<grid, block, 0, stream>>>(
grad.numel(),
grad.data<scalar_t>(),
batch_size,
channels,
height,
width,
grad_input.data<scalar_t>());
}));
THCudaCheck(cudaGetLastError());
return grad_input;
}
And after a bunch of boilerplate to get the extension running, here is my python code:
import torch
from cool_test import _C
from torch.autograd import Function
from torch import nn
class CoolFunc(Function):
@staticmethod
def forward(ctx, x):
y = _C.cool_forward(x)
return y
@staticmethod
def backward(ctx, grad):
dx = _C.cool_backward(grad,
grad.shape[0], grad.shape[1],
grad.shape[2], grad.shape[3])
return dx
class Cool(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return CoolFunc.apply(x)
x = torch.rand(1, 1, 5, 5).cuda()
x.requires_grad = True
m = Cool()
print("input=\n", x)
y = m(x)
print("y=", y)
s = y.sum()
print("s=", s)
s.backward()
print("x grad\n", x.grad)
which gives me this output:
input=
tensor([[[[0.8135, 0.5903, 0.4413, 0.4109, 0.9244],
[0.1199, 0.0319, 0.9599, 0.0336, 0.3685],
[0.7604, 0.5010, 0.7218, 0.2321, 0.1330],
[0.0986, 0.7200, 0.3598, 0.8679, 0.2629],
[0.1547, 0.2007, 0.0335, 0.4450, 0.9741]]]],
device='cuda:0', requires_grad=True)
y= tensor([[[[1.8135, 1.5903, 1.4413, 1.4109, 1.9244],
[1.1199, 1.0319, 1.9599, 1.0336, 1.3685],
[1.7604, 1.5010, 1.7218, 1.2321, 1.1330],
[1.0986, 1.7200, 1.3598, 1.8679, 1.2629],
[1.1547, 1.2007, 1.0335, 1.4450, 1.9741]]]],
device='cuda:0', grad_fn=<CoolFuncBackward>)
s= tensor(36.1598, device='cuda:0', grad_fn=<SumBackward0>)
gradient:
(1,1,.,.) =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
[ Variable[CUDAFloatType]{1,1,5,5} ]
x grad
index=0, n=0, c=0, h=0, w=0, value=1.000000
index=1, n=0, c=0, h=0, w=1, value=0.000000
index=2, n=0, c=0, h=0, w=2, value=0.000000
index=3, n=0, c=0, h=0, w=3, value=0.000000
index=4, n=0, c=0, h=0, w=4, value=0.000000
index=5, n=0, c=0, h=1, w=0, value=0.000000
index=6, n=0, c=0, h=1, w=1, value=0.000000
index=7, n=0, c=0, h=1, w=2, value=0.000000
index=8, n=0, c=0, h=1, w=3, value=0.000000
index=9, n=0, c=0, h=1, w=4, value=0.000000
tensor([[[[1., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]]], device='cuda:0')
As you can see, the last tensor output is just the gradients copied over, yet it is 1 only in a single place and zero everywhere else. Any help?
I am pretty much a noob at CUDA so this may just boil down to bad memory access, but if someone could elaborate on how I should be doing this, I would be really thankful. |
st102568 | Hi,
I am not sure but I think the problem is that you ignore strides when you index your tensors in the kernel.
Does changing you CoolFunc that way helps ?
@staticmethod
def backward(ctx, grad):
grad = grad.clone()
dx = _C.cool_backward(grad,
grad.shape[0], grad.shape[1],
grad.shape[2], grad.shape[3])
return dx |
st102569 | Huh that seemed to have worked!
Can you please explain some more why seemingly just creating a duplicate of the tensor fixes this? |
st102570 | I printed out the stride values of the gradients before and after the clone and I get
before: (0, 0, 0, 0)
after: (25, 25, 5, 1)
Is this potentially a bug? |
st102571 | Hi,
That is expected. The backward of sum, for more efficiency return a tensor that is expand.
That means that in practice, there is a single memory element allocated for it, and the stride is 0 for all dimensions as you can see.
This means that the first element in the first dimension is at position 0*0=0 but the second element is at position 1*0=0 as well. The full formula is element_index * stride = position_in_memory.
In pytorch, you have last dimensions that are contiguous, and so after cloning and getting a full tensor. The stride of the last dimension is 1 as expected: you need to move of 1 to get the next value of that dimension. For the previous to last dimension, the stride is 5 (which is the size of the last dimension) as there are 5 elements between each consecutive elements on that dimension.
Note that pytorch memory access also have a storage_offset element that means that the element [0,0,0,0] of your tensor might not be the first element in the pointer for data.
If you’re not familiar with these things, it might be simpler to keep the clone and then you can assume that you have a contiguous tensor in the cuda code and don’t need to pass storage_offset and stride as arguments. |
st102572 | I see what you mean. Backwards of sum simply expands the tensor to the forward input tensor’s shape, but still has only one memory location allotted.
I guess this means that when reading the sum tensor in backwards, I have to read it taking into account the stride values? (aka all the reads point back to the single memory element?) |
st102573 | To index an Aten tensor properly, you need to take into account it’s size, stride and storageOffset (not sure about the exact name of the last in Aten).
At the moment, your cuda kernel only considers the size and assume storageOffset=0 and stride is the one of a contiguous tensor.
You can either adapt your kernel to take all of them into account, or add a .clone() before your kernel to make sure that your assumptions will be verified. |
st102574 | 1)Why pipy package size is largely different by platform (linux and mac)?
(519MB vs. 11MB)
2)Windows package is not released to pipy?
PyPI
torch 1
Tensors and Dynamic neural networks in Python with strong GPU acceleration |
st102575 | Mac binaries don’t support CUDA, while the CUDA and cuDNN libs are shipped with the Linux binaries, which makes them quite large.
I’m not using Windows personally, but based on the install instructions on the website 1, it seems you can install PyTorch on Windows using pip, e.g.:
pip3 install http://download.pytorch.org/whl/cu80/torch-0.4.1-cp36-cp36m-win_amd64.whl |
st102576 | Hi all,
I was trying to use pytorch wrapper of CTCLoss function (https://github.com/SeanNaren/warp-ctc 12).
But it’s no works with actual master of pytorch. I run this sample code:
import torch
from torch.autograd import Variable
from warpctc_pytorch import CTCLoss
ctc_loss = CTCLoss()
probs = torch.FloatTensor([[[0.1, 0.6, 0.1, 0.1, 0.1], [0.1, 0.1, 0.6, 0.1, 0.1]]]).transpose(0, 1).contiguous()
labels = Variable(torch.IntTensor([1, 2]))
label_sizes = Variable(torch.IntTensor([2]))
probs_sizes = Variable(torch.IntTensor([2]))
probs = Variable(probs, requires_grad=True)
cost = ctc_loss(probs, labels, probs_sizes, label_sizes)
cost.backward()
And it’s broke with error:
Traceback (most recent call last):
File “ctc_test.py”, line 16, in
cost.backward()
File “/usr/local/lib/python3.5/dist-packages/torch/autograd/variable.py”, line 128, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File “/usr/local/lib/python3.5/dist-packages/torch/autograd/init.py”, line 83, in backward
variables, grad_variables, retain_graph, create_graph)
RuntimeError: expected Variable (got ‘torch.FloatTensor’)’
Anybody know how to fix this error?
Thanks in advance! |
st102577 | Apparently some recent patch now requires returning Variables from torch.autograd.Function's backward method (before Tensor were fine). Try wrapping self.grads 29 with torch.autograd.Variable(self.grads).
I’m also affected with my own autograd functions. |
st102578 | @vadimkantorov is right. This will be improved before 0.4 is released once Variable and Tensor are merged. The master branch is in an intermediate state where autograd Functions have to return Variables and not Tensors. |
st102579 | I think everything is the same as official tf impl of MAML, but we cannot replicate the results of MiniImageNet. We got 45% in pytorch, 48%+ in tf.
Is there anyone to succeed this impl of MAML in pytorch? |
st102580 | As she wrote in README, she was successful in one setting, not in other setting… I think there is no perfect impl of MAML in pytorch yet. |
st102581 | I have a PyTorch implementation, and performance there is slightly lagging the TF version as well.
There are lots and lots of hyperparameters to keep track of. I assume that’s the issue. |
st102582 | Hi, I noticed that my algorithm will occupy more and more gpu memory and as a result, reach the limit of gpu memory capacity and out of memory.
I dnt understand which common factor will lead to these. i have checked my code and seems normal. Anyone give some tips how to check this bugs? |
st102583 | This usual indicates that you are holding some tensors in a list (or something similar) which prevents Pytorch from freeing the memory. In the worst case you have a list of non-detached tensors which are still tracked by autograd and hold the whole gradient-path.
If you can post your code we could have a look at it. |
st102584 | Hi, Could u kindly leave your email, so that I can send you my source code( 2 files.).
@justusschock |
st102585 | Is there a way I can replace certain select modules in a network without having to change its definition? For example, in the example below I instantiate a resnet50 from torchvision and then replace ReLU with clampedRelu:
from torchvision.models import *
net = resnet50()
replaceReluWithClampRelu(net)
for i in range(args.start_epoch, args.epochs):
train(net, epoch)
test(net, epoch)
#end for
I dont know how to implement the replaceReluWithClampRelu function in the above example. Any ideas? |
st102586 | Hi there,
I’m using Riddhiman Dasgupta 's pytorch implementation of tree lstm to my machine translation model:
github.com
dasguptar/treelstm.pytorch/blob/master/treelstm/model.py 16
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import Constants
# module for childsumtreelstm
class ChildSumTreeLSTM(nn.Module):
def __init__(self, in_dim, mem_dim):
super(ChildSumTreeLSTM, self).__init__()
self.in_dim = in_dim
self.mem_dim = mem_dim
self.ioux = nn.Linear(self.in_dim, 3 * self.mem_dim)
self.iouh = nn.Linear(self.mem_dim, 3 * self.mem_dim)
self.fx = nn.Linear(self.in_dim, self.mem_dim)
self.fh = nn.Linear(self.mem_dim, self.mem_dim)
def node_forward(self, inputs, child_c, child_h):
child_h_sum = torch.sum(child_h, dim=0, keepdim=True)
This file has been truncated. show original
I’m now having performance issue and would like to know if anyone has any improvement idea.
The code is as below, what this node_forward does is to process one token in a sentence.
def node_forward(self, inputs, child_c, child_h):
child_h_sum = torch.sum(child_h, dim=0, keepdim=True)
iou = self.ioux(inputs) + self.iouh(child_h_sum)
i, o, u = torch.split(iou, iou.size(1) // 3, dim=1)
i, o, u = F.sigmoid(i), F.sigmoid(o), F.tanh(u)
f = F.sigmoid(
self.fh(child_h) +
self.fx(inputs).repeat(len(child_h), 1)
)
fc = torch.mul(f, child_c)
c = torch.mul(i, u) + torch.sum(fc, dim=0, keepdim=True)
h = torch.mul(o, F.tanh(c))
return c, h
In my case,
inputs is a 300 dimensions tensor
child_c and child_h are tensors with size [1,300]
ioux and iouh are nn.Linear with 300 in_features and 900 out_features
fh and fx are nn.Linear with 300 in_features and 300 out_features
I’m running it on my GTX 1070, but I also tried GTX 1080Ti which doesn’t have a significant improvement.
The node_forward method takes 0.00135s. In my translation mode, it needs to do encoding 4 times in each iteration. So if I want to train it for 300k iteration with 50 lines for each iteration. Let’s say all sentences have 50 tokens. It will take:
4 times * 300k iteration * 50 lines/iteration * 50 tokens/lines * 0.00135s/token = 4,050,000s = 46.875 days
If we look into each line:
iou = self.ioux(inputs) + self.iouh(child_h_sum) ----- 0.0003s (22.22% of the method time)
i, o, u = F.sigmoid(i), F.sigmoid(o), F.tanh(u) ----- 0.00014s (10% of the method time)
f = F.sigmoid(self.fh(child_h) +self.fx(inputs).repeat(len(child_h), 1)) ----- 0.00043s (31.85% of the method time)
c = torch.mul(i, u) + torch.sum(fc, dim=0, keepdim=True) ----- 0.00014s (10.37% of the method time)
The overall performance of this tree-LSTM is 10 times slower than the native Pytorch LSTM cell. The extra tree structure can contribute to the slowness but I’m really not sure if it can be 10 times slower because of this.
I checked the implementation of native Pytorch LSTM and GRU cell, it seems that Pytorch is using some CuDnn api to do this kind of LSTM or GRU. So I’m wondering whether I can use that api to speed up my training though I can’t find any document.
On the other hand, I’m not sure if I can do anything to speed up those torch methods in the lines I listed.
Any input is much appreciated! Thanks in advance! |
st102587 | The problem is likely the (lack of) batching.
James Bradbury wrote an article 78 how to do that to speed up things (but it’s PyTorch 0.2 or so).
Best regards
Thomas |
st102588 | I am getting very very slow performance from pytorch prediction on CPU.
90 minutes - keras/tensorflow on 72 processors
<60 minutes - pytorch on GPU
<60 minutes - keras/tensorflow GPU
11 hours - pytorch on 72 processors
I read somewhere pytorch was a little slower on cpu but was not expecting it to be so extreme. Is there a magic formula for using pytorch in CPU?
I load the model with:
torch.load(modelpath, map_location=lambda storage, loc: storage)
model.eval()
To predict I call model(chunk) on chunks that have 5 images.
I had OMP_THREAD_LIMIT=1 but have unset this and it made no difference. |
st102589 | Just tried this on a smaller job on my laptop with 4 processors.
25 minutes keras. cpus are 85-100% utilised.
40 minutes pytorch. cpus are 45-55% utilised.
Still a noticeable gap but not as big. So as the number of CPUs increases what happens? Is this something that can be resolved or is pytorch not suitable for big data predictions on cpus? |
st102590 | Hi, I am a new in pytorch,and seems that i have some problem in dataloader。
When i try to define a dataloader my self, how can i ensure that the dataloader indeed loader the data i want everytime if doesn’t have mistake.
Can i print it? How
Thankyou |
st102591 | Thank you very much for quilkly reply, here is my code.
class PrecompDataset(data.Dataset):
def __init__(self, data_path, data_split, vocab, vocab_tag):
self.vocab = vocab
self.vocab_tag = vocab_tag
loc = data_path + '/'
# Captions
self.captions = []
with open(loc+'%s_caps.txt' % data_split, 'rb') as f:
for line in f:
self.captions.append(line.strip())
# Image features
self.images = np.load(loc+'%s_ims.npy' % data_split)
self.length = len(self.captions)
if self.images.shape[0] != self.length:
self.im_div = 5
else:
self.im_div = 1
# the development set for coco is large and so validation would be slow
if data_split == 'dev':
self.length = 5000
def __getitem__(self, index):
# handle the image redundancy
img_id = index/self.im_div
image = torch.Tensor(self.images[img_id])
caption = self.captions[index]
vocab = self.vocab
vocab_tag = self.vocab_tag
# Convert caption (string) to word ids.
tokens = nltk.tokenize.word_tokenize(
str(caption).lower().decode('utf-8'))
caption = []
caption.append(vocab('<start>'))
caption.extend([vocab(token) for token in tokens])
caption.append(vocab('<end>'))
target = torch.Tensor(caption)
return image, index, img_id
def __len__(self):
return self.length
def collate_fn(data):
'''Build mini-batch tensors from a list of (image, caption) tuples.
'''
# Sort a data list by caption length
data.sort(key=lambda x: len(x[1]), reverse=True)
images, captions, captions_tag, ids, img_ids = zip(*data)
# Merge images (convert tuple of 3D tensor to 4D tensor)
images = torch.stack(images, 0)
# Merget captions (convert tuple of 1D tensor to 2D tensor)
lengths = [len(cap) for cap in captions]
targets = torch.zeros(len(captions), max(lengths)).long()
for i, cap in enumerate(captions):
end = lengths[i]
targets[i, :end] = cap[:end]
return images, targets, captions_tag, lengths, ids
def get_precomp_loader(data_path, data_split, vocab, vocab_tag, opt, batch_size=100,
shuffle=True, num_workers=2):
"""Returns torch.utils.data.DataLoader for custom coco dataset."""
dset = PrecompDataset(data_path, data_split, vocab, vocab_tag)
data_loader = torch.utils.data.DataLoader(dataset=dset,
batch_size=batch_size,
shuffle=shuffle,
pin_memory=True,
collate_fn=collate_fn)
return data_loader
def get_loaders(data_name, vocab, vocab_tag, batch_size, workers, opt):
dpath = os.path.join(opt.data_path, data_name)
train_loader = get_precomp_loader(dpath, 'train', vocab, vocab_tag, opt,
batch_size, True, workers)
val_loader = get_precomp_loader(dpath, 'dev', vocab, opt,
batch_size, False, workers)
return train_loader, val_loader
this is the dataloader, maybe it can be a liitle complex.
Simply, i want to get a batch, in this batch, one image corresponds to 5 captions and one caption_tag.
and i want to print the dataloader beacuse :
someone told me that the output of dataloader will be one image correspond to one caption , but another one tell me it will be one image correspond to 5 captions. i wang to get the correct answer |
st102592 | Wangt-CN:
caption = self.captions[index]
Based on this line, seems you just want to return one caption with one image.
Btw, it seems you forget to return the target and several other things…
Wangt-CN:
target = torch.Tensor(caption)
return image, index, img_id |
st102593 | Yes, you are right, i have fogot sone return
and after debug, it actually return obe caption with one image
Thankyou! |
st102594 | I am trying to debug a PyTorch model with pdb, but I cannot seem to get around this particular Unicode encoding error when trying to view the contents of tensors or net parameters, and none of the usual tricks work to strip or reformat Unicode:
(Pdb) dir(params)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
(Pdb) params
*** UnicodeEncodeError: 'ascii' codec can't encode character '\u22f1' in position 294: ordinal not in range(128)
(Pdb) print(params).encode('ascii', 'ignore').decode('ascii')
*** UnicodeEncodeError: 'ascii' codec can't encode character '\u22f1' in position 294: ordinal not in range(128)
(Pdb) print(params).encode('utf-8')
*** UnicodeEncodeError: 'ascii' codec can't encode character '\u22f1' in position 294: ordinal not in range(128)
(Pdb) print(params).encode('utf-8').strip()
*** UnicodeEncodeError: 'ascii' codec can't encode character '\u22f1' in position 294: ordinal not in range(128)
I can’t even use locals() or globals() in pdb to dump everything:
(Pdb) locals()
*** UnicodeEncodeError: 'ascii' codec can't encode character '\u22f1' in position 335: ordinal not in range(128)
(Pdb) globals()
*** UnicodeEncodeError: 'ascii' codec can't encode character '\u22f1' in position 335: ordinal not in range(128)
Any ideas about a way around this? TIA |
st102595 | I’ve seen this before when I ran a buggy tmux installation that didn’t have unicode support. Are you using a terminal emulator (or something else) that has unicode? |
st102596 | Yeah exact same error even with utf8 and ascii encoding and strip()
Makes debugging almost useless. |
st102597 | Whatever ships with Docker pytorch:latest (0.2.0), which I think is 2.7. I will check later this evening to see. |
st102598 | Ok I am actually running Python 3.5.2 :: Continuum Analytics, Inc.
Bash shell on Konsole Version 2.10.5. Fairly recent everything. Only thing
I can attribute it to is perhaps the bash shell being executed inside the
Docker pytorch:latest container? Maybe I need to spawn Konsole from inside
the Docker container. I will try that next. |
st102599 | You can try something like,
export LC_ALL="en_US.UTF-8"
If it works for you (as it did for me), put it in the .bashrc. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.