id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st98168
|
OK, got it! Thanks for your answer! Whatever, it has been updated to the 1.0 version.As long as there is no problems, I will continue use it!
|
st98169
|
From the documentation here 7, it seems that the loss is mainly the element-wise squared differences between two vectors.
The reduction argument should be able to handle special cases where mean, sum or no-reduction is required.
Does this argument make sense?
|
st98170
|
HI,
Given the default reduction argument value, this is actually doing an MSE.
Is you proposition to introduce a new nn.SELoss that is the same but with the default reduction='none' ?
|
st98171
|
I believe that would make more sense semantically. Writing MSELoss and then not doing mean-squared-error looks counter-intuitive.
In any case, MSELoss is a single metric and should not be overloaded with arguments that make it flexible and thus confusing. Perhaps deprecating it in favour of SELoss, or deprecating the reduction param so that MSELoss doesn’t require any param would be something that could be considered.
|
st98172
|
I want to modify the backward of relu, such that i simply pass through the gradients coming from the top rather than 0-ing out the ones where the unit is off.
I looked at this thread 21 and couldn’t get much out of it. Looking here 21, while this works for making the gradients zero, i am not sure what the components of gradient_input are and which one i should modify to have a pass-through.
|
st98173
|
You can use the backward hooks on the relu Module:
import torch
import torch.nn as nn
inp = torch.randn(5, requires_grad=True)
print(inp) # [ 1.7485, 0.5180, -1.2110, -1.3865, -0.6293]
relu = nn.ReLU()
# Without hook:
out = relu(inp)
out.sum().backward()
print(inp.grad) # [1., 1., 0., 0., 0.]
inp.grad.zero_()
# With hook
def grad_hook(mod, grad_in, grad_out):
# Ignore the computed grad_input
# Make it look like this is an identity
return grad_out
relu.register_backward_hook(grad_hook)
out = relu(inp)
out.sum().backward()
print(inp.grad) # [1., 1., 1., 1., 1.]
|
st98174
|
thanks for the reply, from this post 46 however it seems like what one has to return is modification of grad_input, where in the snippet in your post, we seem to be returning a modification of grad_out.
|
st98175
|
That depends what you want to do.
If you want your relu’s backward to act as if it was an identity, then the gradient of the output wrt to input is 1, and so what you want your backward to compute is grad_output * 1. Ignoring the grad_input computed by the backward of the relu as you replace it.
|
st98176
|
yeah i see your point, for a pointwise activation grad_input and grad_output would be of the same size, so its straightforward to directly use the grad_output to substitute grad_input.
An extra question please, form other posts it seems that modification of gradients is not so straightforward for other layers, is that still the case?
|
st98177
|
Do I correctly understand that a shape of labels in classification and shape of output of model(input) is different?
From CIFAR-10 output = model(input), output:
tensor([[-0.3947, -1.8114, 0.5413, 1.2491, -0.0409, 2.1655, -0.7398, 0.8994,
-0.7245, -0.6783],
[ 5.3390, 3.6180, -0.4063, -2.5301, -2.6485, -3.5857, -3.7007, -3.5152,
9.2215, 3.2827],
[-1.0966, -3.1175, 1.1547, 2.9437, 0.3493, 3.4713, 0.2951, 1.2098,
-1.7341, -2.9322],
[-1.8294, -2.7313, 0.9235, 0.6192, 3.2165, 1.3419, 1.4856, 2.6439,
-3.9445, -2.5060]], grad_fn=<ThAddmmBackward>)
Labels:
tensor([7, 3, 9, 8])
It’s contrintuitive to have.
|
st98178
|
It depends on your loss function.
If you use nn.CrossEntropyLoss or nn.NLLLoss for a classification use case, then you are right.
The output of your model should give logits (or log probabilities) for each sample in the batch and each class, i.e. its output will be [batch_size, nb_classes].
The targets however are just holding the class index for each sample in the batch, i.e. its shape will be [batch_size].
However, if you use another loss function, e.g. nn.MSELoss, the shapes of the model’s output and target should be the same.
The docs 78 give an overview of the different loss functions and the expected shapes.
|
st98179
|
I used this program (https://github.com/clcarwin/convert_torch_to_pytorch 2) to convert a resnet34(official from facebook https://github.com/facebook/fb.resnet.torch/tree/master/pretrained 2) model to pytorch. However I get a problem:
File "convert_torch.py", line 314, in <module>
torch_to_pytorch(args.model,args.output)
File "convert_torch.py", line 259, in torch_to_pytorch
model = load_lua(t7_filename,unknown_classes=True,long_size=8)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 608, in load_lua
return reader.read()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 593, in read
return self.read_object()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 523, in wrapper
result = fn(self, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 546, in read_object
return reader_registry[cls_name](self, version)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 245, in read_nn_class
_load_backend(obj)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/torch/utils/serialization/read_lua_file.py", line 220, in _load_backend
for key in dir(obj):
TypeError: '<' not supported between instances of 'int' and 'str'
Is there any chance that I can covert this model?
|
st98180
|
Use this instead: https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.resnet34 48
|
st98181
|
Hello all
I have this navie question about: Is there any difference, in terms of training or gradient updating process, between batch-style or for-loop style for data that has time-axis, like video data ?
In my opinion, batch style work as in:
class network(nn.Module):
def __init__(self):
self.batch = 16
self.T_length = 15
self.conv = nn.Conv2d(...)
self.cls = nn.Linear(...)
def forward(self, Input):
# Input has size [batch * time_length, 3, 224, 224]
out = self.conv(Input) # [batch * time_length, 128, 28, 28]
out = out.view(batch * time_length, -1)
score = self.cls(out)
score = score.view(batch, time_length, -1)
# score for single video is the average over all frames
score = torch.mean(score, axis=1)
return
While, for-loop style work as
class network(nn.Module):
def __init__(self):
self.batch = 16
self.T_length = 15
self.conv = nn.Conv2d(...)
self.cls = nn.Linear(...)
def forward(self, Input):
# Input has size [time_length, batch, 3, 224, 224]
score = []
for i in input:
score.append(self.cls(self.conv(Input).view(batch, -1)))
# concate list or tensor to new tensor
score = torck.stack(score, axis=1) # [ batch, time_length, num_class]
# average over time axis
score = torch.mean(score, axis=1)
return score
# Then optimize
|
st98182
|
Besides some performance difference, both approaches will yield the same results and gradients.
However, there are some minor issues in your code.
E.g. the view call in the first example should be score = score.view(time_length, batch_size, -1), if you want to get identical values for both models. Otherwise they will be a bit mixed up.
Also you are passing some wrong arguments, e.g. axis instead of dim.
Here is a fixed version with some comparisons:
class network(nn.Module):
def __init__(self):
super(network, self).__init__()
self.batch = 16
self.T_length = 15
self.conv = nn.Conv2d(3, 128, 3, 1, 1)
self.cls = nn.Linear(128*5*5, 2)
def forward(self, Input):
# Input has size [batch * time_length, 3, 224, 224]
out = self.conv(Input) # [batch * time_length, 128, 28, 28]
out = out.view(batch_size * time_length, -1)
score = self.cls(out)
score = score.view(time_length, batch_size, -1)
# score for single video is the average over all frames
score = torch.mean(score, dim=1)
return score
class network2(nn.Module):
def __init__(self):
super(network2, self).__init__()
self.batch = 16
self.T_length = 15
self.conv = nn.Conv2d(3, 128, 3, 1, 1)
self.cls = nn.Linear(128*5*5, 2)
def forward(self, Input):
# Input has size [time_length, batch, 3, 224, 224]
score = []
for x in Input:
#x = Input[torch.tensor([i]).long()]
score.append(self.cls(self.conv(x).view(batch_size, -1)))
# concate list or tensor to new tensor
score = torch.stack(score, dim=0) # [ batch, time_length, num_class]
# average over time axis
score = torch.mean(score, dim=1)
return score
batch_size = 5
time_length = 10
x = torch.randn(time_length, batch_size, 3, 5, 5)
modelA = network()
modelB = network2()
modelB.load_state_dict(modelA.state_dict())
outputA = modelA(x.view(time_length*batch_size, *x.size()[2:]))
outputB = modelB(x)
outputA.mean().backward()
outputB.mean().backward()
print(torch.allclose(outputA, outputB))
print(torch.allclose(modelA.conv.weight.grad, modelB.conv.weight.grad))
print(torch.allclose(modelA.cls.weight.grad, modelB.cls.weight.grad))
Note that you might get a False in the comparisons sometimes, although the tests should pass most of the time. This is due to floating point precision and can most likely be ignored.
|
st98183
|
Great appreciate for your response. Now I figure it out better !
I should have mentioned that above code is not strictly right. I wrote them just to illurstrate the idea. Sorry for the bother.
Best.
|
st98184
|
how to print output shape of each layer or the structure of model built ?
such as model.summary in Keras.
|
st98185
|
You can generate a graph representation of the network using something like visualize 1.3k, as illustrated in this notebook 1.6k.
For printing the sizes, you can manually add a print(output.size()) statement after each operation in your code, and it will print the size for you.
|
st98186
|
Yes, you can get exact Keras representation, using this code 1.4k.
Example for VGG16
from torchvision import models
from summary import summary
vgg = models.vgg16()
summary(vgg, (3, 224, 224))
----------------------------------------------------------------
Layer (type) Output Shpae Param #
================================================================
Conv2d-1 [-1, 64, 224, 224] 1792
ReLU-2 [-1, 64, 224, 224] 0
Conv2d-3 [-1, 64, 224, 224] 36928
ReLU-4 [-1, 64, 224, 224] 0
MaxPool2d-5 [-1, 64, 112, 112] 0
Conv2d-6 [-1, 128, 112, 112] 73856
ReLU-7 [-1, 128, 112, 112] 0
Conv2d-8 [-1, 128, 112, 112] 147584
ReLU-9 [-1, 128, 112, 112] 0
MaxPool2d-10 [-1, 128, 56, 56] 0
Conv2d-11 [-1, 256, 56, 56] 295168
ReLU-12 [-1, 256, 56, 56] 0
Conv2d-13 [-1, 256, 56, 56] 590080
ReLU-14 [-1, 256, 56, 56] 0
Conv2d-15 [-1, 256, 56, 56] 590080
ReLU-16 [-1, 256, 56, 56] 0
MaxPool2d-17 [-1, 256, 28, 28] 0
Conv2d-18 [-1, 512, 28, 28] 1180160
ReLU-19 [-1, 512, 28, 28] 0
Conv2d-20 [-1, 512, 28, 28] 2359808
ReLU-21 [-1, 512, 28, 28] 0
Conv2d-22 [-1, 512, 28, 28] 2359808
ReLU-23 [-1, 512, 28, 28] 0
MaxPool2d-24 [-1, 512, 14, 14] 0
Conv2d-25 [-1, 512, 14, 14] 2359808
ReLU-26 [-1, 512, 14, 14] 0
Conv2d-27 [-1, 512, 14, 14] 2359808
ReLU-28 [-1, 512, 14, 14] 0
Conv2d-29 [-1, 512, 14, 14] 2359808
ReLU-30 [-1, 512, 14, 14] 0
MaxPool2d-31 [-1, 512, 7, 7] 0
Linear-32 [-1, 4096] 102764544
ReLU-33 [-1, 4096] 0
Dropout-34 [-1, 4096] 0
Linear-35 [-1, 4096] 16781312
ReLU-36 [-1, 4096] 0
Dropout-37 [-1, 4096] 0
Linear-38 [-1, 1000] 4097000
================================================================
Total params: 138357544
Trainable params: 138357544
Non-trainable params: 0
----------------------------------------------------------------
|
st98187
|
I write a Flask + Pytorch code, try to do a prediction with pre-trained model on the server. But I met some problem when installing the dependency:
I initially used the following commands to install PyTorch in the “lib” folder.:
pip install -t lib http://download.pytorch.org/whl/cu80/torch-0.3.1-cp27-cp27mu-linux_x86_64.whl
pip install -t lib torchvision
But when I run the code in a virtual environment, the error shows:
import torch._dl as _dl_flags
File "/home/yifang/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/sandbox.py", line 1093, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named torch._dl
Everything works fine if I run the PyTorch Program locally.
So does anyone have experience in deploying PyTorch model on Google Cloud or any other server?
|
st98188
|
I notice that I get different results when I use DataParallel compared to a single GPU run. When I execute the same code on 1 GPU, I get the same loss if I repeat that procedure (assuming a fixed random seed). For some reason though, the loss is ~5% different if I use DataParallel. Is that a bug or some design-workaround that is a consequence of summing up the gradients?
|
st98189
|
Solved by ptrblck in post #2
I think the difference might come from the gradient reduction of all device gradients after the backward pass.
Here is an overview of the DataParallel algorithm.
Unfortunately, I can’t test it right now, but from my understanding after the parallel_apply of model’s backward pass, the gradients wil…
|
st98190
|
I think the difference might come from the gradient reduction of all device gradients after the backward pass.
Here 131 is an overview of the DataParallel algorithm.
Unfortunately, I can’t test it right now, but from my understanding after the parallel_apply of model’s backward pass, the gradients will be reduced and thus accumulated on the default device.
In a general sense, you are using a larger batch size for the same model, which also might change the training behavior. While the parameters of the model are usually updated after each batch iteration, you are using the same parameters for multiple batches (on the different GPU).
Let me know, if that makes sense or if I’m completely mistaken.
As I can’t test it right now, please take this statement with a grain of salt!
|
st98191
|
Thanks a lot for the clarification. Yeah that makes sense, because like you say, it’s not like k “regular” batch updated, but we essentially aggregate the results from the k GPUs before we apply the update.
On the other hand, if I choose a 4-times larger batch size compared to the 1 GPU version, I thought the results are the same, because each GPU would compute the predictions separately, but then the default device would combine the loss of the combined batches to compute the gradient. (but the downside would then be that there couldn’t be an efficient backward pass leveraging parallelism)
From the post you link (Debugging DataParallel, no speedup and uneven memory allocation 9),
in forward:
scatter mini-batch to GPU1, GPU2
replicate model on GPU2 (it is already on GPU1)
model_gpu1(input_gpu1), model_gpu2(input_gpu2) (this step is parallel_apply)
gather output mini-batch from GPU1, GPU2 onto GPU1
in backward:
scatter grad_output and input
parallel_apply model’s backward pass
reduce GPU2 replica’s gradients onto GPU1 model
Why do we need to “gather output mini-batch from GPU1, GPU2 onto GPU1” as the last step of the forward pass? If each GPU has its own gradient (computed based on the scattered mini-batch), this shouldn’t be necessary, right?
|
st98192
|
That reason for this is the loss calculation which will take place on the default device.
As a small side note, this is also the reason you see a bit more memory consumption on one device.
You could skip it by adding your loss directly into your model and calculate the losses on each replica.
Then only the (scalar) loss value has to be reduced.
@albanD created a small example here 37.
|
st98193
|
You could skip it by adding your loss directly into your model and calculate the losses on each replica.
ohhh, I see now. This is basically because the dataset (labels) sit on the first device. It’s not a design choice but rather a consequence of where I put the loss function (or rather the inputs for the loss function in terms of the labels). Makes so much sense now. Thanks!
|
st98194
|
Just wanted to leave a note regarding Batchnorm. The running stats might differ too in case of multi gpu usage instead of single gpu.
github.com/pytorch/pytorch
Issue: Synchronize Batch Norm across Multi GPUs 50
opened by ycszen
on 2017-08-31
I find in some tasks , for example, semantic segmentation, detection, sync batch norm is crucial for performance.In these tasks, batch...
medium priority
|
st98195
|
Hello !
I am issue, that whenever I run any model it takes very less memory like 1.3 gb out of 6 gb ( GTX 1060 ), but volatile gpu utility is 100 %. Please tell me why my laptop is hanging even I have 5 GB of free memory.
Screenshot from 2018-11-03 22-12-52.png790×340 38.6 KB
Thanks
|
st98196
|
How many worker threads do you use with your dataloader? Can you try to reduce the num workers?
Have you stored the data in the internal hard drive or external one?
|
st98197
|
There ir quite expensive AutoML for Tensorflow, there is Auto-Keras for Keras/Tensorflow/etc. But what about automated ML for PyTorch? I have not heard about completed framework, but maybe there are some ongoing efforts to create such automated ML and maybe I can join? It would not be nice to start from scratch. And I don’t see future for PyTorch if not automated ML is supported.
Currently I am using PyTorch, because AllenNLP uses it and there are good libraries - neuron functions, gradiens, optimizers and so on. So - I hope that there are efforts in progress and that there will be future for PyTorch and it is wise to invest in PyTorch. Thanks.
And if there is no such effort, so - why there is no one? Maybe I can start such project but what obstacles and hardships should I take into account?
|
st98198
|
After reading the documentation for Tensor.view,
https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view 2.6k
it seems like it could be used to swap two dimension in a tensor, but this is not the case:
a=torch.randn((1,2,3,4))
# Swap 2nd and 3rd dimensions using split and stack
b = torch.stack(a.split(1, 1), 3).squeeze(1) # has shape (1, 3, 2, 4)
# Swap 2nd and 3rd dimensions using tensor.view
c = a.view((1, 3, 2, 4)) # has shape (1, 3, 2, 4)
(b == c).all() # False
Am I misunderstanding the documentation? What exactly does tensor.view() do in the example above?
|
st98199
|
It’s a bit tricky for me to explain it in words, but it does not directly swap two dimensions but rearranges the values so that it adheres to the new dimensions. Maybe the easiest way to explain it would be with an analogy like transpose. I.e.,
a = torch.tensor([[1, 2, 3],
[4, 5, 6]])
a.view(3, 2)
# tensor([[ 1, 2],
# [ 3, 4],
# [ 5, 6]])
but
a.transpose(0, 1)
# tensor([[ 1, 4],
# [ 2, 5],
# [ 3, 6]])
Or maybe think of it as creating a new empty tensor with the new dimensions specified via the view arguments and then gradually filling it in order using the original values.
|
st98200
|
So reshape from numpy is the same as view from torch?
Yes, that’s correct. View is maybe even a bit more clear, because it’s just changing the view onto that array, not the way how it is laid out in memory (in both cases, NumPy and PyTorch).
|
st98201
|
I have encountered many times the error about the incompatibility of DoubleTensor and FloatTensor. I am wondering why does PyTorch distinguish these two types of Tensors?
|
st98202
|
DoubleTensor is 64-bit floating point and FloatTensor is 32-bit floating point number. So a FloatTensor uses half of the memory as a same sizeDoubleTensor uses. Also GPU and CPU can compute higher number operations if numbers have less precision. However DoubleTensor have higher precision, if thats what you need. So Pytorch leaves it to user to choose which one to use.
If you are asking why we can not use them together, like lists in the python, again it is because of performance. Also it would be so much harder to support GPU backend.
You can read about double vs float 370 or
|
st98203
|
@enisberk clearly gives the distinction between the two. However is this question, why does Pytorch not perform automatic typecasting? To give more control. I suppose you know how to solve these errors, else you may check This page 145.
|
st98204
|
While an automatic typecast might be convenient in some situations, it might introduce silent errors, e.g. in setups working with mixed precision.
In my personal opinion I like to get an error and fix a type cast manually, but maybe there are some use cases where it might make sense to cast automatically.
|
st98205
|
Hello, I am trying to create an LSTM to learn on toy data that is similar to some data I want to train on. My code runs, but the network does not update itself and does not learn the labels. This is a binary classification problem, so I am storing my labels (0/1) in a tensor of size (num_datapts x 1) and my inputs are in a tensor of size (num_datapts x 3). Here is the complete code:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
INPUT_SIZE = 3
HIDDEN_SIZE = 3
OUTPUT_SIZE = 1 # why 2?
class MyLSTM(nn.Module):
def __init__(self, input_dim, hidden_dim, output_size):
super(MyLSTM, self).__init__()
self.hidden_dim = hidden_dim
# The LSTM takes word embeddings as inputs, and outputs hidden states
# with dimensionality hidden_dim.
self.lstm = nn.LSTM(input_dim, hidden_dim)
# The linear layer that maps from hidden state space to tag space
self.fc1 = nn.Linear(hidden_dim, output_size)
self.hidden = self.init_hidden()
def init_hidden(self):
# Before we've done anything, we dont have any hidden state.
# Refer to the Pytorch documentation to see exactly
# why they have this dimensionality.
# The axes semantics are (num_layers, minibatch_size, hidden_dim)
return (torch.zeros(1, 1, self.hidden_dim), # hx & cx
torch.zeros(1, 1, self.hidden_dim))
def forward(self, input):
lstm_out, self.hidden = self.lstm(input, self.hidden)
tag_space = self.fc1(lstm_out.view(len(input), -1))
# F.log_softmax applies softmax activation function on outputs
# Take the log because we're going to define the loss function as NLL and it expects that
tag_scores = F.softmax(tag_space, dim=0)
return tag_scores
# Make some input data
inputs = [torch.randn(1, 3), torch.randn(1, 3), torch.randn(1, 3)] # for _ in range(5)] # make a sequence of length 5
#targets = [torch.ones(1,3, dtype=torch.int64), torch.ones(1,3, dtype=torch.int64), torch.ones(1,3, dtype=torch.int64)]
#targets = torch.tensor([[1], [1], [1]], dtype=torch.float32) #torch.tensor([[0], [0], [1]])
# Add the extra 2nd dimension
# Cat concatenates the list of 3 1x3 tensors into one 3x3 tensor.
# View changes the dimensions of the tensor while preserving the data. -1 infers the size from other dimensions.
# This goes 3*(1 x 3) -> (3 x 3) -> (3 x 1 x 3)
inputs = torch.cat(inputs).view(len(inputs), 1, -1)
targets = torch.tensor([0, 0, 0], dtype=torch.float32) #torch.cat(targets)#.view(len(targets), 1, -1)
print targets.dim()
# Train the model
model = MyLSTM(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE)
loss_function = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)
# See what the scores are before training
# Note that element i,j of the output is the score for tag j for word i.
# Here we don't need to train, so the code is wrapped in torch.no_grad()
with torch.no_grad():
tag_scores = model(inputs)
print(tag_scores)
for epoch in range(300): # again, normally you would NOT do 300 epochs, it is toy data
# Step 1. Remember that Pytorch accumulates gradients.
# We need to clear them out before each instance
model.zero_grad()
# Also, we need to clear out the hidden state of the LSTM,
# detaching it from its history on the last instance.
model.hidden = model.init_hidden()
# Step 2. Run our forward pass.
tag_scores = model(inputs)
# Step 3. Compute the loss, gradients, and update the parameters by
# calling optimizer.step()
loss = loss_function(tag_scores, targets)
print tag_scores
print loss
loss.backward()
optimizer.step()
with torch.no_grad():
tag_scores = model(inputs)
print(tag_scores)
Can anyone tell me what is going on?
|
st98206
|
is there any way to make this faster by using library function?
Please help me with this…
It uses three tensor
input= tensor with size(minibatch,3,Height+51,Width+51)
gradoutput= tensor with size(minibatch,3, Height, Width)
kernel =tensor with size(minibatch,51, Height, Width)
grad=new tensor with size(minibatch,3, Height, Width)
for n in range(minibatch):
for i in range(Height):
for j in range(Width):
for k in range(3):
gradcal=[0,0,0]
for c in range(3):
for l in range(51):
gradcal[c]=gradcal[c]+kernel[n,l,i,j]*input[n,c,i+l,j+25]*gradoutput[n,c,i,j]
grad[n,k,i,j]=gradcal[0]+gradcal[1]+gradcal[2]
|
st98207
|
I had cudnn and CUDA installed on my linux. CUDA version 9.0, cudnn 7.0.5. But when I open a python console and call torch.cuda.is_available(), the terminal freezes immediately. Any ideas why?
|
st98208
|
Try checking for CUDA through tensorflow. Does this happen there as as well? Also, try running this statement elsewhere like ipython.
|
st98209
|
I am curious why giving wrong size of argument crashes all cuda behavior, instead of throwing only simple size error?
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
embedding = nn.Embedding(10, 3).cuda()
input = torch.LongTensor([[1,2,4,5],[4,3,2,9]]).cuda()
embedding(input) # works fine
e1 = nn.Embedding(4,3).cuda() # has input_dim of 4
# following line does not trigger any error for now
torch.Tensor(torch.randn(4,3)).cuda()
#suppose I forgot my embedding dimensions and called e1 with wrong input
e1(input) # It won't work, as expected with the following error:
RuntimeError: cuda runtime error (59) : device-side assert triggered at /opt/conda/conda-bld/pytorch_1535493744281/work/aten/src/THC/generic/THCTensorCopy.cpp:20
# when I tried the following initialization why do I get the same RuntimeError?
torch.Tensor(torch.randn(4,3)).cuda()
|
st98210
|
Exception ignored in: <bound method _DataLoaderIter.__del__ of <torch.utils.data.dataloader._DataLoaderIter object at 0x7f70a2d065f8>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 399, in __del__
self._shutdown_workers()
File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 378, in _shutdown_workers
self.worker_result_queue.get()
File "/usr/lib/python3.5/multiprocessing/queues.py", line 345, in get
return ForkingPickler.loads(res)
File "/usr/local/lib/python3.5/dist-packages/torch/multiprocessing/reductions.py", line 151, in rebuild_storage_fd
fd = df.detach()
File "/usr/lib/python3.5/multiprocessing/resource_sharer.py", line 57, in detach
with _resource_sharer.get_connection(self._id) as conn:
File "/usr/lib/python3.5/multiprocessing/resource_sharer.py", line 87, in get_connection
c = Client(address, authkey=process.current_process().authkey)
File "/usr/lib/python3.5/multiprocessing/connection.py", line 493, in Client
answer_challenge(c, authkey)
File "/usr/lib/python3.5/multiprocessing/connection.py", line 737, in answer_challenge
response = connection.recv_bytes(256) # reject large message
File "/usr/lib/python3.5/multiprocessing/connection.py", line 216, in recv_bytes
buf = self._recv_bytes(maxlength)
File "/usr/lib/python3.5/multiprocessing/connection.py", line 407, in _recv_bytes
buf = self._recv(4)
File "/usr/lib/python3.5/multiprocessing/connection.py", line 379, in _recv
chunk = read(handle, remaining)
ConnectionResetError: [Errno 104] Connection reset by peer
My settings :
Pytorch 0.4.1
num_workers = 8
I think this error doesn’t effect on training but too much noisy.
but can I fix this ?
|
st98211
|
Either I do not understand the rationale for the pad input order or there’s a flip.
As I understand the input to pad would be (height_0, height_k, width_0, width_k), H&W ordered just like torch.Tensor. But that’s not what I see.
version: ‘0.4.1.post2’
zero = torch.zeros(1,1,4,3)
cpad = nn.ConstantPad2d([0,2,0,0], -1)
padded = cpad(zero)
print(padded.size())
I would expect my result to be padded by 2 in the Height dimension, ie. size = (1,1,6,3) but I get
torch.Size([1, 1, 4, 5])
perhaps clearer example
zero = torch.zeros(1,1,4,3)
cpad = nn.ConstantPad2d([2,2,0,0], -1)
padded = cpad(zero)
print(padded.size())
Returns
torch.Size([1, 1, 4, 7])
thank you
|
st98212
|
The input to the padding layer is defined as [left, right, top, bottom]:
padding ( int , tuple ) – the size of the padding. If is int, uses the same padding in all boundaries. If a 4-tuple, uses (paddingLeft, paddingRight, paddingTop, paddingBottom)
In your case you are setting the padding to right (left + right in the second example), to that your width will be increased.
|
st98213
|
Yes, I see that - IMO if tensors are defined as NCHW, padding ought to be defined as [top, bottom, left, right]. Unless theres a reason in cuda why this is useful, I dont see how it makes sense.
A simple use case, I subtract one tensor by another tensor; then use the values to pad the smaller tensor; to use that information in my padding I have to flip the order. As said. I dont understand the rational. Ok, so no bug but odd design.
|
st98214
|
Hi all!
I got an error like this
Traceback (most recent call last):
File “DeepCoral.py”, line 115, in
model = load_pretrain(model)
File “DeepCoral.py”, line 48, in load_pretrain
model_dict[k] = pretrained_dict[k[k.find(".") + 1:]]
KeyError: ‘bn1.num_batches_tracked’
when I tried to load a pre-trained ResNet model from pytorch “https://download.pytorch.org/models/resnet50-19c8e357.pth 27”
My loading function for the pre-trained model is:
def load_pretrain(model):
url = ‘https://download.pytorch.org/models/resnet50-19c8e357.pth 27’
pretrained_dict = model_zoo.load_url(url)
model_dict = model.state_dict()
for k, v in model_dict.items():
if not “cls_fc” in k:
model_dict[k] = pretrained_dict[k[k.find(".") + 1:]]
model.load_state_dict(model_dict)
return model
Could anyone please to help me?
|
st98215
|
jingjing:
num_batches_tracked
This is newly added, so it is in your new state_dict, but not in the downloaded one. We have code to handle this if you are just using load_state_dict on the downloaded one. However, since you are looking keys up in the old state_dict basing on the new state_dict, it won’t work. You could safely skip those.
|
st98216
|
Thank you Simon. I just noticed that I wrote my per-train code in 0.3.1 style, but run with 0.4.1.
|
st98217
|
Hi,
I have the best model trained on my dataset and have the validation error and record the true positive list of validation data at the end.
Then, I use the trained model in inference code and use validation set (instead on test set) to see if I get same true positive list. But I don’t! Some of true positives are missed.
What would be the problem? The model is not perfectly stable.
|
st98218
|
Did you make sure to call model.eval() before the evaluation step?
This will make sure to set all modules to eval, e.g. nn.Dropout won’t drop units and nn.BatchNorm will use the running estimates instead of the batch statistics.
|
st98219
|
Hi,
I am currently looking into getting the BERT architecture to run on GPUs. By the nature of the very long sequences (2200 chars) in my target Dataset even the small model cant fit a singular batch into 16GB memory.
for this reason I split up the transformer blocks onto 2 different GPUs, which actually works quite well.
Would it be possible to combine this approach with Data Parallelism a la nn.DataParallel()? Ideally I would like to have 4 groups of 2 gpus calculating in parallel
|
st98220
|
Have a look at this example 82, where I’ve created a small example using model sharding and nn.DataParallel.
|
st98221
|
Cloned pythourch from starts .CMake Build All in VS 2017
Everything else seems to be installed as by installation guide…
Failing on install Caffe 2…
Caffe 2 You changed the size of TensorImpl on 64-bit arch.See Note [TensorImpl size constraints] on how to proceed.
I have 16 GB RAM
Is it about memory?
How can I solve this?
|
st98222
|
at
D:\dev\ML\pytorch\aten\src\ATen\core\TensorImpl.h
line 1408
// Note [TensorImpl size constraints]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Changed the size of TensorImpl? If the size went down, good for
// you! Adjust the documentation below and the expected size.
// Did it go up? Read on…
//
// Struct size matters. In some production systems at Facebook, we have
// 400M live tensors during a training run. Do the math: every 64-bit
// word you add to Tensor is an extra 3.2 gigabytes in RAM.
//
// If you are a Facebook employee, you can check if the run in question
// has tipped you over the point using the command here:
// https://fburl.com/q5enpv98 4
//
// For reference, we OOMed at 160 bytes (20 words) per TensorImpl.
// This is not counting overhead from strides out-of-line allocation, and
// StorageImpl space. We’re currently comfortably under this number;
// let’s keep it that way. (One currently approved pending size
// increase is inlining sizes and strides as small vectors, to reduce
// dynamic allocations.)
//
// Our memory usage on 32-bit systems is suboptimal, but we’re not checking
// for it at the moment (to help avoid rage inducing cycles when the
// 32-bit number is wrong).
//
// Current breakdown:
//
// vtable pointer
// strong refcount TODO: pack these into one word
// weak refcount
// storage pointer
// sizes vector (start)
// sizes vector (end)
// sizes vector (reserved) TODO: get rid of me
// strides pointer
// storage offset
// numel
// data type pointer
// miscellaneous bitfield
//
static_assert(sizeof(void*) != sizeof(int64_t) || // if 64-bit…
sizeof(TensorImpl) == sizeof(int64_t) * 12,
“You changed the size of TensorImpl on 64-bit arch.”
“See Note [TensorImpl size constraints] on how to proceed.”);
} // namespace at
|
st98223
|
Saying that I have a layer feature map output of the form (1,1,10,10) how can I transform it to (4,1,5,5), while keeping the spatial location as a kernel of 5x5 as mentioned in the image bellow and preserving the gradient ?
HisTrans.png903×396 3.89 KB
As you can see, the features are moved to form new inputs in the input channel.
|
st98224
|
Why don’t you just slice the tensor and then stack it?
Something like:
orange = X[0,:,:X.size(2)//2,:X.size(3)//2]
blue = X[0,:,:X.size(2)//2,X.size(3)//2:]
grey = X[0,:,X.size(2)//2:,:X.size(3)//2]
green = X[0,:,X.size(2)//2:,X.size(3)//2:]
output = torch.stack([orange,blue,grey,green])
This should preserve the gradients I believe.
|
st98225
|
this could work if I have only one input what if I have (4,1,10,10) to be (16,1,5,5) or what if I have (4,1,20,20) to be (64,1,5,5) ? I’m looking for an automatic function that takes a kernel of 5 by 5 and stake it in the first channel of the tensor
|
st98226
|
You could adapt the slicing method to any size just by putting it in a for loop or calling it recursively. You could also do it with a “kernel” by using a a 2d Convolution with weights set to the identity, and then reshape them to be a square again. This method I’d say is a bit more tricky, and you’d need to work out the correct stride sizes for the convolution.
|
st98227
|
Making a loop in a large input image is very costly process. Could you elaborate more please about using a 2d conv?
|
st98228
|
So a convolution2d operator is essentially a simple matrix multiplication over a flattened patch of an image. If your entire image is [b,1,10,10] and you choose convolution with kernel W of size (5,5) with output size (d) and with stride=5, it will do the following 4 operations, say the output is O of size [b,d,2,2]:
O[b_i,0:d,0,0] = W * X[b_i,:,:5,:5].view(1*5*5) where W is size (d,1x5x5)
O[b_i,0:d,0,1] = W * X[b_i,:,:5,5:].view(1*5*5)
etc.
So if you set output dimension to same as input dimension (d = 1x5x5) and set it to Identity matrix it will preserve all the information. And you can then reshape it back into (5,5) and have the same image.
So your output O is of size (b,1x5x5,2,2). Flatten last two dimensions -> (b,5x5,4). Then transpose -> (b,4,5x5). Then reshape again -> (b,4,5,5), and voila.
But slicing much less confusing, not sure about the speed of this vs the for loop with slicing.
|
st98229
|
I am a freshman in pytorch, and I want to know whether the two method below equal to each other.
batch size == 2 and the loss is calculated by the model, then call loss.backwards.
batch size == 1 and the loss is calculated every two step, then call loss.backwards.
|
st98230
|
The network usually accept any number of element in the batch and the loss functions average over the batch size.
So if you use a batch_size of 2 and backward or if you do twice batch size of 1 and backward each of them. You will be off by a factor of 2: the first one took the average while the second one took the sum.
|
st98231
|
Thank you very much! it did help me a lot. Now I can solve the problem without any worries then.
|
st98232
|
I have NVIDIA Quadro P5000 with Windows 7, installed pytorch 0.4 with cuda 9.1.
I am using jupyter notebook to run pytorch codes.
torch.cuda.is_available()
is True
But when I run the code
while True:
torch.randn(2, 2).cuda() + torch.randn(2, 2).cuda()
There is no GPU utilisation. My nvidia-smi indicates
GPU PID TYPE Process name GPU Memory Usage
0 3019 C /home/anaconda3/bin/python N/A
Would appreciate if you can provide help, thanks!
|
st98233
|
Your workload is really small, so that you won’t notice any GPU utilization.
Try it again with a bigger size, e.g. torch.randn(2000, 2000).
|
st98234
|
I have an Ubuntu with GTX1050 and I tried the same code, and the Memory usage is not N/A. Is it possible that I have installed the wrong cuda version on the Windows environment?
|
st98235
|
Maybe I misunderstood the term utilization. Are you referring to the allocated GPU memory or the utilization of the GPU, i.e. in terms of computation?
After the first CUDA call, your GPU should have some used memory. Could you check it on your Windows machine with print(torch.cuda.memory_allocated())?
|
st98236
|
Sorry, I mean both GPU memory allocation and GPU utilization are N/A. Is it due to wrong driver installed?
Previously I installed pytorch 0.4.1 with cuda 9.2, and cuda.is_available() is False.
Should I try pytorch 0.4.0 with cuda 9.0?
|
st98237
|
Did PyTorch work with the GPU on Windows before?
It looks like a wrong driver might be the issue, but I’m really not familiar with Windows.
Which driver version are you currently using?
|
st98238
|
This is my first time installing PyTorch on Windows.
I tried PyTorch 0.4.0 with cuda 8.0, this time there is GPU utilisation but still N/A for memory allocation. At dataloader has issues.
PyTorch 0.4.1 with cuda 9.2 has N/A for both GPU utilisation and memory allocation, but seems to work ok for CPU.
PyTorch 0.4.1 with cuda 9.0 does not detect GPU.
I will try Pytorch 0.4.1 with cuda 9.2
|
st98239
|
I tried PyTorch 0.4.1, Nvidia Quadro P5000 Driver R396 U2 (397.93), with cuda 9.2.
torch.cuda.is_available()
is True
But I still face the problem of N/A for both GPU utilisation and memory allocation. Does this mean PyTorch cuda is not supported in Windows?
|
st98240
|
PyTorch supports CUDA on Windows.
Since I’m not really familiar with Windows, maybe @peterjc123 could help out, who developed some PyTorch version for Windows.
|
st98241
|
Sorry, I don’t know what you mean utilization. Do you mean that the python process doesn’t appear in the processes section of the nvidia-smi output? What error did you meet at the Python side?
|
st98242
|
Sorry for the confusion, what I mean is the GPU is not used at all when I train a neural network model using PyTorch.
From the post that you provided, my understanding is Tensorflow still uses GPU although nvidia-smi states otherwise.
For PyTorch, when I set device to “cpu”, a batch run of 10k data samples took 2 mins, but when I set device to “gpu”, the same batch run took 17 mins, although torch.cuda.is_available() is True
When I run nvidia-smi while training the neural network, it shows the GPU-Util is ~0% and GPU Memory is N/A.
|
st98243
|
I think that there may be some problem with your CUDA installation. I’d suggest you remove all the related things like CUDA, Nvidia GPU drivers and also the PyTorch libraries first and then install them back.
|
st98244
|
When I serialized my module, the instance’s dimension I passed to it was (4, 9, 32, 32), which ‘4’ represented batch size.
After I loaded it in C environment, I found I could only forward a tensor’s dimension exactly the (4, 9, 32, 32).
So is there any way I could forward an arbitrary batch size tensor in C environment.
Besides, originally the input size was (4, 1, 9, 32, 32), but it couldn’t work, so I changed it to (4, 9, 32, 32) and worked. So does it means that the torchscript module loaded in c++ can only forward a 4 dimension tensor?
|
st98245
|
I want to cast a tensor from torch.FloatTensor to torch.DoubleTensor
First I create a tensor:
pnts = [503.566484,512.937416,507.566474,557.514461,516.105827,550.315139,519.150589,517.935416]
pnts =array(pnts)
pnts =pnts.reshape((4, 2))
flow = tensor(pnts)
Then try casting to DoubleTensor:
flow=flow.double()
type(flow)
>>torch.Tensor
Try again:
flow=flow.type(torch.DoubleTensor)
type(flow)
>>torch.Tensor
|
st98246
|
Solved by wwiiiii in post #2
Use t.type() instead of type(t).
|
st98247
|
Hello!
I’m working on making a inspector which examines each tensor, or nn.Module’s gpu/cpu memory resource consumption. (since nvidia-smi only shows total consumption)
Is there any built-in pytorch method to achieve this goal?
Thanks!
|
st98248
|
How pytorch releases variable garbage?
Two methods which I frequently use for debugging:
By @smth
def memReport():
for obj in gc.get_objects():
if torch.is_tensor(obj):
print(type(obj), obj.size())
def cpuStats():
print(sys.version)
print(psutil.cpu_percent())
print(psutil.virtual_memory()) # physical memory usage
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0] / 2. ** 30 # memory use in GB...I think
print('memory GB:',…
|
st98249
|
Hi Smth, running a very basic code on pytorch to learn about the memory usage. But the following error pops up. Any suggestions would be helpful
OSError Traceback (most recent call last)
in ()
1 cpuStats()
----> 2 memReport()
in memReport()
1 def memReport():
2 for obj in gc.get_objects():
----> 3 if torch.is_tensor(obj) or (hasattr(obj, ‘data’) and torch.is_tensor(obj.data)):
4 print(type(obj), obj.size())
5
/usr/lib/python3.6/ctypes/init.py in getattr(self, name)
416 if name[0] == ‘_’:
417 raise AttributeError(name)
–> 418 dll = self._dlltype(name)
419 setattr(self, name, dll)
420 return dll
/usr/lib/python3.6/ctypes/init.py in init(self, name, mode, handle, use_errno, use_last_error)
346
347 if handle is None:
–> 348 self._handle = _dlopen(self._name, mode)
349 else:
350 self._handle = handle
OSError: data: cannot open shared object file: No such file or directory
|
st98250
|
Hi all,
I’m suffering from the hugh bandwidth requirement when I train my model in multiple nodes, so considering to apply this 3. However, I have no idea that what part of the pytorch code I have to replace. I guess that I need to make another torch.distributed.reduce_op to replace torch.distributed.reduce_op.SUM, but I couldn’t find any guideline to implement another operator from official docs or tutorials. Could you let me know what part of pytorch code I have to refer to?
Thanks,
Jinserk
|
st98251
|
I went through paper quickly so correct me if I am wrong. They are not implementing a network communication process, they are not implementing a new communication semantic, they are pre-processing gradients before reducing them. If you are using DistributedDataParallel, you can pre-process gradients before doing backward propagation. If you want to also change distribution behavior like skipping gradient sharing every two epoch etc., you can implement DistributedDataParallel yourself by following distributed tutorial 3 with operations like torch.distributed.reduce_op.
|
st98252
|
Thanks for quick and kind reply @enisberk! I wonder that if I use DistributedDataParallel, it performs all_reduce automatically or not? I asked the same question here but want to ask here again and will remove the thread if it is clarified.
|
st98253
|
Are you asking if you need to call something like that:
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM)
to be able to use DistributedDataParallel ?
No, you do not need to. You can see imagenet example 1
|
st98254
|
Thanks for clarifying. Then how can I pickup only big gradients to make them sparse, as the paper proposed, if the DistributedDataParallel controls all I/O internally?
|
st98255
|
I think so, it is handling IO internally Docs 1
Check out the tutorial 2 to see how Arnold implementing it, so you can use it to modify gradient before reducing them.
|
st98256
|
I scraped a few images. However, a lot of them are GIF and octet-stream. It seems the ‘ImageFolder’ directly ignores those kind of images. For example, the image_datasets below only has 2 data points as there are only 2 jpg images in this folder and the others are GIF or octet-stream.
image_datasets = datasets.ImageFolder(os.path.join(data_dir, validation)
Number of datapoints: 2
Is there any more general way to read the image files.
|
st98257
|
The most flexible way to load your data would be to write your own Dataset.
Basically you just have to worry about three functions:
__init__: here you have to pass your data or paths to your data, if you want to lazily load it. Also you can define transformations here, which should be applied on your data (and target).
__getitem__: here you have to implement your logic to load your data. E.g. in case you’ve passed paths to your Dataset, you can get the current path using index and use whatever library you want to load a single sample.
__len__: returns the length of your Dataset.
Here is a small example:
from PIL import Image
from torch.utils.data import Dataset, DataLoader
class MyDataset(Dataset):
def __init__(self, gif_paths):
self.paths = gif_paths
def __getitem__(self, index):
x = Image.open(self.paths[index])
# Convert the gif here to frames, etc.
...
return x
def __len__(self):
return len(self.paths)
gif_paths = ['./a.gif', './b.gif']
dataset = MyDataset(gif_paths)
loader = DataLoader(
dataset,
batch_size=10,
num_workers=2,
shuffle=True
)
|
st98258
|
Hi ptrblck
Thanks for your reply. I would like to utilize the existing functionality of the original ImageFolder dataset as much as I can so that I can easily read labels and apply torchvision.transforms later on.
I look at the source code of ImageFolder 7. The main problem is that there is a parameter called 'IMG_EXTENSIONS which lists the extensions wth which the file will be loaded by the default image loader. Any file with an extension not listed in this list will be ignored during loading.
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
Is there any way I can just reset this parameter and reserve the other functionality of the ‘ImageFolder’ class?
|
st98259
|
You could use DatasetFolder and provide the extensions yourself.
Also, you might want to provide the loader to load and process the .GIF files, and return a sample.
|
st98260
|
Hi ptrblck
Thanks for your suggestion. I implemented a customized DatasetFolder. However, I run into an issue reported here Iterate through customized DatasetFolder does not work 12
Do you have suggestion?
Best
|
st98261
|
Hi, I’m new in pytorch…
how can I save only part of the model?
I train model that for training has 3 output but for inference, I just need one of the outputs
can I load the model and save just the part I need?
that would save time in the inference
has some have an example?
Thanks
|
st98262
|
Solved by ptrblck in post #2
I would save the whole model’s state_dict and just reimplement an “inference” model, which yields only one output. Here is a small example:
class MyModelA(nn.Module):
def __init__(self):
super(MyModelA, self).__init__()
self.fc1 = nn.Linear(10, 1)
self.fc2 = nn.Linear(1…
|
st98263
|
I would save the whole model’s state_dict and just reimplement an “inference” model, which yields only one output. Here is a small example:
class MyModelA(nn.Module):
def __init__(self):
super(MyModelA, self).__init__()
self.fc1 = nn.Linear(10, 1)
self.fc2 = nn.Linear(10, 1)
self.fc3 = nn.Linear(10, 1)
def forward(self, x):
x1 = self.fc1(x)
x2 = self.fc2(x)
x3 = self.fc3(x)
return x1, x2, x3
# Train modelA
modelA = MyModelA()
x = torch.randn(1, 10)
output1, output2, output3 = modelA(x)
# ...
# Save modelA
torch.save(modelA.state_dict(), 'modelA.pth')
# Duplicate modelA and add a switch for inference
class MyModelB(nn.Module):
def __init__(self, fast_inference=False):
super(MyModelB, self).__init__()
self.fc1 = nn.Linear(10, 1)
self.fc2 = nn.Linear(10, 1)
self.fc3 = nn.Linear(10, 1)
self.fast_inference = fast_inference
def forward(self, x):
if self.fast_inference:
return self.fc1(x)
x1 = self.fc1(x)
x2 = self.fc2(x)
x3 = self.fc3(x)
return x1, x2, x3
modelB = MyModelB(fast_inference=True)
modelB.load_state_dict(torch.load('modelA.pth'))
output = modelB(x)
Would that work for you?
|
st98264
|
for my current case yes that would work
is this way can save memory (run GPU)?
also is there a way to save the whole model ? architecture + weight ? (as in keras and tensorflow )
|
st98265
|
I am a beginner here trying to use pytorch for classification where the features are all numeric values. I have been trying to follow other classification examples but they are either image or text which is not exactly what I want. I get the following error from the below code following a Kaggle Titanic Competition kernel:
RuntimeError: cannot unsqueeze empty tensor
import torch
import numpy as np
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.i1 = nn.Linear(74, 128)
self.i1 = nn.Linear(128, 3)
# 3 possible labels for now
def forward(self, x):
x = self.i1(x)
x = F.dropout(x, p=0.1)
x = F.relu(x)
x = self.i2(x)
x = F.sigmoid(x)
return x
class NumberDataset(Dataset):
def __init__(self):
self.data = pd.read_csv('./data.csv', header=0, usecols=fields)
# Number of columns in data is 75
# Number of columns for self.x or input is 74
# Nunber of columns for self.y or target is 1
self.x = torch.from_numpy(np.asarray(self.data.iloc[:, :-1])).type(torch.FloatTensor)
self.y = torch.from_numpy(np.asarray(self.data.iloc[:, -1])).type(torch.LongTensor)
self.len = len(self.data)
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return self.len
# returns 640
if __name__ == '__main__':
dataset = NumberDataset()
train_loader = DataLoader(dataset=dataset, batch_size=128, shuffle=True)
net = Net()
batch_size = 128
num_epochs = 10000
learning_rate = 0.01
batch_no = dataset.len // batch_size
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
for i, data in enumerate(train_loader, 0):
# get the inputs and labels from data loader
inputs, labels = data
for epoch in range(num_epochs):
if epoch % 5 == 0:
print('Epoch {}'.format(epoch + 1))
# Mini batch learning
for i in range(batch_no):
start = i * batch_size
end = start + batch_size
x_var = Variable(inputs[start:end])
y_var = Variable(abels[start:end])
# Forward + Backward + Optimize
optimizer.zero_grad()
ypred_var = net(x_var)
loss = criterion(ypred_var, y_var)
loss.backward()
optimizer.step()
Where exactly am I going wrong? Is this approach right for a feed forward neural network?
|
st98266
|
It’s just a guess, but it seems the error is coming from your batching.
Currently you are using a DataLoader with a batch_size of 128, i.e. in each iteration your DataLoader will provide a batch of 128 samples.
In this loop you are trying to apply your own batching using the batch number.
However, inputs and labels will only contain 128 samples, not the whole dataset.
After the first valid batch, you will get an empty slice, since start and end will be too large.
If you use a Dataset and DataLoader you don’t have to implement batching yourself. The DataLoader will take care of it (even using multiprocessing to speed up the loading). You just have to implement the logic to load a single sample in your Dataset.
Try to remove the batching code in your training procedure. Also, as a small side note, Variables are deprecated and since 0.4.0 you can use tensors directly.
The loop over the DataLoader corresponds to one epoch, so you should move the epoch up:
for epoch in range(num_epochs):
for i, data in enumerate(train_loader):
inputs, labels = data
optimizer.zero_grad()
ypred = net(inputs)
...
if epoch%5 == 0:
print(...)
|
st98267
|
ptrblck:
for epoch in range(num_epochs):
Thank you that solved that error. However, when I print out the loss it does seem to change. Is everything else with my logic sound ?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.