id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st82868 | If I understand your issue correctly, commenting this line:
vec = rescale_intensity(plt.imread(osp.join('/home/XXX', vector))/255)
yields normal behavior, while keeping it increases the memory?
How did you define rescale_indensity?
@nile649
Your projects were running fine and now after changing the storage you are noticing an increasing memory usage? Did you change something else (PyTorch version etc.)? |
st82869 | actually, I just cross checked with previous projects, and it is happening with them as well. I doubt it is the code, but something else. I did look in previous post about assigning different variables, not using list, and as such, but it seems it is a different problem.
All the research projects over the last year use the same dataloader, and it is the first time I am having memory issue even with the weak old projects. |
st82870 | Check, if you are accidentally storing the computation graph, e.g. by accumulating the loss without detaching or storing it in a list.
Could you try to create a minimal code snippet to reproduce this issue? |
st82871 | Not sure if related, but I am having the same Issue with the mask-rcnn Pytorch version 2 |
st82872 | You’re right, I did debugging step by step and the following line is the culprit, I am directly treating loss term as scalar while calculating average loss over the epoch.
avg_loss_g = (avg_loss_g+loss_G)/(i+1) |
st82873 | If the problem is not with variables in dataloader, then it is with the variables in main function. |
st82874 | Yes, CPU memory.
DataLoader increases RAM usage every iteration
Is there any reason why you load all of your images during init ?
That was the error (and it makes lots of sense ) .
Now, I store the image paths during __init__ and load the images during __getitem__, as you mentioned. It works perfectly.
Thanks,
Very consitent memory leak
I tried some more things:
disabled eval mode
removed a non standard regularization step
replaced the non standard activation function with an out of the box ELU
In all cases I see the same consistent memory leak of ~108k pages of memory per epoch.
Any additional ideas on how to analyze this would be welcome.
Alberto
github.com/pytorch/pytorch
Issue: Possible CPU-side memory leak even when fitting on GPU 2
opened by trias702
on 2018-11-12
closed by soumith
on 2018-11-13
🐛 Bug
A possible CPU-side memory leak even when fitting on the GPU using PyTorch 0.4.1.
To Reproduce
I am quite new to PyTorch,...
todo
github.com/pytorch/pytorch
Issue: [Bug] CPU memory keeps increasing when using gloo backend 5
opened by stgzr
on 2019-01-18
closed by facebook-github-bot
on 2019-02-03
🐛 Bug
I found CPU memory keeps increasing when using dist.all_gather in gloo backend.
Update: it seems that gather and all_reduce have the...
cherry-picked
module: distributed
This with the @ptrblck response made me understand what are the reasons for potential memory leak in pytorch. I will suggest read thru the links I have posted. |
st82875 | Hi
I have the following snippet
329 for i in range(n):
330 foo[i, :] = functor(x - i)
331 bar[i, :] = functor(y - i)
Clearly these operations are parallelizable and I’m looking into something like numpy apply_along_axis or any operation that would make my stuff parallel.
Functor uses PyTorch operations.
Any ideas? |
st82876 | Solved by Roulbac in post #2
Solved using broadcasting where functor is an elementwise op and x,y are 1D vectors
326 range_tensor = torch.arange(n, out=torch.FloatTensor()).reshape(-1, 1)
327 foo = functor(x.reshape(1, -1) - range_tensor)
328 bar = functor(y.reshape(1, -1) - range_tensor) |
st82877 | Solved using broadcasting where functor is an elementwise op and x,y are 1D vectors
326 range_tensor = torch.arange(n, out=torch.FloatTensor()).reshape(-1, 1)
327 foo = functor(x.reshape(1, -1) - range_tensor)
328 bar = functor(y.reshape(1, -1) - range_tensor) |
st82878 | Hi all,
Of course, the datatype of the data you’re trying to propagate through your network matters.
Feeding your model input with wrong input type might give you:
RuntimeError: Input type (torch.LongTensor) and weight type (torch.FloatTensor) should be the same
And feeding model output of wrong type might yield something along the lines of:
RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'
To build a more flexible system I was wondering: How can one find the data type that will fit a model programmatically?
For output I’ve tried list(model.parameters())[-1] which might be a bit naive. |
st82879 | Might not be the best way, but for the inputs you could do something like:
current_children = model
while list(current_children.children()) != []:
current_children = list(current_children.children())[0]
for p_name, p in current_children.named_parameters():
print('{}: {}'.format(p_name, p.dtype)) |
st82880 | Hi there,
my problem is as follows:
I have a mixture of Labelled Sample Group and Unlabeled Sample Group. For some special reason, I have to mix those samples in a same mini-batch to train a classification network, with CrossEntropyLoss . So I need to ignore these unlabeled samples when computing the CrossEntropyLoss.
I tried to assign a pseudo label to these unlabeled samples and set the option weight in CrossEntropyLoss to be ( zero ) corresponding to the pseudo label , but found that it wouldn’t satisfy my demand. Although the loss on the pseudo class is ignored, if the prediction of an unlabeled data have large values on other indexes, it still generate large loss. I need those samples contribute exactly 0 to the CrossEntropyLoss.
So will someone kindly help me with this issue?
Millions of thanks in advance. |
st82881 | Hello,
Indeed setting the weight in CrossEntropyLoss set weights with respects to the classes which seems not to be what you need.
Not sure my solution could help you but in my opinion you could create 3 datasets, one with labelled, one with unlabelelled and one that return the 2. You can create them via module Dataset of Pytorch, you can make a call only on the labelled data to compute the crossentropyloss, something like:
mixed_dataset = MixedDataset() #the __getitem__() function return ( labeleddata, unlabeleddata)
labeled_dataset = LabeledDataset()
unlabelled_dataset = UnlabeledDataset()
for data in mixed_dataset:
whatever you need
for labeled in labeled_dataset:
compute loss
whatever you need
just be sure to not mix the index and always return the corresponding data |
st82882 | Thanks for your reply.
I’m a little confused that there are two for loops to get 2 batch of data. Can you explain more about that?
In my case, both the labeled data and unlabeled data are mixed and shuffled during training, forming a minibatch to do forward propagation. |
st82883 | Hi SoucheChapich, thanks for your reply.
I’m a little confused that there are two for loops to get two batches of data. Can you explain more about that?
In my case, both the labeled data and unlabeled data are mixed and shuffled during training |
st82884 | I notice that there exists a parameter called ignore_index in nn.CrossEntropyLoss(), but it seems that ignore_index works similarly to zero weight and cannot solve the problem that misclassified
unlabeled data still contribute to the final loss |
st82885 | Hello,
I was just thinking about a solution for your case, I think that something like that is possible.
How did you define your dataset ? Are you using data.Dataset class from pytorch ? If yes, you should be able to specify whatever you want. I mean, you can do somehing like:
class mixedDataset(data.Dataset):
def __getitem__(self, index):
return your combined_data
def __getlabeleddata_(self,index):
return your labeled data
and after you can iterate through your mixedDataset and calling your getlabeldata function to get the labeled data. |
st82886 | Yes, I use Dataset and dataloader class from pytorch. You can viewed the model comprising a feature extractor and a classifier which works in an E2E manner. For both labeled and unlabeled data mixed together to do forward propagation, however, you can view it as we use the whole data for feature extraction, but only labeled data was used for classificaion. |
st82887 | I have no idea how torch.mean(dim=0) is working.
for example when i run the code below
#------------------------------------------------
import torch
t = torch.FloatTensor([[1, 2], [3, 4]])
print(t.mean(dim=0)
#------------------------------------------------
The output is
tensor([2., 3.])
I don’t know why the output comes like this.
Anyone with the insight please tell me how it is working like this. |
st82888 | It means: give me the mean of the elements iterated of the axis dim.
In your example what it does is:
(t[0] + t[1]) / num_elements = ([1, 2]+ [3, 4]) / 2 = [2., 3.]
Similarly if you specified dim1, it would do:
(t[:,0] + t[:,1]) / 2 = tensor([ 7., 13.])
same result as
>>> t.mean(dim=1)
tensor([ 7., 13.]) |
st82889 | The dim parameter defines over which dimension of the tensor you are taking a mean. In your case, dim=0
t = [[1,2],
[3,4]]
t.mean(dim=0) = [(1+3)/2, (2+4)/2] = [2,3]
For dim=1,
t = [[1,2],
[3,4]]
t.mean(dim=1) = [(1+2)/2, (3+4)/2] = [1.5,3.5]
Hope this helps!
Regards |
st82890 | I do not understand what does the syncStreams function do in pytorch.Can the function synchronize different nodes cuda streams?
屏幕快照 2019-08-19 下午3.39.23.png836×233 32.5 KB |
st82891 | Hi, all,
I have problems regarding reading large training data from disk.
The situation is I have one single huge file (roughly 100G), each line is a training example.
Clearly I can not load them all into memory.
When I searched for the solution.
One possible solution is to split this huge file into small files and use DataSet and DataLoader like mentioned in here: Loading huge data functionality 95
However, in this way, the total number(the return value of __len__ in DataSet) of training example becomes the number of small files not the true number of my training examples. DataLoader sees each small file as one example which is weird.
Can any one provide an elegant solution for this situation? Perhaps producer/consumer style? |
st82892 | @marchss @jetcai1900 Not yet. Finally, I implemented the producer/consumer loader by myself. |
st82893 | I am dazzled about all the pieces of tutorials from any kind of websites. How SGD was implemented in PyTorch?
lr: learning rate
w: weights
dw: the grad of weights
Is this equation w'= momentum * w - lr * (dw + weight_decay * w) right?
Or this v=momentum * v(t-1) + (dw + weight_decay * w), then w = w - lr * v, here v(t-1) means the last time v. |
st82894 | something like
------abcd------
—ab… …cd–
a-----b…c----d
where a, b, c, d… are patterns learnt by a neural network.
ab, cd is combination of the patterns learnt at the lower hierarchy and so on.
if a has learnt patterns for lips, b for nose, c for eyes, d for tongue, then abcd would be face. |
st82895 | This looks like the idea behind the hierarchical features learned in CNNs as described in Unsupervised Learning of Hierarchical Representations with Convolutional Deep Belief Networks 39.
The figures from this paper are quite popular in presentation slides and blog posts (Google search 14). |
st82896 | I think it is a bit different,
What I am saying, is a whole neural network at the bottom, which only knows how to predict lips, similarly whole neural network for tongue.
And then these combine together to form next hierarchy.
But what is combining two neural networks in PyTorch, so if one of them is able to predict lips, other nose, then combination would be able to predict (nose + lips)? |
st82897 | I’m not sure, what your work flow would be and how you would like to force the submodels to predict only a part of the face.
Would you want to use different label sets, i.e. one model would only get nose - not nose labels, while the others would get the mouth pairs etc.?
Do you have a dataset, where only parts of faces would be visible?
If the complete face is always visible, you wouldn’t be able to only force on a particular part.
Or would you only use cropped patches of the face image?
In that case, I’m not sure, how your validation/test set would look like. |
st82898 | This is related to one shot meta learning, so I have sample and query in meta train set, and sample and query in meta test set, the task is to make neural network classify by showing only one image, that is, show it one image in the sample of meta test set, and it would give correct classification for query in meta test set, for this we show images to neural network in sample of meta train set, and ask it to predict correctly in the query of meta train set, if it gives incorrect prediction, then loss increases, task is to minimize loss, once we have a neural network that gives low loss in meta train set, then it would give correct result by showing only one image in sample of meta test set and make correct prediction for query of meta test set. What I think is that we want our neural network to learn a whole hierarchy during meta training stage, that is, face, lips, tongue, eyes…, and after meta training we have a neural network that has learnt hierarchy, so in meta test set, it would adapt quickly to the sample, and be able to predict query of meta test set correctly. |
st82899 | Hi, I am trying to export the segmentation some segementation of the segmentation model, newly added to torchvision. They export sucessfully after applying this workaround 14. However the ONNX graph generates several cast operations as seen in the picture.
image.png1919×303 92.9 KB
It says its coming from the ASPPPooling layer but that layer is defined as:
image.png719×168 23.6 KB
And I dont think any of these layers do any casting. Any ideas where this Cast[to=1] comes from or how to avoid it? Any help will be greatly appreciated!!
P.S I am using pytorch and torchvision both compiled from source |
st82900 | I guess the cast is related to this line of code 58 in interpolate, which was added in this PR 18 to fix tracing.
PS: I could run the code without modifying anything or building from source:
class AsppPooling(nn.Module):
def __init__(self, in_channels, out_channels, norm_layer):
super(AsppPooling, self).__init__()
self.gap = nn.Sequential(nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, out_channels, 1, bias=False),
norm_layer(out_channels),
nn.ReLU(True))
def forward(self, x):
_, _, h, w = x.size()
pool = self.gap(x)
return F.interpolate(pool, (h,w))
model = AsppPooling(3, 3, nn.BatchNorm2d)
torch.onnx.export(model, torch.randn(2, 3, 2, 2), 'tmp.onnx', verbose=True) |
st82901 | Thank you so much! @ptrblck. What should I expect if I were to remove the .floor operation?. Would the results be the same if I wanted to use that model for segmentation? |
st82902 | I’m not sure, but I would assume you would get wrong results.
Also, I don’t think you should be too worried about casting a single value, as this should not change the time a lot.
That being said, these are just guesses, as I’m not very familiar with ONNX, so @eellison might have more insight as the author of the PR. |
st82903 | I am not worried because of speed. I am trying to export some ONNX models to OpenCV as part of my GSoC project 4 and the OpenCV ONNX importer does not support the Cast operation from ONNX yet. I am trying to see if I can get away with not implementing it |
st82904 | Hi
I am currently using the transforms.ToTensor(). As per the document it converts data in the range 0-255 to 0-1.
However, the transform work on data whose values ranges between negative to positive values? Any ideas how this transform work. And the transformed values no longer strictly positive.
In most tutorials regarding the finetuning using pretrained models, the data is normalized with [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]). I would like to know how these values are computed? Are they computed by attained by using mean & std value of each channel from the entire training data? |
st82905 | ToTensor() works for the image, whose elements are in range 0 to 255. You can write your custom Transforms to suit your needs.
[0.485, 0.456, 0.406] is the normalized mean value of ImageNet, and [0.229, 0.224, 0.225] denotes the std of ImageNet.
Yes, it is computed per channels. |
st82906 | Oki I got it.
http://pytorch.org/docs/0.2.0/_modules/torchvision/transforms.html#ToTensor 5.6k explains. The entire array is converted to torch tensor and then divided by 255. This is how it is forces the network to be between 0 and 1. |
st82907 | Actually, I found it is different from *1.0/255 in C++. The results between transforms.ToTensor() in Python and *1.0/255 in C++ are not same.
I am wondering why… |
st82908 | My gut instinct was * 1.0 / 256 instead of * 1.0 / 255. Does this fix the problem, @LvJC? |
st82909 | I am trying to find out if there is any way to force the distribution of classes in each batch that is produced when using the pytorch Dataset and Dataloader functionality. For example, I am doing binary classification and (because my class sizes are imbalanced) during training I would like each batch to be 50% positive examples and 50% negative. Is there any way to achieve this with Dataloader?
Thanks! |
st82910 | I think the proper way to have such a functionnality is to subclass torch.utils.data.Sampler with a custom one that samples equiprobably from positive and negative samples. Then, you pass an instance of this custom sampler to the DataLoader as the sampler argument.
In any case, however, you will need to decide if you want to repeat the smaller class (so that you visit every element of the larger class once per epoch) or to trim the larger class (so that you visit every element of the smaller class once per epoch). In the first case, data augmentation is recommended. |
st82911 | Personally, I use the WeightedRandomSampler class (https://pytorch.org/docs/stable/data.html#torch.utils.data.WeightedRandomSampler 62) and give each sample a weight of inverse the frequency of each class, thus resulting in an equal representation of the classes in the mini-batch (assuming a big enough batch size I guess) |
st82912 | I want to clarify one point regarding the WeightedRandomSampler.
While it is oversampling the minority class it is also undersampling the majority class .
Lets say i have 100 images of classA and 900 images of classB
Then dataloader length will be 1000. and when we will iterate in minibatches it will ensure equal distribution thus approx 500 images of class A and 500 images of classB will be used for training.
Can’t we say it is oversampling the minority but undersampling the majority in dataset? |
st82913 | Conv layers work much longer, tens of times longer than linear layers (on gpu). What is the reason for this? Are there ways to accelerate ultra-precise networks? Maybe there is an opportunity to collapse not in steps, but in a bundle? (It’s not about the batch) |
st82914 | The operations in a conv layer might include e.g. additional im2col ops or fft based operations.
How and which layers did you profile on the GPU? |
st82915 | class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv11 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv11.weight)
self.relu11c = nn.PReLU()
self.bn11c = nn.BatchNorm2d(32, affine=True)
self.conv12 = nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv12.weight)
self.relu12c = nn.PReLU()
self.bn12c = nn.BatchNorm2d(32, affine=True)
self.conv13 = nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv13.weight)
self.relu13c = nn.PReLU()
self.bn13c = nn.BatchNorm2d(32, affine=True)
self.mpool1 = nn.MaxPool2d(kernel_size=2, stride=2) #80x16
self.conv21 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1) #80x16
nn.init.xavier_uniform_(self.conv21.weight)
self.relu21c = nn.PReLU()
self.bn21c = nn.BatchNorm2d(64, affine=True)
self.conv22 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv22.weight)
self.relu22c = nn.PReLU()
self.bn22c = nn.BatchNorm2d(64, affine=True)
self.conv23 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv23.weight)
self.relu23c = nn.PReLU()
self.bn23c = nn.BatchNorm2d(64, affine=True)
self.mpool2 = nn.MaxPool2d(kernel_size=2, stride=2) #40x8
self.conv31 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv31.weight)
self.relu31c = nn.PReLU()
self.bn31c = nn.BatchNorm2d(128, affine=True)
self.conv32 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv32.weight)
self.relu32c = nn.PReLU()
self.bn32c = nn.BatchNorm2d(128, affine=True)
self.conv33 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
nn.init.xavier_uniform_(self.conv33.weight)
self.relu33c = nn.PReLU()
self.bn33c = nn.BatchNorm2d(128, affine=True)
self.mpool3 = nn.MaxPool2d(kernel_size=2, stride=2) #20x4
self.fc7 = nn.Linear(10240, 700)
nn.init.xavier_uniform_(self.fc7.weight)
self.relu7 = nn.PReLU()
self.bn7 = nn.BatchNorm2d(1, affine=True)
self.fc8 = nn.Linear(700, 1)
nn.init.xavier_uniform_(self.fc8.weight)
self.tan = nn.Hardtanh()
def forward(self, x):
out = self.conv11(x)
out = self.relu11c(out)
out = self.bn11c(out)
res = out
out = self.conv12(out)
#out = self.relu12c(out)
out = self.bn12c(out)
out += res
out = self.conv13(out)
out = self.relu13c(out)
out = self.bn13c(out)
out = self.mpool1(out)
out = self.conv21(out)
out = self.relu21c(out)
out = self.bn21c(out)
res = out
out = self.conv22(out)
#out = self.relu22c(out)
out = self.bn22c(out)
out += res
out = self.conv23(out)
out = self.relu23c(out)
out = self.bn23c(out)
out = self.mpool2(out)
out = self.conv31(out)
out = self.relu31c(out)
out = self.bn31c(out)
res = out
out = self.conv32(out)
#out = self.relu32c(out)
out = self.bn32c(out)
out += res
out = self.conv33(out)
out = self.relu33c(out)
out = self.bn33c(out)
out = self.mpool3(out)
out = out.contiguous().view(batch,1,1,10240)
out = self.fc7(out)
out = self.relu7(out)
out = self.bn7(out)
out = self.fc8(out)
out = out.contiguous().view(batch,1)
#print('out ',out.size())
return out
device = torch.device("cuda:0")
net = Net()
net.to(device)
...
w = torch.from_numpy(w).unsqueeze(1).to(device)
outputs = net(w)
... |
st82916 | Thanks for the code.
How did you profile the code and which assumptions did you make?
You could try to use the JIT to fuse some operations. |
st82917 | I simply call model.half() and change my input data from float32 to float16. However, the model will throw RuntimeError: cuda runtime error (74) : misaligned address error at /opt/conda/conda-bld/pytorch_1556653183467/work/aten/src/ATen/native/cuda/SoftMax.cu:545. The exact error address will change at each time I retrain the model. |
st82918 | Do you have a code snippet to reproduce this issue?
We’ve seen a similar issue recently in apex/amp 19, but could not reproduce it due to lack of information. |
st82919 | I guess the issue happens between the dataParallel wrapper and the half precision. I have tried apex/amp and the same issue exists except the O1 optimization. The issue may be reproduced simply with a linear projection. The error’s position is not fixed, sometimes happens at the very first linear layer, I guess you can replicate it with simply a linear layer, > 1 GPUs and DataParallel wrapper.
model, optimizer = amp.initialize(model, optimizer,
opt_level='O2'
)
model = torch.nn.DataParallel(model, device_ids=[0,1,2]) |
st82920 | i am trying to multiply the input vector of size (4,5,32,32)
here
4 - batch size
5 - channels
32 x 32 feature size
As mentioned in the parametric channelwise relu i want to multiply a vector to each of the channels |
st82921 | Please don’t tag certain people specifically. They will answer, if they have time.
Also, this might discourage other users to post an answer. |
st82922 | Could you explain the parametric channelwise ReLU?
How would you like to multiply the input of [4, 5, 32, 32] with a tensor, i.e. what shape would the internal tensor have? |
st82923 | The internal tensor will be of 1x channel number. For 5 channel input we would have 1x5 as the internal tensor.
For [4 , 5, 32, 32]
We need to multiply 1 value for each of the [32,32] in each batch.
So 5 different values are used for each of the 5 channels in 32 x 32 |
st82924 | Does anyone know how to freeze weights at a deep layer (to prevent backpropagation), for only some elements of a batch? I want all elements to still backpropagate through the final layer, and some but not all to backprop beyond that.
I know how to selectively freezing some elements of a batch (with a mask), as well as how to freeze a deep layer (deep_layer.requires_grad = False), but I can’t think of a way to do both simultaneously. Thanks a lot! |
st82925 | Hi!!
I’m doing some experiments and I found that even though I fixed starting weight(I used pre-initialized weight), learning_rate and data order(I set shuffle option to False), the gradient changed when I try this two times! I got gradients of my model throughout 5 epochs and I did this for two times. Then I compared those gradients each other. They get further and further as epoch gets bigger.
Is there any other way that gradients can be changed? |
st82926 | Hi,
Are you running your model on the GPU? Some op used by cuDNN are non-deterministic (especially backward accumulation with atomicAdd with floating points).
Please find more info about it here 4 |
st82927 | Oh wow thanks for quick replying LOL.
I found out that I have to do all three things in the link to make gradients same.
Thanks so much for the information!!
Have a good one! |
st82928 | I have a multi-class classification problem but when I train it, the loss becomes stagnant after few epochs at 1.7918.
The output is:
[[-0.1240, -0.1240, -0.1240, -0.1240, -0.1240, -0.1240]]
for every class and doesn’t change a bit after that.
The model:
# Feature Encoder
class Enc(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(14, 12)
self.fc2 = nn.Linear(12, 10)
self.fc3 = nn.Linear(10, 8)
self.fc4 = nn.Linear(8, 6)
def forward(self, x):
fn = nn.ReLU()
hidden = fn(self.fc2(fn(self.fc1(x))))
out = self.fc4(fn(self.fc3(hidden)))
return out
model = Enc().to(device)
The training loop:
criterion = nn.CrossEntropyLoss().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01, momentum = 0.09)
for epoch in range(10000):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch%1999 == 1:
print(loss)
What should I do? |
st82929 | I searched inside https://pytorch.org/docs/master/optim.html 90 but haven’t found any Layer-wise AdaptiveRate Scaling optimizer LARS 108 implemented. Same for LAMB. Are there any plans soon? Should we add FR? |
st82930 | Hi,
LARC is not available directly in PyTorch but it is in Apex https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py 701 |
st82931 | Someone tell me how to remove embidding from the transformer and instead of softmax make MSELoss. |
st82932 | I am facing an error “Out of memory” when trying to load 100 MySmallModel in “cuda:0”.
I have two GPU with 12GB.
RuntimeError: CUDA out of memory. Tried to allocate 28.00 MiB (GPU 0; 11.91 GiB total capacity; 11.18 GiB already allocated; 19.38 MiB free; 34.67 MiB cached)
Can any please help me how can I solve this problem?/ How can I divide “self.fc1 = nn.Linear(70000, 3000)” layer into multiple layers and then do the computation?
class MySmallModel(nn.Module):
def __init__(self,nodes):
super(MySmallModel, self).__init__()
self.fc1 = nn.Linear(70000, 3000)
self.fc3 = nn.Linear(3000, 1000)
self.fc1.cuda(0)
self.fc3.cuda(1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = x.cuda(1)
x = F.relu(self.fc3(x))
return x
class Classifier(nn.Module):
def __init__(self,input_nodes):
super(Classifier, self).__init__()
self.networks = nn.ModuleList([MySmallModel() for i in range(100)])
self.sharedlayer = nn.Sequential(
nn.Linear(30000, 300),
nn.ReLU(),
nn.Linear(300, 100),
nn.ReLU(),
)
self.sharedlayer.cuda(1)
def forward(self, input_):
x_list=[]
x_list.append(F.relu(self.networks[i](tensor_Data)))
x = torch.cat((x_list), 1)
x = x.cuda(1)
h_shared = self.sharedlayer(x)
return h_shared
================================================
criterion = nn.MSELoss()
model = Classifier(input_nodes)
optimizer = optim.SGD(model.parameters(), lr=0.01)
trainloader = torch.utils.data.DataLoader(NN_data_train, batch_size=1, shuffle=True)
for epoch in range(n_epochs):
running_loss = 0
i = 0
model.train()
for data, label in trainloader:
out1 = model(data.cuda(0))
output = torch.cat([out1], 1)
loss = criterion(output.cuda(1), label.cuda(1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
I have already reduce the batch size to 1. But still same memory problem.
Please help. |
st82933 | Hi all,
I am having trouble finding research on models that used CrossEntropy vs CTC and their performance. It seems that if you have some kind of seq2seq task, it makes a lot of sense to use CTC but I would like to see what kind of difference I can expect. Any hints are welcome.
Thanks |
st82934 | Hi,
I’m new to pytorch. Why does the prebuilt pytorch for macos only use one core when using CPU? Is there a documented way to get a better performing build when only CPU is available.
torch.config.show() reports:
‘PyTorch built with:\n - GCC 4.2\n - clang 9.0.0\n - Intel® MKL-DNN v0.18.1 (Git Hash 7de7e5d02bf687f971e7668963649728356e0c20)\n - NNPACK is enabled\n - Build settings: BLAS=MKL, BUILD_NAMEDTENSOR=OFF, BUILD_TYPE=Release, CXX_FLAGS= -Wno-deprecated -fvisibility-inlines-hidden -Wno-deprecated-declarations -DUSE_FBGEMM -DUSE_QNNPACK -O2 -fPIC -Wno-narrowing -Wall -Wextra -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -Wno-invalid-partial-specialization -Wno-typedef-redefinition -Wno-unknown-warning-option -Wno-unused-private-field -Wno-inconsistent-missing-override -Wno-aligned-allocation-unavailable -Wno-c++14-extensions -Wno-constexpr-not-const -Wno-missing-braces -Qunused-arguments -fcolor-diagnostics -faligned-new -fno-math-errno -fno-trapping-math -Wno-unused-private-field -Wno-missing-braces -Wno-c++14-extensions -Wno-constexpr-not-const, DISABLE_NUMA=1, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, USE_CUDA=False, USE_EIGEN_FOR_BLAS=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=OFF, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=OFF, USE_NNPACK=ON, USE_OPENMP=OFF, \n’
I installed pytorch in a virtual environment using pip. |
st82935 | resnet-neural-e1548772388921.png1130×635 31.5 KB
How can I implement resnet as in the picture? How to add X to the next layer? |
st82936 | Solved by ptrblck in post #3
Have a look at the resnet implementation in torchvision.
In particular the definition of BasicBlock and Bottleneck might be helpful. |
st82937 | Have a look at the resnet implementation in torchvision.
In particular the definition of BasicBlock and Bottleneck might be helpful. |
st82938 | Hello at all!
a question regarding keywords in torch.nn.Sequential, it is possible in some way to forward keywords to specific models in a sequence?
model = torch.nn.Sequential(model_0, MaxPoolingChannel(1))
res = model(input_ids_2, keyword_test=mask)
here, keyword_test should be forwarded only to the first model.
Thank a lot and best regards! |
st82939 | Solved by albanD in post #2
Hi,
You can pass any single input to the sequential. So you can pass a tuple or dict if you want and unpack them in your first model.
The implementation is simple and can be found here if you want to see the forward method of the Sequential |
st82940 | Hi,
You can pass any single input to the sequential. So you can pass a tuple or dict if you want and unpack them in your first model.
The implementation is simple and can be found here 137 if you want to see the forward method of the Sequential |
st82941 | Dear all,
I tried to run PyTorch transfer learning codes on Colab for my project. The codes need Pytorch 0.3.1 and torchvision 0.2.0. I have uninstalled the current version of PyTorch and try to install the needed version via:
!pip3 install torch==0.3.1 torchvision==0.2.0 -f https://download.pytorch.org/whl/torch_stable.html
however, the Cuda did not install. I have searched for several days to find the solution, but unfortunately, I did not get anything useful. Would somebody please help me with that? Thank you so much in advance. |
st82942 | Hi all,
I come across a strange problem when I train my model on the server. At the first several iterations, the running time is OK. All the CPUs are working for IO and GPU is working. But after several iterations, suddenly the CPUs do not work for IO. I do not know what happened.
Could someone help me? Thank you very much!
During the first several iterations:
Selection_002.png1228×92 8.48 KB
Selection_001.png1182×463 59.1 KB
Suddenly, CPUs are not working:
Selection_004.png1247×57 5.18 KB
Selection_003.png1199×445 53.4 KB
And it continues like this. Very slow. |
st82943 | Solved by hasakii in post #5
Its mainly caused by IO problem. It seems that you used a super computer, but the swap area is too small. When loading data from disk, it would comsumes too much memory for data buffering.
Here is some suggestions:
mapping the input feature to output label one by one and contiguously write to dis… |
st82944 | Hi,
How is the GPU usage?
At the beginning, the dataloader preloads many samples so that might explain the high cpu usage. |
st82945 | Hi The GPU is always zero. I think my dataset is too large and I should put it in a mounted storage machine. Maybe it is the reason of IO problem? |
st82946 | Might be unrelated, but how many workers are you using? Also do you set pin_memory=True? |
st82947 | Its mainly caused by IO problem. It seems that you used a super computer, but the swap area is too small. When loading data from disk, it would comsumes too much memory for data buffering.
Here is some suggestions:
mapping the input feature to output label one by one and contiguously write to disk.
clean the swap area.
use other machine if possible. |
st82948 | Right now I use 8 workers. Yes, I set pin_memory=True. After I put the data back into the local disk, the speed becomes normally. |
st82949 | What I want is fairly simple: a MSE loss function, but able to mask some items:
def masked_mse_loss(a, b, mask):
sum2 = 0.0
num = 0
for i in len(range(a)):
if mask[i] == 1:
sum2 += (a[i] - b[i]) ** 2.0
num += 1
return sum2 / num
Due to backward issue, I believe such a straightforward implementation would not make pytorch happy, but I have no idea on how to make it in correct way. |
st82950 | Solved by zhl515 in post #4
You can call out.backward() to backpropagate the error.
predict = torch.tensor([1.0, 2, 3, 4], dtype=torch.float64, requires_grad=True)
target = torch.tensor([1.0, 1, 1, 1], dtype=torch.float64, requires_grad=True)
mask = torch.tensor([1, 0, 0, 1], dtype=torch.float64, requires_grad=True)
out = to… |
st82951 | I was under the belief that pytorch would accept this kind of loss function. What error does it give you? |
st82952 | I wrote the loss class:
class MaskedMSELoss(torch.nn.Module):
def __init__(self):
super(MaskedMSELoss, self).__init__()
def forward(self, input, target, mask):
diff2 = (torch.flatten(input) - torch.flatten(target)) ** 2.0
sum2 = 0.0
num = 0
flat_mask = torch.flatten(mask)
assert(len(flat_mask) == len(diff2))
for i in range(len(diff2)):
if flat_mask[i] == 1:
sum2 += diff2[i]
num += 1
return sum2 / num
What would be default backward looks like? |
st82953 | You can call out.backward() to backpropagate the error.
predict = torch.tensor([1.0, 2, 3, 4], dtype=torch.float64, requires_grad=True)
target = torch.tensor([1.0, 1, 1, 1], dtype=torch.float64, requires_grad=True)
mask = torch.tensor([1, 0, 0, 1], dtype=torch.float64, requires_grad=True)
out = torch.sum(((predict-target)*mask)**2.0) / torch.sum(mask)
out.backward() |
st82954 | I modified the algorithm to a more simple form that removed for cycle and if, and it works properly:
diff2 = (torch.flatten(input) - torch.flatten(target)) ** 2.0 * torch.flatten(mask)
result = torch.sum(diff2) / torch.sum(mask)
return result
Thanks! |
st82955 | Hi.
I used this line in my main pytorch code:
torch.where(F.softmax(presence_vector.view(-1), dim=0) >= (1/len(m_vector))
I faced this error: AttributeError: module ‘torch’ has no attribute ‘where’.
'torch version is: ‘0.3.1’
Is there any help?
Thanks |
st82956 | Hi @solsol
torch.where was added in v0.4.0 https://github.com/pytorch/pytorch/releases/tag/v0.4.0 21
How can I do the operation the same as `np.where`?
@truenicoco, torch.where() looks like it’'s in 0.4! http://pytorch.org/docs/master/torch.html#torch.where
thanks others for examples of other options for 0.3 and before |
st82957 | Hello, I’m trying to upgrade to pytorch 1.2. I’ve found that official guidance seems to need cudatoolkit version to be 9.2 or higher. Is it possible to use pytorch 1.2 with cudatoolkit 9.0? Thanks for any help! |
st82958 | You should be able to compile PyTorch using CUDA9.0.
However, the binaries dropped the support for CUDA8.0 and CUDA9.0 in the latest release. |
st82959 | Thank you! Sorry for the late reply. I have tried to build pytorch 1.2 from source following the instruction on the official github website. I came across the following problem: “ninja: build stopped: subcommand failed.” I can’t provide the detailed error report now because our server is in the progress of update. When it’s done, I’ll try it again. Thanks for your help! |
st82960 | Hi All,
I want to use a net as part of loss function, but the problem is that the net outputs different values when I use eval() and train(), it actually outputs much better when I use eval().
But, when I use eval(), I get the following error when I try to use the net as part of a loss:
RuntimeError: cudnn RNN backward can only be called in training mode
So I want to get the same net output as using eval() and also avoid the mentioned error.
Any help will be appreciated. |
st82961 | Solved by rmokady in post #2
I found some workaround. declare net.train() then for any Dropout and BatchNorm layers:
net.dropout.p = 0
net.batchNorm.training = False
It seems to work. |
st82962 | I found some workaround. declare net.train() then for any Dropout and BatchNorm layers:
net.dropout.p = 0
net.batchNorm.training = False
It seems to work. |
st82963 | This is very weird. I have loaded CIFAR10 dataset:
import torchvision.datasets as datasets
import torchvision.transforms as transforms
dataloader = datasets.CIFAR10
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = dataloader(root='./data', train=True, download=True, transform=transform_train)
Then I find the image returned by trainset.getitem and the one accessed directly are different.
The getitem in class CIFAR10(data.Dataset) says
def __getitem__(self, index):
img, target = self.data[index], self.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
But if I implement getitem() directly and run this
by_get_item = trainset[0][0]
directly = trainset.transform(Image.fromarray(trainset.data[0]))
print(torch.sum(torch.abs(
by_get_item - directly
)))
it prints a non-zero and the value keeps changing. Why does this happen? |
st82964 | Solved by ptrblck in post #2
Since you are using random transformations, you’ll get randomly transformed samples every time.
Remove RandomHorizontalFlip and RandomCrop and you should get the same outputs. |
st82965 | Since you are using random transformations, you’ll get randomly transformed samples every time.
Remove RandomHorizontalFlip and RandomCrop and you should get the same outputs. |
st82966 | I am trying online hard mining, and my simplified code is like this:
class OhemCELoss(nn.Module):
def __init__(self, thresh, n_min, ignore_lb=255, *args, **kwargs):
super(OhemCELoss, self).__init__()
self.thresh = thresh
self.n_min = n_min
self.ignore_lb = ignore_lb
self.criteria = nn.CrossEntropyLoss(ignore_index=ignore_lb)
def forward(self, logits, labels):
N, C, H, W = logits.size()
n_pixs = N * H * W
logits = logits.permute(0, 2, 3, 1).contiguous().view(-1, C)
scores = F.softmax(logits, dim=1).cpu()
labels = labels.view(-1)
labels_cpu = labels.cpu()
invalid_mask = labels_cpu==self.ignore_lb
labels_cpu[invalid_mask] = 0
picks = scores[torch.arange(n_pixs), labels_cpu]
picks[invalid_mask] = 1
sorteds, inds = torch.sort(picks)
thresh = self.thresh if sorteds[self.n_min]<self.thresh else sorteds[n_min]
labels[picks>thresh] = self.ignore_lb
loss = self.criteria(logits, labels)
return loss
if __name__ == '__main__':
criteria1 = OhemCELoss(thresh=0.7, n_min=16*20*20//16).cuda()
criteria2 = OhemCELoss(thresh=0.7, n_min=16*20*20//16).cuda()
net1 = nn.Sequential(
nn.Conv2d(3, 19, kernel_size=3, stride=2, padding=1),
)
net1.cuda()
net1.train()
net2 = nn.Sequential(
nn.Conv2d(3, 19, kernel_size=3, stride=2, padding=1),
)
net2.cuda()
net2.train()
inten = torch.randn(16, 3, 20, 20).cuda()
lbs = torch.randint(0, 19, [16, 20, 20]).cuda()
lbs[1, 10, 10] = 255
logits1 = net1(inten)
logits1 = F.interpolate(logits1, inten.size()[2:], mode='bilinear')
logits2 = net2(inten)
logits2 = F.interpolate(logits2, inten.size()[2:], mode='bilinear')
loss1 = criteria1(logits1, lbs)
loss2 = criteria2(logits2, lbs)
loss = loss1 + loss2
loss.backward()
With this code I got the error message of:
Traceback (most recent call last):
File "loss.py", line 79, in <module>
loss.backward()
File "/home/zhangzy/.local/lib/python3.5/site-packages/torch/tensor.py", line 102, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/zhangzy/.local/lib/python3.5/site-packages/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
Where is the inplace operation that causes this error please? |
st82967 | Would you please show me how to fix this? I changed it like this:
def forward(self, logits, labels):
N, C, H, W = logits.size()
n_pixs = N * H * W
logits = logits.permute(0, 2, 3, 1).contiguous().view(-1, C)
with torch.no_grad():
scores = F.softmax(logits, dim=1).cpu().detach()
labels = labels.view(-1)
labels_cpu = labels.cpu().detach()
invalid_mask = labels_cpu==self.ignore_lb
labels_cpu[invalid_mask] = 0
picks = scores[torch.arange(n_pixs), labels_cpu]
picks[invalid_mask] = 1
sorteds, inds = torch.sort(picks)
thresh = self.thresh if sorteds[self.n_min]<self.thresh else sorteds[n_min]
labels[picks>thresh] = self.ignore_lb
loss = self.criteria(logits, labels)
return loss
But the problem still exists |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.