id
stringlengths
3
8
text
stringlengths
1
115k
st104000
Solved by tom in post #5 0.1.12 doesn’t have broadcasting, so you have to use expand/expand_as. In Richard’s example x + y.expand_as(x). Best regards Thomas
st104001
Seems to work for me: In [1]: import torch In [2]: x = torch.randn(1, 25, 256) In [3]: y = torch.randn(1, 1, 256) In [4]: x + y Out[4]: tensor([[[ 1.4846, -1.2704, -1.5809, ..., 0.9014, -0.8867, 0.8496], [ 4.1737, 2.4117, -0.0261, ..., 0.0534, -0.5655, 0.9513], [ 0.3474, 0.2071, -3.2485, ..., 0.4155, -0.6435, 1.7778], ..., [ 2.6008, 0.7829, -2.2995, ..., 1.4929, -0.8345, 1.1157], [ 2.9556, 1.7386, -0.8274, ..., 1.0852, -0.4116, 2.2215], [ 2.6638, 0.6301, -3.5564, ..., 0.7788, 1.2027, 2.0694]]]) what version of pytorch are you on? Could you provide a code snippet?
st104002
Yeah, I tested it with 0.4 and it works. The question now is, how to make it work with 0.1.12?
st104003
0.1.12 doesn’t have broadcasting, so you have to use expand/expand_as. In Richard’s example x + y.expand_as(x). Best regards Thomas
st104004
Hello, I would like to ask a question about the license that PyTorch is released under or PyTorch’s SPDX tag. I need this info for an internal open source contribution approval. It seems that both Tensorflow and MxNET use Apache License 2.0. Caffe is released under BSD 2-Clause license. However, from PyTorch license page on github, I only can find copyright info, but no license name there. Does someone know the PyTorch license or SPDX tag info? Thanks.
st104005
I’m not a lawyer, but the LICENSE 112 file looks like 3-clause-BSD to me. Note that the license text seems to be applicable to all the copyrighted files that are listed above and was present before the caffe2 merge. Best regards Thomas
st104006
How to convert the following batch normalization layer from Tensorflow to Pytorch? tf.contrib.layers.batch_norm(inputs=x, decay=0.95, center=True, scale=True, is_training=(mode=='train'), updates_collections=None, reuse=reuse, scope=(name+'batch_norm')) I couldn’t find some of the following inputs in the batchnorm layer in Pytorch.
st104007
Solved by ptrblck in post #2 Based on the doc, let’s try to compare the arguments. decay seems to be 1-momentum in PyTorch. center and scale seem to be the affine transformations, (affine in PyTorch). is_training can be achieved by calling .train() on the Module. I’m not sure, what updates_collection, resuse and scope mean …
st104008
Based on the doc 90, let’s try to compare the arguments. decay seems to be 1-momentum in PyTorch. center and scale seem to be the affine transformations, (affine in PyTorch). is_training can be achieved by calling .train() on the Module. I’m not sure, what updates_collection, resuse and scope mean and the docs are quite confusing for me. Your layer would therefore look like: bn = nn.BatchNorm2d( num_features=features, affine=True, momentum=0.05 ).train() PS: some arguments and properties like affine and .train() are set by default, but I’ve added them for clarification.
st104009
Hi, I am trying to do sampling from a network (during training) in order to compute loss function. However, I am getting RuntimeError: cuda runtime error (2) : out of memory at /pytorch/aten/src/THC/generic/THCStorage.cu:58 if the sampling times is too large, which I don’t understand. The Pseudo-code (sorry, the actual code is very large): #sampling_network is pre-trained and no updates during this training for param in sampling_network.parameters(): param.requires_grad = False optimizer.zero_grad() sampling_times = N total_loss = 0. sampling_inputs = main_network(inputs) #do sampling for sampling_time in range(sampling_times): prediction = sampling_network(sampling_inputs) loss = compute_loss(prediction) total_loss += loss #fixed typo total_loss.backward() optimizer.step() In my case, the training is fine when N <=5, but throws “out of memory” error when N > 5. What I don’t understand is the memory usage should be regardless with the setting of N as the same sampling_network is just simply called multiple times. Am i missing something? Thanks,
st104010
What are you doing with total_loss? Currently you are storing the computation graph in it. If you just need it for printing, you should use: total_loss += loss.item() Or do you need it somewhere for a backward pass?
st104011
ptrblck: Or do you need it somewhere for a backward pass? Sorry, typo, it should be total_loss.backward() Also fixed in main thread.
st104012
OK, that makes sense. The memory usage won’t stay the same, since for each pass a new computation graph is created and stored. You could call .backward() in the for loop and optimizer.step() outside of it.
st104013
@ptrblck, Thanks. If I understand it correctly, calling .backward() with in the loop and step() outside of the loop will make the gradients to be computed at ever sampling time, and the trainable variables to be updated in the end of the sampling process. And this will have exactly the same effects (in terms of learning) to the network, but more memory efficient. Am I right?
st104014
Yes, you will save some memory but need more compute, since the gradients will be calculated in every step. Besides that it should be identical.
st104015
I’m not sure if this is a bug or If im being dumb. Running this code: ## Code example import numpy as np import torchvision import torch import time seed = int(time.perf_counter()) print('seed:',seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic=True #Define Model class MNISTAutoencoder(torch.nn.Module): def __init__(self): super(MNISTAutoencoder, self).__init__() self.encoder = torch.nn.Sequential(torch.nn.Linear(28*28,512,bias=True), torch.nn.Softplus(beta=1), torch.nn.Linear(512,256,bias=True), torch.nn.Softplus(beta=1), torch.nn.Linear(256,128,bias=True), torch.nn.Softplus(beta=1), torch.nn.Linear(128,32,bias=True), torch.nn.Softplus(beta=1),) self.decoder = torch.nn.Sequential(torch.nn.Linear(32,128,bias=True), torch.nn.Softplus(beta=1), torch.nn.Linear(128,256,bias=True), torch.nn.Softplus(beta=1), torch.nn.Linear(256,512,bias=True), torch.nn.Softplus(beta=1), torch.nn.Linear(512,28*28,bias=True), torch.nn.Sigmoid(),) def forward(self,x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded net = MNISTAutoencoder() loss = torch.nn.MSELoss() #Load Data trainset = torchvision.datasets.MNIST("./data/",download=True,train=True) X = [torchvision.transforms.ToTensor()(s[0]) for s in trainset] X = torch.cat(X).view(-1,28*28) nTrials = 11 #Get Parameters to make sure same is used across Trials pars = [p.data.clone() for p in net.parameters()] #1: CUDA Float if torch.cuda.is_available(): for i in range(nTrials): net_cuda = net.cuda() for (cuda_p,p) in zip(net_cuda.parameters(),pars): cuda_p.data = p.clone().cuda() X_cuda = X.cuda() X_cuda_var = torch.autograd.Variable(X_cuda,requires_grad=False) start = time.perf_counter() res = loss(net(X_cuda_var),X_cuda_var) stop = time.perf_counter() print('CUDA Float: {:.32f}'.format(np.float64(res)),type(net_cuda.parameters().__next__().data),type(X_cuda),'took',stop-start,'seconds') #2: CPU Float for i in range(nTrials): net_float = net.float() for (float_p,p) in zip(net_float.parameters(),pars): float_p.data = p.clone().float() X_float = X.float() X_float_var = torch.autograd.Variable(X_float,requires_grad=False) start = time.perf_counter() res = loss(net(X_float_var),X_float_var) stop = time.perf_counter() print('CPU Float: {:.32f}'.format(np.float64(res)),type(net_float.parameters().__next__().data),type(X_float),'took',stop-start,'seconds') #3: CUDA Double if torch.cuda.is_available(): for i in range(nTrials): net_cuda_double = net.double().cuda() for (cuda_double_p,p) in zip(net_cuda_double.parameters(),pars): cuda_double_p.data = p.clone().double().cuda() X_cuda_double = X.double().cuda() X_cuda_double_var = torch.autograd.Variable(X_cuda_double,requires_grad=False) start = time.perf_counter() res = loss(net(X_cuda_double_var),X_cuda_double_var) stop = time.perf_counter() print('CUDA Double: {:.32f}'.format(np.float64(res)),type(net_cuda_double.parameters().__next__().data),type(X_cuda_double),'took',stop-start,'seconds') #4: CPU Double for i in range(nTrials): net_double = net.double() for (double_p,p) in zip(net_double.parameters(),pars): double_p.data = p.clone().double() X_double = X.double() X_double_var = torch.autograd.Variable(X_double,requires_grad=False) start = time.perf_counter() res = loss(net(X_double_var),X_double_var) stop = time.perf_counter() print('CPU Double: {:.32f}'.format(np.float64(res)),type(net_double.parameters().__next__().data),type(X_double),'took',stop-start,'seconds') Gives a ~20% lower loss for 32bit floats, but ONLY when run on GPU. (This is consistent for different seeds.) The runtime suggests that the right precision is used on both GPU and CPU, yet I feel that the difference between CPU float and the other runs is way too large to be due to the lower precision. Does anybody see what’s going on? Thank you! seed: 7197644 CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.27543109748512506 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.031048773787915707 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.023138870485126972 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.02370053343474865 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.022951023653149605 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.022918391972780228 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.02192889992147684 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.021906440146267414 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.02196166105568409 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.021798920817673206 seconds CUDA Float: 0.24038340151309967041015625000000 <class 'torch.cuda.FloatTensor'> <class 'torch.cuda.FloatTensor'> took 0.02138354256749153 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.28088248707354 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.273789366707206 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.301917650736868 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.366850168444216 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.251176925376058 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.254637469537556 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.248044191859663 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.26183510106057 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.272330325096846 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.187176392413676 seconds CPU Float: 0.18305869400501251220703125000000 <class 'torch.FloatTensor'> <class 'torch.FloatTensor'> took 8.140838886611164 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.5673027914017439 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41811269149184227 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41235586535185575 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.4123460128903389 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41235347278416157 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41240311600267887 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.4124773908406496 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41238985676318407 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41240973211824894 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.4142442727461457 seconds CUDA Double: 0.24038340743650432607125821959926 <class 'torch.cuda.DoubleTensor'> <class 'torch.cuda.DoubleTensor'> took 0.41422911919653416 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.737960833124816 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.918829107657075 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.934827781282365 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.825709821656346 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.902172627858818 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.822428305633366 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.829005297273397 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.847982819192111 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.84829668328166 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.882735094055533 seconds CPU Double: 0.24038340743650035702394518466463 <class 'torch.DoubleTensor'> <class 'torch.DoubleTensor'> took 10.890244227834046 seconds System Info PyTorch version: 0.3.0.post4 Is debug build: No CUDA used to build PyTorch: 8.0.61 OS: CentOS Linux release 7.4.1708 (Core) GCC version: (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16) CMake version: version 2.8.12.2 Python version: 3.6 Is CUDA available: Yes CUDA runtime version: 9.0.176 GPU models and configuration: GPU 0: GeForce GTX 1080 Ti Nvidia driver version: 387.26 cuDNN version: Could not collect Versions of relevant libraries: [pip3] numpy (1.14.2) [pip3] torch (0.3.0.post4) [pip3] torchvision (0.2.0) [conda] Could not collect
st104016
I tried to debug your code and I think this problem is related to this issue 170 (I just tested the CPU side so far). You’ll get the same results, if your calculate the MSELoss manually: torch.mean((output32 - X_float_var)**2) > tensor(0.2477) torch.mean((output64 - X_double_var)**2) > tensor(0.2477, dtype=torch.float64) loss(output32, X_float_var) > tensor(0.1844) loss(output64, X_double_var) > tensor(0.2477, dtype=torch.float64)
st104017
I want to train a model from a folder of (hundreds of) .csv files. How can I load this data and feed it to my model without loading all of it into memory at once?
st104018
You can define a class, and for every step, you just read the data you need with the dataloader. For more information, you can read the tutorial below: https://pytorch.org/tutorials/beginner/data_loading_tutorial.html 256 Best wishes.
st104019
Thanks Jindong, I was reading through that tutorial, however is it possible to do something like: def get_data(path): df = pd.read_csv(path) return df.as_matrix data_sets = datasets.DatasetFolder(path_to_datasets, loader=get_data, extensions=['.csv']) train_loader = torch.utils.data.DataLoader(data_sets, batch_size=32, shuffle=False, num_workers=4) to read from all .csv files in the folder and train the model? (this gives an error, telling me data_sets is a method, but is anything along these line possible?).
st104020
Hi, That is because you forgot the () after the as_matrix. Try df.as_matrix() Best wishes.
st104021
Stumbled across something odd as I was playing around with tensor slicing. a = torch.arange(20).view(4, 5) # tensor([[ 0., 1., 2., 3., 4.], # [ 5., 6., 7., 8., 9.], # [ 10., 11., 12., 13., 14.], # [ 15., 16., 17., 18., 19.]]) If I use invalid indices for the first dimension (e.g., a[5:, :], a[4:4, :]), an error pops up (as expected). # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1) But when I use them for the second dimension, this happens: a[:, 5:] # tensor([ 5., 10., 15., 0.]) # Permutation of the first column? a[:, 4:4] # tensor([ 4., 9., 14., 19.]) # Squeezed final column Is this intentional/does this serve a purpose? Thanks in advance!
st104022
How can one feed variable size input to an LSTM layer? So I need the input to be : [batch, timestep, FEATURES], where FEATURES varies from example to example. Since I will be getting new examples constantly (model will have to do on-line training) padding is not an option.
st104023
That’s just not how LSTMs work - they use a linear layer (or two) under the hood and that won’t cope with varying feature size. You could, of course, manually reimplement LSTM (there also is one in the https://github/pytorch/benchmark 8 repository) and replace the linear with convolutions or so. I think this has been proposed somewhere in the literature. But all of this will leave the territory covered by PyTorch’s LSTM implementation. Best regards Thomas
st104024
Actually you can: batch_size = x.size()[0] x = torch.reshape(x, (batch_size, -1, 1)) layer, _ = self.LSTM(x.float()) it’s a workaround but it seems to do the job.
st104025
Ouch, my eyes hurt! More seriously: If that achieves what you need, great, but you have now used variable time length and a feature size of 1, no?
st104026
but you have now used variable time length and a feature size of 1, no? Yes. Ouch, my eyes hurt! Sorry about that, lad
st104027
In url: https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html 4 Gradients section, the Zi|xi = 6(xi+2) = 18 rather than 27?
st104028
No, x_i = 1, y_i = x_i + 2 = 3, z_i = y_i * y_i * 3 = 3 * 3 * 3 = 27. Best regards Thomas
st104029
I’m a total newbie and I’ve got this message below right before finishing PyTorch installation. Can anyone please tell me what is wrong with this? (base) C:\Users\Ju Hong Min>conda install pytorch cuda91 -c pytorch Solving environment: done Package Plan environment location: C:\ProgramData\Anaconda3 added / updated specs: - cuda91 - pytorch The following NEW packages will be INSTALLED: cuda91: 1.0-0 pytorch pytorch: 0.4.0-py36_cuda91_cudnn7he774522_1 pytorch [cuda91] Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: | WARNING conda.gateways.disk:exp_backoff_fn(49): Uncaught backoff with errno EEXIST 17 failed ERROR conda.core.link:_execute(502): An error occurred while installing package ‘None’. PermissionError(13, ‘Permission denied’) Attempting to roll back. Rolling back transaction: done PermissionError(13, ‘Permission denied’) FileExistsError(17, ‘File already exists. Cannot overwrite’)
st104030
Solved by ptrblck in post #2 Did you install conda as admin? The “permission denied” error seems to be pointing to it. Could you run the terminal as an admin and try it again?
st104031
Did you install conda as admin? The “permission denied” error seems to be pointing to it. Could you run the terminal as an admin and try it again?
st104032
@ptrblck Thank you so much. Problem solved. I uninstalled anaconda3 and re-installed the same anaconda3 x64, permission allowed to every user. But still had some other errors (https://github.com/conda/conda/issues/6053 52 & https://github.com/conda/conda/issues/6286 21) so I again uninstalled anaconda3 x64 and re-installed anaconda3 x32. This worked for me.
st104033
I am using pickle to save some tensors to files (pickle.dump), and later load them into memory (pickle.load). Some of the tensors are pretty large (the pickle file is about 220MB for one tensor). Dump takes several minutes but loading takes at least 20 minutes. Is pickle the fastest way to do this? Any suggestions to make it run faster? Thanks!
st104034
My apologies. Deserialization actually took only a few minutes – there was another bottleneck. But I still wonder if there’s a faster way for doing this than pickle.
st104035
There is torch.load/save . Some people use numpy-compatible interfaces (e.g. just npz, which should be pretty efficient, or hdf5 which is cross-platform and popular e.g. with keras). Best regards Thomas
st104036
This is an excerpt from the classic “Training a classifier” tutorial on PyTorch.org 9. The loss function and optimizer are defined as below: criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) in order to evaluate loss and update gradients to take an optimization step like so: outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() Forgive the possibly stupid question but where is the link between the loss function and optimizer object? All that optimizer needs for initiation seems to be the parameters of net which simply has the definitions of the linear, activation, softmax etc. Where do we tell the optimizer that it is the gradient of the loss function w.r.t these parameters that guides the step? In other words, the parameters are there but not what we are taking the gradient of.
st104037
The gradients are calculated during the loss.backward() call. You can try to print the gradients before and after this step using print(net.fc1.weight.grad). Before the backward pass the gradients will be empty, after it you will see some values. The optimizer just “knows” how to update the provided parameters using this gradient. You can find more information in this beginner tutorial 46.
st104038
Thanks for info, but I have gone through the tutorial at a high level. It is exactly how the optimizer knows that I am asking about. So, we have a loss function with gradients on the variables that decide (along with step size/learning rate) what the next values of variables should be. It seems odd that the construct - torch.optim instance - that takes the step knows only about the parameters ( it looks that way from the statement “optimizer = …” ) and not the loss function. How does it pick up gradient values correctly? In other words, what if I had another loss function on the same set of parameters (for e.g., loss_2 = nn.NLLLoss(outputs, labels) where outputs and labels are as above)? How would it know which gradient to use to take the next “step”? One pictures a setup where the forward-backward construct (net), the loss function and the optimizer have to work in tandem and not seeing it.
st104039
trengan: So, we have a loss function with gradients on the variables that decide (along with step size/learning rate) what the next values of variables should be. The loss function does not know the next values. It just calculates the current gradients for all necessary parameters. The optimizer uses these gradients of the provided parameters to update the weights. Some optimizers have a momentum term or other parameters for running averages. Have a look at e.g. Adam 7. So indeed the optimizer only needs to know which Parameters to update and how to do it. The needed gradient has to be provided by the backward pass of your loss function. trengan: In other words, what if I had another loss function on the same set of parameters (for e.g., loss_2 = nn.NLLLoss(outputs, labels) where outputs and labels are as above)? How would it know which gradient to use to take the next “step”? The gradients are accumulated by default. So in your case both loss functions would calculate the gradients which are summed for each parameter. That is also the reason you have so zero out the gradient before the next backward pass (optimizer.zero_grad() in your training code).
st104040
Pytorch version 0.4 I made my own LSTM modules and use it, then I compute loss with RMSLoss. When I call backward on that loss, I get this error. RuntimeError: Tensor: invalid storage offset at /pytorch/aten/src/THC/generic/THCTensor.c:759 What this error means and how can I solve this?
st104041
Met same problem here. Traceback (most recent call last): File "train.py", line 127, in <module> train() File "train.py", line 87, in train regression_loss.backward() File "/home/dd/anaconda3/lib/python3.6/site-packages/torch/tensor.py", line 93, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "/home/dd/anaconda3/lib/python3.6/site-packages/torch/autograd/__init__.py", line 89, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Tensor: invalid storage offset at /opt/conda/conda-bld/pytorch-cpu_1524582300956/work/aten/src/TH/generic/THTensor.cpp:761
st104042
Hi @richard, thanks for the concern. I attached my graph below. I debugged and find that the error may happen in torch.statck or torch.reshape operation. The T3_LSTM() is my original code and it could not do backward(). In T4_LSTM() I comment final output and it could do the backward(). Not sure if it is a bug or a mis-usage. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F BATCH_SIZE = 1 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class T1_LSTM(nn.Module): def __init__(self, input_channels, lstm_hidden_size=100, lstm_num_layers=2): super(T1_LSTM, self).__init__() self.lstm_1 = nn.LSTM(input_channels, lstm_hidden_size, lstm_num_layers, bias=False, bidirectional=True) self.lstm_2 = nn.LSTM(input_channels, lstm_hidden_size, lstm_num_layers, bias=False, bidirectional=True) self.lstm_1_states = ( torch.zeros((lstm_num_layers*2, BATCH_SIZE, lstm_hidden_size)).to(device), torch.zeros((lstm_num_layers*2, BATCH_SIZE, lstm_hidden_size)).to(device), ) self.lstm_2_states = ( torch.zeros((lstm_num_layers*2, BATCH_SIZE, lstm_hidden_size)).to(device), torch.zeros((lstm_num_layers*2, BATCH_SIZE, lstm_hidden_size)).to(device), ) def forward(self, first_chain, second_chain): lstm_1_out, self.lstm_1_states = self.lstm_1( first_chain, self.lstm_1_states) lstm_2_out, self.lstm_2_states = self.lstm_2( second_chain, self.lstm_1_states) return lstm_1_out[-1], self.lstm_1_states, lstm_2_out[-1], self.lstm_2_states class T2_LSTM(nn.Module): def __init__(self, input_channels, lstm_hidden_size=100, lstm_num_layers=2): super(T2_LSTM, self).__init__() self.lstm = nn.LSTM(input_channels, lstm_hidden_size, lstm_num_layers, bias=False, bidirectional=True) self.lstm_states = ( torch.zeros((lstm_num_layers*2, BATCH_SIZE, lstm_hidden_size)).to(device), torch.zeros((lstm_num_layers*2, BATCH_SIZE, lstm_hidden_size)).to(device), ) def forward(self, input, t1_states): lstm_out, self.lstm_states = self.lstm(input, t1_states) return lstm_out[-1] class T3_LSTM(nn.Module): def __init__(self, sequence_input_channels, lstm_hidden_size=100, lstm_num_layers=2): super(T3_LSTM, self).__init__() self.t1_lstm_1 = T1_LSTM(sequence_input_channels, lstm_hidden_size, lstm_num_layers) self.t1_lstm_2 = T1_LSTM(sequence_input_channels, lstm_hidden_size, lstm_num_layers) self.t2_lstm = T2_LSTM(sequence_input_channels, lstm_hidden_size, lstm_num_layers) def forward(self, input1, input2, input3): alpha_out_1, alpha_states_1, alpha_out_2, alpha_states_2 = self.t1_lstm_1( input2, input3) beta_out_1, beta_states_1, beta_out_2, beta_states_2 = self.t1_lstm_2( input3, input2) sum_states = ( torch.add(torch.add(alpha_states_1[0], alpha_states_2[0]), torch.add(beta_states_1[0], beta_states_2[0])), torch.add(torch.add(alpha_states_1[1], alpha_states_2[1]), torch.add(beta_states_1[1], beta_states_2[1])), ) p_out = self.t2_lstm(input1, sum_states) h_out = torch.add(torch.add(alpha_out_1, alpha_out_2), torch.add(beta_out_1, beta_out_2)) # stack alogn width out = torch.stack([torch.reshape(p_out, (BATCH_SIZE, 1, p_out.shape[1])), torch.reshape(h_out, (BATCH_SIZE, 1, h_out.shape[1]))], dim=1) return out class T4_LSTM(nn.Module): def __init__(self, sequence_input_channels, lstm_hidden_size=100, lstm_num_layers=2): super(T4_LSTM, self).__init__() self.t1_lstm_1 = T1_LSTM(sequence_input_channels, lstm_hidden_size, lstm_num_layers) self.t1_lstm_2 = T1_LSTM(sequence_input_channels, lstm_hidden_size, lstm_num_layers) self.t2_lstm = T2_LSTM(sequence_input_channels, lstm_hidden_size, lstm_num_layers) def forward(self, input1, input2, input3): alpha_out_1, alpha_states_1, alpha_out_2, alpha_states_2 = self.t1_lstm_1( input2, input3) beta_out_1, beta_states_1, beta_out_2, beta_states_2 = self.t1_lstm_2( input3, input2) sum_states = ( torch.add(torch.add(alpha_states_1[0], alpha_states_2[0]), torch.add(beta_states_1[0], beta_states_2[0])), torch.add(torch.add(alpha_states_1[1], alpha_states_2[1]), torch.add(beta_states_1[1], beta_states_2[1])), ) p_out = self.t2_lstm(input1, sum_states) h_out = torch.add(torch.add(alpha_out_1, alpha_out_2), torch.add(beta_out_1, beta_out_2)) # # stack alogn width # out = torch.stack([torch.reshape(p_out, (BATCH_SIZE, 1, p_out.shape[1])), # torch.reshape(h_out, (BATCH_SIZE, 1, h_out.shape[1]))], dim=1) return p_out, h_out def test_t3(): t = T3_LSTM(31) a = t.forward(torch.randn(15, 1, 31), torch.randn(115, 1, 31), torch.randn(125, 1, 31)) print(a.shape) a.backward(torch.randn(a.shape)) def test_t4(): t = T4_LSTM(31) a,b = t.forward(torch.randn(15, 1, 31), torch.randn(115, 1, 31), torch.randn(125, 1, 31)) print(a.shape) a.backward(torch.randn(a.shape), retain_graph=True) b.backward(torch.randn(b.shape)) # error happens test_t3() # works test_t4()
st104043
Met the same problem. I used torch.reshape in my code, but didn’t use torch.stack. Replacing torch.reshape with torch.view worked for my case. Supposedly, this is related to when someone depends on copying vs. viewing behavior 53. torch.reshape sometimes copies tensors internally, which can make gradient backward path disconnected. I hope some more detailed guides about when to use and when not to use torch.reshape to be added at docs. Related stackoverflow question: https://stackoverflow.com/questions/49643225/whats-the-difference-between-reshape-and-view-in-pytorch 52
st104044
Met the same issue when using torch.stack() (see last answer): Optimizing diagonal stripe code I need to get a diagonal stripe of the matrix. Say, I have a matrix of size KxN, where K and N are arbitrary sizes and K>N. Given a matrix: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] From it I would need to extract a diagonal stripe, in this case, a matrix MxV size that is created by truncating the original one: [[ 0 x x] [ 3 4 x] [ x 7 8] [ x x 11]] So the result matrix is: [[ 0 4 8] [ 3 7 11]] Now, an additional problem that I face is that I have a tensor of, say, s…
st104045
Same problem here, and I also used reshape. But before it worked well, until I changed argmax to slice, than this problem appeared
st104046
At the current time, it seems that model parameters trained on multiple GPU cannot be loaded to the model on the single GPU, nor reversely. For example, I trained my model on two GPUs and then when I test the model, I would like to use only one GPU. But the parameters loading failed. Does anyone has a solution?
st104047
Have you looked into the map_location arg here? https://github.com/pytorch/pytorch/blob/master/torch/serialization.py#L289 16
st104048
So in my case, how to write map_location? I have tried map_location=lambda storage, loc: storage to load all parameters to GPU and it does not work.
st104049
Many times after using a view or transpose function we need to manually apply the .contiguous() to make the tensor contiguous for further operations. Usually I get to know about this after getting an error saying make it contiguous. Is there any tip when to use contiguous option, it’s a bit irritating to wait for errors. Also I have seen that it changed between pytorch version. A code that works in pytorch 0.4 didnt work with pytorch .3 until I used the contiguous option.
st104050
Which operations are throwing this error for you? There shouldn’t really be any tensor contiguity expectations, so it’s probably a bug.
st104051
Hi, can’t reproduce error again sorry. But it comes a lot after reshape, squeeze and transpose operations. Link to a Past Question 41 I asked when I faced that error. Although I can’t reproduce it again , probably that error occurred in my model after alot of operations and (possibly) combined effect on them. Anyway thanks!!
st104052
Okay, sounds good. Thanks for the report, and if you run into it again please let us know!
st104053
I am trying to use ignore_index, which is a newly introduced keyword parameter for nn.CrossEntropyLoss(). I updated pytorch from source code and it is up to date. (bleeding edge version) The following is my code: criterion = nn.CrossEntropyLoss() for epoch in range(self.numEpoch): for batch in self.train_loader: user_idx = Variable(batch['user_idx']).cuda() item_vecs = Variable(batch['item_vecs'].float()).cuda() optimizer.zero_grad() pred = model(user_idx, item_vecs) loss = criterion(pred, item_vecs, ignore_index=-1) # I get the error here!! loss.backward() optimizer.step() I get the following error message when I call criterion(pred, item_vecs, ignore_index=-1) TypeError: "forward() got an unexpected keyword argument 'ignore_index'" I am tracking the source code, and I realized that the function forward() is from class CrossEntropyLoss() in torch/nn/modules/loss.py The initializer has the parameter ignore_index. (Refer to line 515 of torch/nn/modules/loss.py) Does anyone have any idea why this doesn’t work?
st104054
http://pytorch.org/docs/master/nn.html#torch.nn.CrossEntropyLoss 175 ignore_index should be specified when you construct the criterion function, ie, criterion = nn.CrossEntropyLoss(ignore_index = -1) And then you can use it elsewhere: criterion(output, target)
st104055
Hello, whenever I set ignore_index to -1 or 255 I face an error: line 1054, in nll_loss return torch._C._nn.nll_loss2d(input, target, weight, size_average, ignore_index, reduce) RuntimeError: cuda runtime error (59) : device-side assert triggered at /opt/conda/conda-bld/pytorch_1518238409320/work/torch/lib/THCUNN/generic/SpatialClassNLLCriterion.cu:131 However, I need to set ignore_index to 255 or -1.
st104056
Are you running into this issue? I can’t seem to reproduce it, can you provide some code or the inputs that this is failing on?
st104057
I’m trying to setup the environment for the course fast.ai on my local Mac computer which has the NVIDIA GeForce GT 750M, with 386 CUDA cores, which I would like to take advantage of… I already have everything setup, the driver, the cuda toolkit, the cudnn libs, everything is detailed at this link: Deep Learning Course Forums – 22 Jun 18 MAC with GPU? 10 Today is June 21, 2018, I’d like to have the environment installed in my MacOSX, which has the NVIDIA GeForce GT 750M, which has 384 CUDA Cores… according to this:... the las comment is me… I detail every step I have gone into… I have no error at compilation and everything is solved… however when execute a line of the fast.ai library I see the following error: Screen Shot 2018-06-27 at 5.15.49 PM.png794×97 17.2 KB What it means? am I out of luck ? The video card has 386 CUDA cores, I just want for test and the course if I need something heavy probably will look into another setup to run heavy data computations but for this course, I’d like to have my laptop to run jupyter notebooks, I cannot believe that spite meeting all requirements from nvidia, the CUDA support 3.0, etc… I’m stuck at pytorch unable to process my GPU, can anyone really give me some insight, what is the problem, because so far from NVIDIA side, I’ve meet all requirements and the libraries are installed CUDA Toolkit, Drivers, cuDNN, and pytorch compiled, but I see one error there: /Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu:222:134: warning: self-comparison always evaluates to true [-Wtautological-compare] switch (memType) { case CUDAHistogramMemoryType::SHARED: (__cudaPushCallConfiguration(grid, block, (CUDAHistogramMemoryType::SHARED == CUDAHistogramMemoryType::SHARED) ? sharedMem : (0), at::globalContext().getCurrentCUDAStream())) ? (void)0 : kernelHistogram1D< output_t, input_t, int64_t, 1, 2, 1, CUDAHistogramMemoryType::SHARED> (aInfo, pInfo, bInfo, binsize, totalElements, getWeightsOp); if (!((cudaGetLastError()) == (cudaSuccess))) { throw Error({__func__, "/Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu", 222}, at::str(at::str("cudaGetLastError() == cudaSuccess", " ASSERT FAILED at ", "/Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu", ":", 222, ", please report a bug to PyTorch. ", "kernelHistogram1D failed"))); } ; ; break; case CUDAHistogramMemoryType::MULTI_BLOCK: (__cudaPushCallConfiguration(grid, block, (CUDAHistogramMemoryType::MULTI_BLOCK == CUDAHistogramMemoryType::SHARED) ? sharedMem : (0), at::globalContext().getCurrentCUDAStream())) ? (void)0 : kernelHistogram1D< output_t, input_t, int64_t, 1, 2, 1, CUDAHistogramMemoryType::MULTI_BLOCK> (aInfo, pInfo, bInfo, binsize, totalElements, getWeightsOp); if (!((cudaGetLastError()) == (cudaSuccess))) { throw Error({__func__, "/Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu", 222}, at::str(at::str("cudaGetLastError() == cudaSuccess", " ASSERT FAILED at ", "/Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu", ":", 222, ", please report a bug to PyTorch. ", "kernelHistogram1D failed"))); } ; ; break; default: (__cudaPushCallConfiguration(grid, block, (CUDAHistogramMemoryType::GLOBAL == CUDAHistogramMemoryType::SHARED) ? sharedMem : (0), at::globalContext().getCurrentCUDAStream())) ? (void)0 : kernelHistogram1D< output_t, input_t, int64_t, 1, 2, 1, CUDAHistogramMemoryType::GLOBAL> (aInfo, pInfo, bInfo, binsize, totalElements, getWeightsOp); if (!((cudaGetLastError()) == (cudaSuccess))) { throw Error({__func__, "/Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu", 222}, at::str(at::str("cudaGetLastError() == cudaSuccess", " ASSERT FAILED at ", "/Users/josepen/Development/pytorch/aten/src/ATen/native/cuda/SummaryOps.cu", ":", 222, ", please report a bug to PyTorch. ", "kernelHistogram1D failed"))); } ; ; } Not sure is says: please report a bug to PyTorch.
st104058
Hello, I am quite new to this topic and I have the following question. This is the code for network. I would like to use this code to make prediction just for one picture. This picture will undertaken some preprocessing and than directly past through the network. I don’t know how to change the code, so that it is possible just to load one picture and the data_loader isn’t necessary. Any suggestion ? # -*- coding: utf-8 -*- import argparse import os import shutil import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision.transforms as transforms import torchvision.datasets as datasets import densenet as dn import timeit import numpy as np img_dir = 'pictures' checkpoint = torch.load('modelbest.pth.tar') model = dn.DenseNet3() model.load_state_dict(checkpoint['state_dict']) batchSize = 1 positive_class = 0 negative_class = 1-positive_class normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]], std=[x/255.0 for x in [63.0, 62.1, 66.7]]) transform_test = transforms.Compose([ transforms.ToTensor(), normalize ]) data = datasets.ImageFolder(root=img_dir, transform=transform_test) data_loader = torch.utils.data.DataLoader( data, batch_size=batchSize, shuffle=False) model.eval() start = timeit.default_timer() correct = 0.0 total = 0 TP = 0 TN = 0 FP = 0 FN = 0 fp_index = [] fn_index = [] lenData = len(data) for i, (input, target) in enumerate(data_loader): input_var = torch.autograd.Variable(input, volatile=True) target_var = torch.autograd.Variable(target, volatile=True) output = model(input_var) _, predicted = torch.max(output.data, 1) correct += (predicted.cpu() == target.cpu()).sum() predicted = predicted.cpu().numpy() target = target.cpu().numpy() for i in range(predicted.size): if predicted[i][0]==positive_class and target[i]==positive_class: # True Positive. TP +=1 if predicted[i][0]==negative_class and target[i]==negative_class: # True Negative. TN +=1 if predicted[i][0]==positive_class and target[i]==negative_class: # False Positive. FP +=1 fp_index.append(total+i) if predicted[i][0]==negative_class and target[i]==positive_class: # False Negative. FN +=1 fn_index.append(total+i) total += len(target) print ('\nAccuracy %.2f %%' % (100 * correct/total)) print('Calculation Time: %.2fs' % (timeit.default_timer() - start)) print('Data: %d' % total) print('True Positive: %d' % TP) print('True Negativ: %d' % TN) print('False Positive: %d' % FP) print('False Negativ: %d' % FN) print('\nFalse Positives') for i in fp_index: print data.imgs[i] print('\nFalse Negatives') for i in fn_index: print data.imgs[i]
st104059
You could use this as a starter code (I’ve skipped the loading of the state_dict etc.): image = Image.open(YOUR_PATH) x = transform_test(image) # If you are using PyTorch < 0.4.0 x = Variable(x, volatile=True) # Else you would use: with torch.no_grad(): model.eval() output = model(x) ...
st104060
I am trying to train on around 200G of .npy files. I have a custom image class: class CustomImageFolder(ImageFolder): def __init__(self, root, transform=None): super(CustomImageFolder, self).__init__(str(root),transform) def __getitem__(self, index): path = self.imgs[index][0] img = np.load(path) img /= 255 # normalization return img root = Path(dset_dir).joinpath('ZebraFish/train/') transform = None train_kwargs = {'root':root, 'transform':transform} dset = CustomImageFolder train_dataset = dset(**train_kwargs) train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True, drop_last=True) I’m getting the following error: RuntimeError: Found 0 files in subfolders of: data/ZebraFish/train Supported extensions are: .jpg,.jpeg,.png,.ppm,.bmp,.pgm,.tif. I see that the default loader function 3 will create a PIL object. Although since I’m working with .npy is there a simple way around this? Is there a way to make the dataLoader have this same massive functionality with .npy files? All the best
st104061
Solved by ptrblck in post #2 Sure! You don’t need to inherit from ImageFolder. Just create your own Dataset and load your numpy arrays as you want: class MyDataset(Dataset): def __init__(self, root, transform=None): self.image_paths = os.glob.(... # get your numpy array paths here def __getitem__(self, index)…
st104062
Sure! You don’t need to inherit from ImageFolder. Just create your own Dataset and load your numpy arrays as you want: class MyDataset(Dataset): def __init__(self, root, transform=None): self.image_paths = os.glob.(... # get your numpy array paths here def __getitem__(self, index): img = np.load(self.image_paths[index]) ... def __len__(self): return len(self.image_paths)
st104063
I have defined my Net with 1 input and 1 out,but trained with 100 inputs, now How can I use 1 input to get 1 output
st104064
Based on your model description, your input should have the dimensions [batch_size, 1]. Your output will therefore have the same dims. Each sample has only one feature and the model outputs one prediction for each sample. If you would like to pass only one sample, you could call model(x[0]).
st104065
Here is a small example: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.hidden = nn.Linear(1, 10) self.predict = nn.Linear(10, 1) def forward(self, x): x = F.relu(self.hidden(x)) x = self.predict(x) return x model = MyModel() batch_size = 10 x = torch.randn(batch_size, 1) output = model(x) print(output.shape) > torch.Size([10, 1]) output = model(x[0]) # Only first sample print(output.shape) > torch.Size([1]) Is this what you are looking for?
st104066
Yes, exactly, and I want to also know, for example, if I want to set the Import x=0.5, how should I write. Thank you very much.
st104067
Building PyTorch From source. My platform is: OS: CentOS CPU: IBM Power8 GPU: NVIDIA P100 CUDA: 9.0 Python: Miniconda 3.6 The error shows up at 86% of NVCC building. The error message starts as: [ 86%] Building NVCC (Device) object caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/ATen/native/cuda/caffe2_gpu_generated_SpectralOps.cu.o /ccs/home/sajaldash/pytorch/aten/src/ATen/cuda/CUDAHalf.cu(27): error: identifier "__half_raw" is undefined /ccs/home/sajaldash/pytorch/aten/src/ATen/cuda/CUDAHalf.cu(34): error: identifier "__half_raw" is undefined /ccs/home/sajaldash/pytorch/aten/src/ATen/cuda/CUDAHalf.cu(40): error: identifier "__half_raw" is undefined /ccs/home/sajaldash/pytorch/aten/src/ATen/cuda/CUDAHalf.cu(46): error: identifier "__half_raw" is undefined /ccs/home/sajaldash/pytorch/aten/src/ATen/cuda/CUDAHalf.cu(52): error: identifier "__half_raw" is undefined 5 errors detected in the compilation of "/tmp/tmpxft_00008a8e_00000000-6_CUDAHalf.cpp1.ii". CMake Error at caffe2_gpu_generated_CUDAHalf.cu.o.Release.cmake:279 (message): Error generating file /ccs/home/sajaldash/pytorch/build/caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/ATen/cuda/./caffe2_gpu_generated_CUDAHalf.cu.o The bottom part of the error message is: make[2]: *** [caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/caffe2_gpu_generated_THCTensorMathScan.cu.o] Error 1 8 errors detected in the compilation of "/tmp/tmpxft_000092b2_00000000-6_THCTensorIndex.cpp1.ii". CMake Error at caffe2_gpu_generated_THCTensorIndex.cu.o.Release.cmake:279 (message): Error generating file /ccs/home/sajaldash/pytorch/build/caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/./caffe2_gpu_generated_THCTensorIndex.cu.o make[2]: *** [caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/caffe2_gpu_generated_THCTensorIndex.cu.o] Error 1 6 errors detected in the compilation of "/tmp/tmpxft_00009329_00000000-6_THCTensorMode.cpp1.ii". CMake Error at caffe2_gpu_generated_THCTensorMode.cu.o.Release.cmake:279 (message): Error generating file /ccs/home/sajaldash/pytorch/build/caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/./caffe2_gpu_generated_THCTensorMode.cu.o make[2]: *** [caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/caffe2_gpu_generated_THCTensorMode.cu.o] Error 1 make[1]: *** [caffe2/CMakeFiles/caffe2_gpu.dir/all] Error 2 make: *** [all] Error 2 Failed to run 'bash tools/build_pytorch_libs.sh --use-cuda --use-nnpack nccl caffe2 nanopb libshm gloo THD c10d' Any idea?
st104068
error_pytorch.PNG1098×260 13.4 KB I used following code to save model weights. It successfully saves for first time and but throws error while saving weights second time. The error is shown in the attached snapshot. What could be the possible solution? state = model.state_dict() def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): """Save checkpoint if a new best is achieved""" torch.save(state, filename) if is_best: print('\t=> Saving new best weights') shutil.copyfile(filename,'model_bestweights.pth.tar') #save checkpoint else: print('\t=> Validation accuracy did not improve')
st104069
I have the following network resnet18 = models.resnet18(pretrained=True) fc_ftrs = resnet18.fc.in_features resnet18.fc = nn.Linear(fc_ftrs,self.numClasses) I want to use small learning rate at for the base of my network (finetuning) and different for the fully connected. If my optimizer is defined as follows : RMSprop([{resnet18.parameters(), 'lr': 1e-6}, {resnet18.fc.parameters(), 'lr': 5e-4}]) will both learning rates added up for the fully connected layer or will the second override?
st104070
Solved by tom in post #6 Sorry for posting a wrong solution before. The reason it does not work as expected is because python’s in tries to use ==, and that will not identify tensors. Using the parameter names will work (you could also hack around it by keeping a set of p.data_ptr() and filter by that, but that is ugly…): …
st104071
[Edit: The original suggestion is broken, my apologies, see blow!] Did you actually try? Any recent version of PyTorch should give you an error 10. You can get rid of those by using fc_params = list(resnet18.fc.parameters()) other params = [p for p in resnet18.parameters() if p not in fc_params] or so. Best regards Thomas
st104072
I was actually gonna try it, your method is pretty simple! Thanks will use this!
st104073
Hi I tried your approach, I get the following error RuntimeError: The size of tensor a (7) must match the size of tensor b (2048) at non-singleton dimension 3 The 7 sized tensor is probably due to the 7x7 convolution in resnet!
st104074
For now I have resolved it as list(resnet.parameters())[:-2] for the base parameters Is the any other suggested approach for this!??
st104075
Sorry for posting a wrong solution before. The reason it does not work as expected is because python’s in tries to use ==, and that will not identify tensors. Using the parameter names will work (you could also hack around it by keeping a set of p.data_ptr() and filter by that, but that is ugly…): fc_params = [p for n,p in m.named_parameters() if not n.startswith('fc.')] other_params = [p for n,p in m.named_parameters() if n.startswith('fc.')] Best regards Thomas
st104076
Do you think that instead of raising error parameters appear in more than one parameter group if we support overriding the learning rate it would be simpler? Like for my use case it woulf have been much simpler, ofcourse it creates possibility of mistakes from user side but in my opinion more positive than negative!
st104077
To be honest, I think that is is a very special application where you need this and don’t have it conveniently available. For example, (I think) the fast.ai library (Jeremy Howard advocates a graded learning rate for finetuning) library sticks the various modules in a Sequential module and then gets the parameter groups by iterating over the submodules. The other option is to use the parameter names, there probably are more elegant solutions than the above if you need it in a systematic way.
st104078
Hello, I was wondering how to handle 2D input data while doing a 1D convolution in PyTorch. This nice answer handles three situations: https://stats.stackexchange.com/questions/292751/is-a-1d-convolution-of-size-m-with-k-channels-the-same-as-a-2d-convolution-o/292791 495 I am interested in the second example: I have multiple 1D vectors of the same length that I can combine into a 2D matrix as input, and I want a 1D array as output. I would like to do a 1D convolution with 1 channel, a kernelsize of n×1 and a 2D input, but it seems that this is not possible in PyTorch as the input shape of Conv1D is minibatch×in_channels×iW (implying a height of 1 instead of n). My question is, how can I do a 1D convolution with a 2D input (aka multiple 1D arrays stacked into a matrix)? Thanks in advance.
st104079
Solved by ptrblck in post #2 The second example is using basically a 2D convolution where the kernel height is equal to the input height. This code should yield the desired results: batch_size = 1 channels = 1 height = 3 length = 10 kernel_size = (height, 5) x = torch.randn(batch_size, channels, height, length) conv = nn.Co…
st104080
The second example is using basically a 2D convolution where the kernel height is equal to the input height. This code should yield the desired results: batch_size = 1 channels = 1 height = 3 length = 10 kernel_size = (height, 5) x = torch.randn(batch_size, channels, height, length) conv = nn.Conv2d( in_channels=1, out_channels=1, kernel_size=kernel_size, stride=1, padding=(0, 2) ) output = conv(x) print(output.shape) > torch.Size([1, 1, 1, 10])
st104081
Considering this model for an autoencoder, I am unable to fit it within a NVIDIA GTX 1070 GPU. How can I use batches to fit this within my GPU? class Autoencoder(nn.Module): def __init__(self, ): super(Autoencoder, self).__init__() self.fc1 = nn.Linear(NUM_COLS, 25000) self.fc2 = nn.Linear(25000, 15000) self.fc3 = nn.Linear(15000, 2000) self.fc4 = nn.Linear(2000, 500) self.fc5 = nn.Linear(500, 100) self.fc6 = nn.Linear(100, 500) self.fc7 = nn.Linear(500, 2000) self.fc8 = nn.Linear(2000, 15000) self.fc9 = nn.Linear(15000, 25000) self.fc10 = nn.Linear(25000, NUM_COLS) self.relu = nn.ReLU() self.softmax = nn.Softmax() def forward(self, x): x1 = self.relu(self.fc1(x)) x2 = self.relu(self.fc2(x1)) x3 = self.relu(self.fc3(x2)) x4 = self.relu(self.fc4(x3)) x5 = self.relu(self.fc5(x4)) x6 = self.relu(self.fc6(x5)) x7 = self.relu(self.fc7(x6)) x8 = self.relu(self.fc8(x7)) x9 = self.relu(self.fc9(x8)) x10 = self.relu(self.fc10(x9)) return x1, x2, x3, x4, x5, x6, x7, x8, x9, x10 model = Autoencoder().double() if cuda: model = model.cuda() criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=1e-4, weight_decay=1e-5) t_X = Variable(torch.from_numpy(X), requires_grad=False) if cuda: t_X = t_X.cuda() print('Start training') for epoch in range(num_epochs): # ===================forward===================== output = model(t_X)[-1] loss = criterion(output, t_X) # ===================backward==================== optimizer.zero_grad() loss.backward() optimizer.step() # ===================log======================== print('epoch [{}/{}], loss:{:.4f}' .format(epoch + 1, num_epochs, loss.data[0]))
st104082
Hi All, In the data preparation phase for my network, I read an image one at a time, and then, I want to extract several patches from this image as my mini-batch. In other words, the data preparation consists of two steps: 1) read an image and 2) extract random patches to form the mini-match. What’s the proper way to use BatchSampler to implement this? Thanks, Saeed
st104083
Solved by ptrblck in post #2 You could just sample in __getitem__ and stack the patches into the batch dimension: Here is a small example sampling 5x5 patches. These patches are returned as a 4-dimensional tensor from __getitem__. During the training you could push these patches into the batch dimension with view. class MyDat…
st104084
You could just sample in __getitem__ and stack the patches into the batch dimension: Here is a small example sampling 5x5 patches. These patches are returned as a 4-dimensional tensor from __getitem__. During the training you could push these patches into the batch dimension with view. class MyDataset(Dataset): def __init__(self): self.data = torch.randn(100, 3, 24, 24) def __getitem__(self, index): # Get current image image = self.data[index] # Sample patches patches = self.sample_pathes(image) return patches def sample_pathes(self, image): # Your sampling logic size = 5 patches = [] for i in range(5): patch = image[:, i:i+size, i:i+size] patches.append(patch) patches = torch.stack(patches) return patches def __len__(self): return len(self.data) dataset = MyDataset() loader = DataLoader( dataset, batch_size=10, shuffle=False, num_workers=2 ) loader_iter = iter(loader) x = loader_iter.next() x = x.view(-1, 3, 5, 5)
st104085
I create two neural network models m1 and m2, however when I modify the weights in m1, the weights in m2 are modified as well. I suspected I am not instantiating them properly, however they do have different memory addresses. I have also tried creating a custom class based on nn.module instead of using nn.sequential but the issue remains. Any help much appreciated. The issue is demonstrated as follows: from collections import namedtuple, OrderedDict import torch import torch.nn as nn # if gpu is to be used device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def init_weights(m): if type(m) == nn.Linear: m.weight.data.fill_(0.2) m.bias.data.fill_(1.0) D_in = 4 H = 8 D_out = 2 net_spec = OrderedDict([('0', torch.nn.Linear(D_in, H)), ('1', torch.nn.ReLU()), ('2', torch.nn.Linear(H, D_out))]) m1 = torch.nn.Sequential(net_spec) m2 = torch.nn.Sequential(net_spec) print('object addresses:') print(' m1 :',hex(id(m1))) print(' m2 :',hex(id(m2))) print("\nm1 weights:\n",m1.state_dict()['0.weight']) print("\nm2 weights:\n",m2.state_dict()['0.weight']) m1.apply(init_weights) print('m1 weights updated') print("\nm1 weights:\n",m1.state_dict()['0.weight']) print("\nm2 weights:\n",m2.state_dict()['0.weight']) output: object addresses: m1 : 0x7f893cbe91d0 m2 : 0x7f893cbe92e8 m1 weights: tensor([[-0.4047, 0.1752, -0.1989, -0.2917], [-0.0466, -0.0044, 0.1561, 0.2465], [ 0.0700, -0.3357, -0.4978, -0.0837], [-0.0248, -0.2826, -0.4564, -0.0516], [-0.0024, -0.1732, -0.4144, -0.3790], [-0.3075, 0.2768, -0.2676, 0.4495], [-0.4929, 0.1328, -0.3153, -0.4591], [-0.0597, 0.3718, 0.0522, 0.0899]]) m2 weights: tensor([[-0.4047, 0.1752, -0.1989, -0.2917], [-0.0466, -0.0044, 0.1561, 0.2465], [ 0.0700, -0.3357, -0.4978, -0.0837], [-0.0248, -0.2826, -0.4564, -0.0516], [-0.0024, -0.1732, -0.4144, -0.3790], [-0.3075, 0.2768, -0.2676, 0.4495], [-0.4929, 0.1328, -0.3153, -0.4591], [-0.0597, 0.3718, 0.0522, 0.0899]]) m1 weights updated m1 weights: tensor([[ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000]]) m2 weights: tensor([[ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000], [ 0.2000, 0.2000, 0.2000, 0.2000]]) Solution Found: I found two ways to create the second model m2 that does not have the issue. m2 = torch.nn.Sequential(copy.deepcopy(net_spec)) or m2 = copy.deepcopy(m1) It seems strange to me that the instantiation of the network is tied to the instance OrderedDict() passed to the class to instantiate the model. If anyone can enlighten me it would be appreciated.
st104086
Solved by justusschock in post #4 Additionally python (just like the pytorch-C-backend) used something similar to call by reference. Thus the sequential class only receives a reference of the OrderedDict which only holds references of the layers.
st104087
You’re right, it is related to the OrderedDict you’re using to instantiate the nn.Sequential modules. Because PyTorch is imperative whenever you write PyTorch code it is executed immediately, so when yo do net_spec = OrderedDict([('0', torch.nn.Linear(D_in, H)), ('1', torch.nn.ReLU()), ('2', torch.nn.Linear(H, D_out))]) you’re actually instantiating a linear module with dims. [D_in, H], a relu module and another linear with dims [H, D_out]. These modules are grouped in your OrderedDict and when you pass this to nn.Sequential what happens is that you wrap those SAME modules that are already created in a new Sequential module. So the two Sequential modules are indeed different instances, but they both wrap the same underlying Linear modules: id(net_spec['0']) == id(m1[0]) == id(m2[0]) # Same nn.Linear instance
st104088
Additionally python (just like the pytorch-C-backend) used something similar to call by reference. Thus the sequential class only receives a reference of the OrderedDict which only holds references of the layers.
st104089
The current method of saving a model seems to be this: https://cs230-stanford.github.io/pytorch-getting-started.html#saving-and-loading-models 198 What if I trained a model for 50 epochs, but notice the model starts to overfit at the 40th epoch. How can I save/load the model weights at the 40th epoch?
st104090
You can call torch.save() 90 multiple times in your training routine and save the model’s data in different output files.
st104091
Recommended approach path = os.path.join(SAVE_DIR, 'model.pth') torch.save(MODEL.cpu().state_dict(), path) # saving model MODEL.cuda() # moving model to GPU for further training
st104092
Does torch.save() overwrite the previous saved model, or can I save multiple models?
st104093
If you save it into another buffer or file it will not overwrite the previous one. So if you follow the recommended approach 174 @alwynmathew mentioned, you can for example use the number of the current epoch in the filename. Example: model is the model to save epoch is the counter counting the epochs model_dir is the directory where you want to save your models in For example you can call this for example every five or ten epochs. torch.save(model.state_dict(), os.path.join(model_dir, 'epoch-{}.pt'.format(epoch)))
st104094
So if I call that function at a certain epoch (say every 10), it will save it as a new file under epoch-number.pt? Thanks!
st104095
Small correction on @mteser answer: torch.save(model.state_dict(), os.path.join(model_dir, 'epoch-{}.pth'.format(epoch)))
st104096
I also found examples in the documentation which use .pt instead of .pth, for example here 43, but also some that use .pth in examples. It is just a name, but is somewhere one file-suffix explicitely recommended?
st104097
Which extension should be used for saving the model: torch.save(model.state_dict(), os.path.join(model_dir, 'epoch-{}.pth'.format(epoch))) link 35 or torch.save(model.state_dict(), os.path.join(model_dir, 'epoch-{}.pt'.format(epoch))) link 21
st104098
I don’t think there’s preference of one over the other, it’s just a convention like .pkl or .pck or .pickle, but by convention from python docs, we go with .pkl similarly, we are choosing .pth here. It doesn’t matter. similar forum_post 77 and SO answer 88
st104099
When you divide a tensor of size (64,128,32,32) by a tensor of size (64,1,32,32) you get an error because the size must match, yet in situations like these expand() is implicit and numpy does it this way. torch’s div() doesn’t operate that way, am I missing something or is this intentional? The solution is of course expand_as() but the fact that it’s not default leads me to believe that perhaps I missed something.