id
stringlengths
3
8
text
stringlengths
1
115k
st99168
IMO, you don’t need to implement a class as you pasted. In that case, implementing your loss function using torch and/or torch.nn.functional functions. Then, pytorch will do backprop automatically.
st99169
I can obtain loss value like this print(last_loss_v) # tensor([3.0082], device='cuda:0') But I can’t see grad value from print(last_loss_v.grad) # None And when I try this last_loss_v.backward() This erros shows up RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn What I want is to update CNN weights until this loss tensor([3.0082], device=‘cuda:0’) minimizes enough Would you inform me some guides about points what I incorrectly did and how to solve above errors?
st99170
Oh, really? One thing I define loss function using torch functions is this and it could backprop. https://github.com/crcrpar/pytorch.sngan_projection/blob/master/losses.py 653
st99171
I’ve read your loss function but I can’t see what is the difference except you use torch and F’s operation (like torch.mean(), F.softplus()) at the end of each function This is code I’m writing https://github.com/youngminpark2559/test/tree/master/update_CNN Would you tell me what is the difference? Generating network https://github.com/youngminpark2559/test/blob/master/update_CNN/train/train.py#L65 Obtaining prediction https://github.com/youngminpark2559/test/blob/master/update_CNN/train/train.py#L97 Calculating loss https://github.com/youngminpark2559/test/blob/master/update_CNN/train/train.py#L102 Updating network https://github.com/youngminpark2559/test/blob/master/update_CNN/train/train.py#L170
st99172
I think these 2 lines 37 are wrong . detach() does Returns a new Tensor, detached from the current graph. The result will never require gradient. https://pytorch.org/docs/stable/autograd.html?highlight=detach#torch.Tensor.detach 17
st99173
Yeah. I’ll find how to resize torch tensor image by not using detach() and numpy(). But without using detach() and numpy(), and with the circumstance where I change this sentence https://github.com/youngminpark2559/test/blob/master/update_CNN/train/train.py#L164 to en_i_loss=Variable(en_i_loss,requires_grad=True) All epochs can be done. But loss value still shows constant, which means CNN is not updated like this Total number of parameters: 224481 en_i_loss tensor(8.7888, device='cuda:0', requires_grad=True) en_i_loss.grad tensor(1., device='cuda:0') Saved model at end of iteration en_i_loss tensor(8.7888, device='cuda:0', requires_grad=True) en_i_loss.grad tensor(1., device='cuda:0') Saved model at end of iteration en_i_loss tensor(8.7888, device='cuda:0', requires_grad=True) en_i_loss.grad tensor(1., device='cuda:0') Saved model at end of iteration Saved model at end of epoch Train finished And above CNN not being updated issue was my first issue. Implementing custom loss function is attempt to resolve that first issue.
st99174
I think I’ve solved this issue. I shouldn’t have broken backpropagation graph by newly and unnecessarily wrapping torch Variable tensor in loss_functions.py. Newly wrapping torch tensor by Variable() deletes grad values. In conclusion, I checked and made all torch Variable tensors print grad_fn by using this print(torch_Variable_tensor.grad_fn) # <MeanBackward1 object at 0x7f1ebc889da0> If all torch tensors print grad_fn information, that means backpropagation graph is well connected and means you can perform backpropagation by using loss.backward()
st99175
Hi everyone Data I am trying to train a model in the biomedical domain with a rather specialized task (flow prediction). My input consists of video clips and I would like to predict either a single image or a video. I have pixel wise ground truth for every frame of the video but the number of videos is very limited. Architecture Architecture wise I am considering a CNN, RNN combination where the CNN provides a representation of the input frames for the RNN to learn about the temporal relationship between input frames. Now my question is: What kind of CNN do I use and on what do I pretrain it? Since I am working with biomedical data I would assume image net as well as most other image data sets do not really help as the image content is very different. Are there data sets/tasks/networks I could use for this purpose?
st99176
What kind of medical images are you dealing with? Since you are dealing with flow I would assume some kind of US doppler? Depending on your image modality you might find some open source data sources. If your use case is academic it might be even simpler, as not so many are on CC0. How many videos / images do you have? Maybe you could indeed start with a standard pre-trained model and fine tune through all layers, if you have enough images.
st99177
The input is pure RGB video of blood vessels captured by a microscope. In terms of data set I currently have about 50 clips of around a minute of varying quality. Do you think a pretrained model would adjust to the very different domain?
st99178
Hi masus04, I have previously worked on medical image analysis and was recently able to use imagenet pretrained networks available in pytorch on ultrasound images and get really good results. I didn’t freeze any layer and experimented with a few hyperparameters. Overall, I think it would be a good idea to try out these pretrained models and then move to your own domain specific pretrained models, if the former does not work.
st99179
Hi Mazhar So you loaded a pretrained imagenet CNN and used some hidden layer’s output for your representation? I’ll definitely try it, thank you.
st99180
Hi, I can confirm what @Mazhar_Shaikh said. I worked with cell images (pretty far from ImageNet as well) and pre trained model on Image net improved a lot my results. As Mazhar said, I did not freeze the layers and just used the pre trained weights as initialization for my own training for the corresponding section of my network (encoder of a Unet). Good luck
st99181
According to my understanding, layer normalization is to normalize across the features (elements) of one example, so all the elements in that example should (1) use the same mean and variance computed over the example’s elements themselves. (2) scale and bias via the same parameter gamma and beta i.e. different elements in one example should use the same normalization parameters, not different parameters for each element. (not per-element) However, in the officail doc of nn.LayerNorm , a note says "Unlike Batch Normalization and Instance Normalization, which applies scalar scale and bias for each entire channel/plane with the affine option, Layer Normalization applies per-element scale and bias with elementwise_affine " I think this is confusing… I wonder if there is a mistake in the doc or the implementation is truly as the note says, or if my understanding of layer normalization is wrong. (paper is at https://arxiv.org/abs/1607.06450 16) Can anyone give me some suggestions ?
st99182
PyTorch LN is correct. In Sec. 5.1 of the original paper, . They also learn an adaptive bias b and gain g for each neuron after the normalization.
st99183
Thanks for your correction. So is the following understanding correct? Assuming the input minibatch is of size (N, C, H, W). For each example, the elements in all channels (CHW elements) are used to compute the mean and variance to normalize that example, and there are NCHW scale and bias parameters for each element in each channel of each example.
st99184
Mostly correct! But there are only CHW scale and bias parameters because N is the batch dimension. This is all based on the assumption that you normalize over the last 3 dimensions. Actually in channeled data, it is unclear whether you should normalize over the channel dimension or not.
st99185
So if I do not normalize over channel dimension, I would: (1) normalize over HW elements for each channel of each example in a minibatch (i.e. compute NC mean and variance values) (2) use scale and bias parameters for each element in the same channel of every examples in the minibatch (i.e. CHW scale and bias parameters) Am I correct ?
st99186
gdp: (2) use scale and bias parameters for each element in the same channel of every examples in the minibatch (i.e. CHW scale and bias parameters) No, you would have HW scale and bias parameters. Basically the number of such parameters is equal to the number of elements you normalized over (in each computation of mean and variance).
st99187
If I use HW scale and bias parameters, the same location in different channels will share the same scale and bias parameters, is it right ? while in a BatchNorm, different channels use different scale and bias parameters.
st99188
Oh thanks a lot ! But the LayerNorm paper did not specify its usage in CNN, is the above usage a convention?
st99189
It’s unclear how it should be applied on a CNN, so we provide a lot of flexibility and you can normalize over either C or not. But in either case, I think the paper is pretty clear in that you have a scale and bias for each normalized element.
st99190
I am trying to use the torch.nn.TripletMarginLoss 4 on three tensors a, b, c. The module internally calls torch.nn.Functional.triplet_margin_loss 1 which also gives the same error when called independently on the the three tensors. Below is a code snippet and all of this is in pytorch 0.4 under python 3.6. Is this a dimension bug. How can I fix this? a = torch.FloatTensor([0.1, 0.2]) b = torch.FloatTensor([0.2, 0.2]) c = torch.FloatTensor([0.1, 0.3]) torch.nn.Functional.triplet_margin_loss(a,b,c)
st99191
Solved by kenmikanmi in post #2 Here you can see that: Shape: Input: (N,D) where D is the vector dimension. Output: scalar. If reduce is False, then (N). N is batch size. So you need to add batch dimension for your tensor like this: input import torch a = torch.FloatTensor([[0.1, 0.2]]) b = torch.FloatTensor([[0.2, 0.2]])…
st99192
Here 18 you can see that: Shape: Input: (N,D) where D is the vector dimension. Output: scalar. If reduce is False, then (N). N is batch size. So you need to add batch dimension for your tensor like this: input import torch a = torch.FloatTensor([[0.1, 0.2]]) b = torch.FloatTensor([[0.2, 0.2]]) c = torch.FloatTensor([[0.1, 0.3]]) torch.nn.functional.triplet_margin_loss(a,b,c) output tensor(1.0000)
st99193
I noticed that in the source of DataParallel, it is implemented by threading: I reply my question in https://github.com/pytorch/pytorch/issues/3917 8 Is that Global Interpreter Lock makes DataParallel working slower? I modified my code with multiprocessing and the speed up 4x with 4-gpu. I wander is that the threading making DataParallel slower?
st99194
I guess it will depend on the size of the net you are using. If it is very small, then your will spend most time executing python code and thus using threading will slow you down. Otherwise, most of the time will be spent running stuff on the GPU anyway and so there is no use for multiple processes. In that case threads are used as they are much cheaper to create.
st99195
I tested with CondenseNet: CondenseNet.jpg560×518 54.4 KB It takes almost 80ms one batch with 32 image(224x224). Is that CondenseNet too small? How do you think?
st99196
Because most time is spent on CUDA kernels which don’t have GIL anyways, and transmitting CUDA tensors across processes is very tricky.
st99197
Hi, I have installed LibTorch (PyTorch C++ API) successfully by following the instructions on Installing C++ Distributions of PyTorch 46. Now, I want to use it in another C++ Project. As I am newbie in CMake in Ubuntu, can anyone help me to implement a correct CMake file which with it I can use LibTorch in my C++ Projects? As another question, In fact I am using CLion IDE for C++ coding in Ubuntu, so can anyone help me how I can write a correct CMake for my CLion C++ projects for using LibTorch?
st99198
Solved by Tobias_Czempiel in post #2 Hi, checkout this example. It pretty much the makefile from the example except that I added OpenCV as well. From there on its just normal CMake!
st99199
Hi, GitHub tobiascz/MNIST_Pytorch_python_and_capi 181 This is an example of how to train a MNIST network in Python and run it in c++ with pytorch 1.0 - tobiascz/MNIST_Pytorch_python_and_capi checkout this example. It pretty much the makefile from the example except that I added OpenCV as well. From there on its just normal CMake!
st99200
Pytorch has provided windows support for version 0.4 several months ago. I have tried pip install --upgrade torch and follow the instructions form the official website: pip3 install torchvision However, the version I got is still 0.2. Why is that? And what should I do to fix it?
st99201
the newest version of pytorch already have c++ interfaces. So is that possible to convert a caffe layer to pytorch layer?
st99202
Some layers might be portable, but as far as I know, Caffe2 layers make some assumptions about the input, e.g. contiguity, which might make these layers unportable. Take this information with a grain of salt as I’ve just scratched Caffe2 on the surface so far.
st99203
Hi, I have a training set which I want to divide into batches of variable sizes based on the index list (batch 1 would contain data with index 1 to 100, and batch 2 contains index 101 to 129, batch 3 contains index 130 to 135, …, for instance). I check dataloader but it seems to me that it only supports fixed-size batches. I wonder what would be a good way to do that? Thank you!
st99204
Solved by ptrblck in post #4 Do you know these lengths beforehand? If so, you could use these indices to slice your data, set batch_size=1 and view your data to fake your batch size: class MyDataset(Dataset): def __init__(self): self.data = torch.randn(250, 1) self.batch_indices = [0, 100, 129, 150, 200, 2…
st99205
Because I want to keep the order fixed, such that a specific batch contains data exactly specified by the index list. For my example above, batch 1 should only contain data with index 1 to 100, not 100 random data points. Same for batch 2,3,…
st99206
Do you know these lengths beforehand? If so, you could use these indices to slice your data, set batch_size=1 and view your data to fake your batch size: class MyDataset(Dataset): def __init__(self): self.data = torch.randn(250, 1) self.batch_indices = [0, 100, 129, 150, 200, 250] def __getitem__(self, index): start_idx = self.batch_indices[index] end_idx = self.batch_indices[index+1] data = self.data[start_idx:end_idx] return data def __len__(self): return len(self.batch_indices) - 1 dataset = MyDataset() loader = DataLoader( dataset, batch_size=1, shuffle=False, num_workers=2 ) for data in loader: data = data.view(-1, 1) print(data.shape)
st99207
I want to reiterate over the file loaded by getitem function, because it contains many training samples (one file can contain up to 200 training samples), do I have to create a subset on this dataset? How is it done? What’s best practice? thx def __len__(self): return len(self.all_files) def __getitem__(self, idx): #load track from midi files track = ppr.Multitrack(self.all_files[idx], beat_resolution=self.beat_res) track = track.get_stacked_pianoroll() #if 1 track midifile if(track.shape[2]==1): track = np.squeeze(track,2) #quick fix for multitrack, melody in almost every song on midi[0] else: track = track[:,:,0] #binarize if(self.binarize): track[track > 0] = 1 #full track length in ticks length = track.shape[0] while(True): #get random (bar long) sequence from the given midi file random = np.random.randint(0,(length-1)-self.seq_length) sequence = track[random:random+self.seq_length,:] #only return this sequence if it is not a zero for all ticks if(np.any(sequence)): break #transpose notes out of range of the 5 chosen octaves sequence = transposeNotesHigherLower(sequence) #cut octaves to get input shape [96,60] sequence = cutOctaves(sequence) #unsqueeze first dimension for input sequence = np.expand_dims(sequence, axis=0) return sequence
st99208
Would it be possible to precompute all valid sequence start indices? If so, you could store the list of all files and the file_id with start_index in your Dataset. Then in the __getitem__ you could use the index to get the current file_id with its corresponding start_index to load the file and the sequence. Would that work for you?
st99209
I have written a CPP extension and I am loading it via JIT. Within the CPP extension I am allocating a CPP array and return it as a Tensor. It looks roughly like this: float *data = new float[sizeX*(N-n)*sizeY]; .... some stuff that fills data ... auto f = torch::CPU(kFloat).tensorFromBlob(data, {sizeX,N-n,sizeY}); return f This creates a memory leak because I assume “data” is never garbage collected. What’s the proper way of doing this?
st99210
Create the tensor using torch API and then fill the data using tensor.data<float>().
st99211
I am new to Pytorch and trying to understand the LSTM implementation. So I create an input with unit length and pass it through a) LSTMCell and b) LSTM My understanding is LSTM is basically stacking LSTMCell in an efficient manner, so if I manually provide both the same input (all other parameters like hidden size etc. remaining the same) the output should be exactly the same for both. I have inserted by standalone code below and I am getting different results. Can someone please point to what the issue is? """ Comparison LSTMCell and LSTM """ import numpy as np import torch # get SAME input for both cases. inpsize=1 batch=1 hiddensize=5 seq_len=1 nlayers=1 torch.manual_seed(999) x_cell= torch.randn(seq_len,batch,inpsize) h0_cell= torch.randn(batch,hiddensize) c0_cell= torch.randn(batch,hiddensize) x_layer = x_cell.clone() h0_layer = h0_cell.clone() c0_layer = c0_cell.clone() h0_layer = h0_layer.view(nlayers,batch,hiddensize) c0_layer = c0_layer.view(nlayers,batch,hiddensize) # LSTM Cell Stacked into layers lstm= torch.nn.LSTMCell(inpsize,hiddensize) out_cell=[] states_cell=[] ht_cell, ct_cell = h0_cell.clone() , c0_cell.clone() for i in range(seq_len): ht_cell,ct_cell = lstm(x_cell[i],(ht_cell,ct_cell)) out_cell.append(ht_cell) states_cell.append(ct_cell) print('output cell is', out_cell) print('states cell is', states_cell) # full LSTM full_lstm = torch.nn.LSTM(inpsize, hiddensize, nlayers) out_layer, (ht_layer,ct_layer) = full_lstm(x_layer, (h0_layer,c0_layer)) print('Layer Output is', out_layer) print('ht layer Output is', ht_layer) print('ct layer Output is', ct_layer) # print('Input is', x_cell) # print('Cell Output is', out_cell) # print('Layer Output is', out_layer) The output reads: Done output cell is [tensor([[-0.1558, 0.1880, -0.3255, -0.0062, 0.0196]], grad_fn=<ThMulBackward>)] state cell is [tensor([[-0.3916, 0.4230, -0.7570, -0.0181, 0.0513]], grad_fn=<ThAddBackward>)] Layer Output is tensor([[[-0.0504, 0.2765, -0.1421, 0.1251, 0.0082]]], grad_fn=<CatBackward>) ht layer Output is tensor([[[-0.0504, 0.2765, -0.1421, 0.1251, 0.0082]]], grad_fn=<ViewBackward>) ct layer Output is tensor([[[-0.0801, 0.4966, -0.3166, 0.2123, 0.0124]]], grad_fn=<ViewBackward>) If I am using 1 layer of seq_len= 1, exactly the same inputs, shouldn’t LSTM be the same as a LSTMCell? I am confused. Thanks for your time.
st99212
Solved by InnovArul in post #2 In your code, the weight initialization of both LSTMCell, LSTM are not same. Initialize seed manually before creating the instances. torch.manual_seed(999) lstm= torch.nn.LSTMCell(inpsize,hiddensize) torch.manual_seed(999) full_lstm = torch.nn.LSTM(inpsize, hiddensize, nlayers)
st99213
In your code, the weight initialization of both LSTMCell, LSTM are not same. Initialize seed manually before creating the instances. torch.manual_seed(999) lstm= torch.nn.LSTMCell(inpsize,hiddensize) torch.manual_seed(999) full_lstm = torch.nn.LSTM(inpsize, hiddensize, nlayers)
st99214
Arul - That worked, thanks much. But since I had already set the seed at the top, I was hoping that it gets reflected throughout the code - looks like it isn’t the case.
st99215
The reason is that the random number generator changes its state with each number generated. You can think of it as creating a very long list of pseudorandom numbers when the seed is set, then successive calls return the next number in the sequence. Without resetting the seed when you initialize the second LSTM, you’re choosing a different starting place in the sequence, so the numbers will be different.
st99216
Hi, Suppose I have a very simple lstm model class model(nn.Module): def __init(...): lstm = self.LSTM() def init_hidden(): #init to zero def forward(self, inputs): lstm_hidden = self.init_hidden() output, (hidden, cell) = lstm(inputs) then, when i train my model, does lstm_hidden keep initialized in every epoch by lstm_hidden = self.init_hidden() ? if so, does it always start with zero hidden weights?
st99217
In your code the hidden state is initialized to zeros in each forward pass, i.e. in every iteration.
st99218
I tested .cpu() speed with the following code. import torch import torch.nn as nn from time import time import numpy as np class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(10000, 1000) self.fc2 = nn.Linear(1000, 1000) self.fc3 = nn.Linear(1000, 1000) self.fc4 = nn.Linear(1000, 1000) def forward(self,x): x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) x = self.fc4(x) return x net = Net() net.cuda() net.eval() try1_time = [] try2_time = [] try3_time = [] for _ in range(10): x = torch.FloatTensor(10,10000).random_().cuda() with torch.no_grad(): y1 = net(x) #try1 st = time() y1_numpy = y1.cpu().numpy() try1_time.append(time()-st) y1 = y1*10 #try2 st = time() y1_numpy = y1.cpu().numpy() try2_time.append(time()-st) with torch.no_grad(): y2 = net(x) # y2, not y1 #try3 st = time() y1_numpy = y1.cpu().numpy() # y1 try3_time.append(time()-st) print ("try1:%fs" %(np.mean(try1_time))) print ("try2:%fs" %(np.mean(try2_time))) print ("try3:%fs" %(np.mean(try3_time))) result is try1:0.001630s try2:0.000073s try3:0.001641s I expected try2 time = try3 time, because y1 is not affected by y2 = net(x). How can I speed up try3?
st99219
CUDA code is asynchronous, so I don’t think your timings are completely correct. Try to time using torch.cuda.Event 12, like the following: start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() y1.cpu() end.record() torch.cuda.synchronize() elapsed = start.elapsed_time(end)
st99220
Hi. I tested with your codes and got the following result. try1:0.061309s try2:0.062861s try3:0.057283s I think this is correct. Thank you.
st99221
import torch import torch.nn as nn rnn=nn.GRU(130, 1024, 5).cuda() inp=torch.rand((960, 125, 130)).cuda() hid=torch.zeros((5, 125, 1024)).cuda() out, hid = rnn(inp, hid) returns RuntimeError: sizes must be non-negative I don’t understand why or what’s happening here. If I run the same thing on CPU (same exact code, omitting all intances of .cuda()), it will work.
st99222
Does your GPU look like it is running out of memory? You can watch via nvidia-smi. Do you have cudnn installed? what version of pytorch are you running?
st99223
Can someone explain to me what that function _convolution_double_backward() does? And when it is called? It is located in Convolution.cpp 4
st99224
Solved by albanD in post #2 HI, As you can see here, it defines the backward of the backward function for convolution. It is used if you need higher order derivatives through a conv layer. The autograd could build it automatically from the backward implementation of conv but this custom function is much faster.
st99225
HI, As you can see here 16, it defines the backward of the backward function for convolution. It is used if you need higher order derivatives through a conv layer. The autograd could build it automatically from the backward implementation of conv but this custom function is much faster.
st99226
Hi, I am learning the Deep learning using pytorch toolkit. I have trained the sample model by pytorch python version. I am trying to test the trained model on python C++ using example-app.cpp which is given in the pytorch packages. If I am using the below given sequences of code it is crashing at run time Code sequences:- auto f = CPU(kFloat).tensorFromBlob(float_buffer, {output_height,output_width}); std::vectortorch::jit::IValue inputs; inputs.push_back(f); auto output = module->forward(inputs).toTensor(); Error message :- [ CPUFloatType{2,32} ] terminate called after throwing an instance of ‘at::Error’ what(): Tensor that was converted to Variable was not actually a Variable (Variable at But If I am using the below given sequences of code it is working well std::vectortorch::jit::IValue inputs; ** at::Tensor b1 = torch::randn({2, 32});** ** inputs.push_back(b1);** ** auto output = module->forward(inputs).toTensor();** I feel that C++ standard format of features vectors converted into Tensor format (auto f = CPU(kFloat).tensorFromBlob(float_buffer, {output_height,output_width}); ) is wrong because it gives data type as [ CPUFloatType{2,32} ] but The function at::Tensor b1 = torch::randn({2, 32}) is giving data type as [ Variable[CPUFloatType]{2,32} ] is C++ standard format of features vector into Tensor format conversion correct ? auto f = CPU(kFloat).tensorFromBlob(float_buffer, {output_height,output_width}); Please help me to how to resolve the above issue ?
st99227
Hi, I think you have exactly the same error as this one: MNIST with pytorch c++ api 308.
st99228
Could you try to do that instead of your auto f? at::Tensor f = torch::from_blob(float_buffer, at::IntList(sizes), options); f = float_buffer.toType(at::kFloat); also checkout my GitHub repo I did something very similar there in line 31: github.com tobiascz/MNIST_Pytorch_python_and_capi/blob/master/example-app.cpp 115 #include <iostream> #include <torch/script.h> // One-stop header. #include <iostream> #include <memory> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; void showImage(Mat image) { namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display. imshow("Display window", image ); waitKey(0); } This file has been truncated. show original greetings
st99229
As per your suggestion i added your changes in my code and now it is working thanks lot.
st99230
hi! I install pytorch 1.0 from source successfully. But it does not contain torchvision , when I run import torchvison : Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'torchvision' If I conda install torchvision , it seems to install pytorch 0.4.0. what should I do? Thanks!
st99231
yes thats correct pytorch 1.0 doesn’t include torchvision and condo install torchvision also installs pytorch 0.4. So as InnovArul already said install pytorch 1.0 and after that pip install torchvision.
st99232
I’m training an auto-encoder network with Adam optimizer (with amsgrad=True) and MSE loss for Single channel Audio Source Separation task. Whenever I decay the learning rate by a factor, the network loss jumps abruptly and then decreases until the next decay in learning rate. I’m using Pytorch for network implementation and training. Following are my experimental setups: Setup-1: NO learning rate decay, and Using the same Adam optimizer for all epochs Setup-2: NO learning rate decay, and Creating a new Adam optimizer with same initial values every epoch Setup-3: 0.25 decay in learning rate every 25 epochs, and Creating a new Adam optimizer every epoch Setup-4: 0.25 decay in learning rate every 25 epochs, and NOT creating a new Adam optimizer every time rather using PyTorch's multiStepLR decay scheduler every 25 epochs I am getting very surprising results for setups #2, #3, #4 and am unable to reason any explanation for it. Following are my results: Setup-1 Results: Here I'm NOT decaying the learning rate and I'm using the same Adam optimizer. So my results are as expected. My loss decreases with more epochs. Below is the loss plot this setup. 7 optimizer = torch.optim.Adam(lr=m_lr,amsgrad=True, ...........) for epoch in range(num_epochs): running_loss = 0.0 for i in range(num_train): train_input_tensor = .......... train_label_tensor = .......... optimizer.zero_grad() pred_label_tensor = model(train_input_tensor) loss = criterion(pred_label_tensor, train_label_tensor) loss.backward() optimizer.step() running_loss += loss.item() loss_history[m_lr].append(running_loss/num_train) Setup-2 Results: Here I'm NOT decaying the learning rate but every epoch I'm creating a new Adam optimizer with the same initial parameters. Here also results show similar behavior as Setup-1. Because at every epoch a new Adam optimizer is created, so the calculated gradients for each parameter should be lost, but it seems that this doesnot affect the network learning. Can anyone please help on this? 1 for epoch in range(num_epochs): optimizer = torch.optim.Adam(lr=m_lr,amsgrad=True, ...........) running_loss = 0.0 for i in range(num_train): train_input_tensor = .......... train_label_tensor = .......... optimizer.zero_grad() pred_label_tensor = model(train_input_tensor) loss = criterion(pred_label_tensor, train_label_tensor) loss.backward() optimizer.step() running_loss += loss.item() loss_history[m_lr].append(running_loss/num_train) Setup-3 Results: As can be seen from the results in below plot, my loss jumps every time I decay the learning rate. This is a weird behavior. If it was happening due to the fact that I'm creating a new Adam optimizer every epoch then, it should have happened in Setup #1, #2 as well. And if it is happening due to the creation of a new Adam optimizer with a new learning rate (alpha) every 25 epochs, then the results of Setup #4 below also denies such correlation. 3 decay_rate = 0.25 for epoch in range(num_epochs): optimizer = torch.optim.Adam(lr=m_lr,amsgrad=True, ...........) if epoch % 25 == 0 and epoch != 0: lr *= decay_rate # decay the learning rate running_loss = 0.0 for i in range(num_train): train_input_tensor = .......... train_label_tensor = .......... optimizer.zero_grad() pred_label_tensor = model(train_input_tensor) loss = criterion(pred_label_tensor, train_label_tensor) loss.backward() optimizer.step() running_loss += loss.item() loss_history[m_lr].append(running_loss/num_train) Setup-4 Results: In this setup, I'm using Pytorch's learning-rate-decay scheduler (multiStepLR) which decays the learning rate every 25 epochs by 0.25. Here also, the loss jumps everytime the learning rate is decayed. I'm not understanding the reason behind this behaviour. 2 scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer, milestones=[25,50,75], gamma=0.25) optimizer = torch.optim.Adam(lr=m_lr,amsgrad=True, ...........) for epoch in range(num_epochs): scheduler.step() running_loss = 0.0 for i in range(num_train): train_input_tensor = .......... train_label_tensor = .......... optimizer.zero_grad() pred_label_tensor = model(train_input_tensor) loss = criterion(pred_label_tensor, train_label_tensor) loss.backward() optimizer.step() running_loss += loss.item() loss_history[m_lr].append(running_loss/num_train) I’m not able to understand the reason for the sudden jumps in the loss whenever I decay the learning rate. EDIT: As suggested in the comments and reply below, I’ve made changes to my code and trained the model. I’ve added the code and plots for the same. Any help. Thanks
st99233
Hi, I do not fully understand the problem, too. However here are some thoughts on your problem: Your loss decays without explicit learning rate decay. Is there a particular reason you want to get learning rate decay working? Adam uses adaptive learning rates intrinsically. I guess for many problems that should be good enough. You can read more on this in this discussion on Stackoverflow 84. Adam (like many other common optimization algorithms) adapts to a specific machine learning problem by computing/estimating momenta. Creating a new optimizer every epoch therefor should degrade performance due to loss of the information I feel like decreasing the learning rate by 75 % might be too high when using a momentum based optimizer. Would be interesting, if reducing the learning rate by something like 15–25 % gives better results.
st99234
Hi @Florian_1990, As stated in the original Adam paper, Adam calculates learningrate for each parameter and updates it with each iteration. So inherently I should NOT be able to use learning rate scheduler lr_scheduler.MultiStepLR() on optim.adam() with a new learning rate. My doubts: In Setup-3 I’m intentionally creating a new Adam optimizer every 25 epochs but in Setup-4, I’m using available lr_scheduler.MultiStepLR() to decay learning rate every 25 epochs. And surprisingly the behavior in both these settings are same, which I’m not able to understand. Normally PyTorch should throw a warning/error when using lr_scheduler on optim.adam() stating that external lr_decay creates inconsistent behavior or something like this. My goal is to learn faster when the loss starts saturating [using Adam] and decaying learning rate is one of the solutions usually. Thanks
st99235
Hi, Any help please. Any insight about what I’m doing wrong would be very helpful. Thanks
st99236
I think lr decay was not applied in setting 3 and the accumulated momenta weren’t used. vinaykumar2491: optimizer = torch.optim.Adam(lr=m_lr,amsgrad=True, …) if epoch % 25 == 0 and epoch != 0: lr *= decay_rate Also, setup1 worked well w/o lr decay, I mean for me. So I think it’s too early to decay lr. This is totally based on my intuition and may include a bunch of mistakes. Hope help you.
st99237
crcrpar: I think lr decay was not applied in setting 3 and the accumulated momenta weren’t used. I agree. Thats why I took care of externally decaying learningrate and using the accumulated momentum in Setup-4. But, I still donot understand the results of Setup-4.
st99238
Yes the learning curve of setup 4 looks weird for me. But I suspect the timing of LR decay because setup 1 seems very good without LR decay, I mean, there are no plateau and hints of overfitting. So how about training your model longer e.g. 100 or 200 epochs then applying LR decay?
st99239
I trained on longer epochs and I got below results. The network doesnot find any loss plateau in Setup-1; but the time consumed to run so many epochs takes lots of time. I ran 200 and 999 epochs and the results are in below graphs. 999 epochs took me 7 days on Quadro P4000. bloss.png1084×558 51 KB aloss.png1052×556 54.3 KB In pursuit of faster convergence, I am doing a learning rate decay. In the processof this, I am confused by the behaviour of lr_scheduler on Adam optimizer. I’m curious if there is any implementation fault with lr_scheduler for Adam. Should optim.Adam allow lr_scheduler?
st99240
Oh, sorry to hear that. IMO, to faster convergence, use larger initial learning rate then decay LR. For example, 1e-3 as initial LR.
st99241
Hi~ I’m trying to implement dqn algorithm and there is a problem with making two models with one model class. Here is my code. MODEL FILE import torch as torch import torch.nn as nn class Flatten(nn.Module): def forward(self, x): N, C, H, W = x.size() return x.view(N, -1) class NeuNet(nn.Module): def __init__(self, action_num): super(NeuNet, self).__init__() self.conv = nn.Sequential( nn.Conv2d(4, 32, kernel_size=8, stride=4), nn.ReLU(inplace=True), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(inplace=True), nn.Conv2d(64, 64, kernel_size=3, stride=1), nn.ReLU(inplace=True), ) self.linear = nn.Sequential( nn.Linear(3136, 512), nn.ReLU(inplace=True), nn.Linear(512, action_num) ) def forward(self, x): out = self.conv(x) N, C, H, W = out.size() out = self.linear(out.view(N, -1)) return out MAIN FILE cpu_dtype = tc.FloatTensor gpu_dtype = tc.cuda.FloatTensor main_model = model.NeuNet(4) update_model = model.NeuNet(4) tc.manual_seed(7) a = tc.rand(5, 4, 84, 84).type(cpu_dtype) b = tc.rand(5, 4).type(cpu_dtype) loss_fn = nn.SmoothL1Loss() optimizer = tc.optim.RMSprop(main_model.parameters(), lr=0.00025, alpha=0.99, eps=1e-6) print('before learning') out = main_model.forward(a) print('main_model loss :', tc.sum((out - b)**2/20)) out = update_model.forward(a) print('update_model loss :', tc.sum((out - b)**2/20)) for i in range(2000): out = update_model.forward(a) cost = loss_fn(out, b) optimizer.zero_grad() cost.backward() optimizer.step() if i % 100 == 0: print('iter :', i) print('cost :', cost) print('\nafter update_model learning') out = main_model.forward(a) print('main_model loss :', tc.sum((out - b)**2/20)) out = update_model.forward(a) print('update_model loss :', tc.sum((out - b)**2/20)) main_model = copy.deepcopy(update_model) print('\nafter copying up_m to ma_m') out = main_model.forward(a) print('main_model loss :', tc.sum((out - b)**2/20)) out = update_model.forward(a) print('update_model loss :', tc.sum((out - b)**2/20)) print('\nmain predict :', main_model.forward(a)) print('update predict :', update_model.forward(a)) print('label :', b) As you can see, I made two models like this. print('before learning') out = main_model.forward(a) print('main_model loss :', tc.sum((out - b)**2/20)) out = update_model.forward(a) print('update_model loss :', tc.sum((out - b)**2/20)) But when I execute the main file, the result comes like this. before learning main_model loss : tensor(0.3037, grad_fn=<SumBackward0>) update_model loss : tensor(0.2928, grad_fn=<SumBackward0>) iter : 0 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 100 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 200 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 300 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 400 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 500 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 600 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 700 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 800 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 900 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1000 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1100 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1200 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1300 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1400 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1500 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1600 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1700 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1800 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) iter : 1900 cost : tensor(0.1464, grad_fn=<SmoothL1LossBackward>) after update_model learning main_model loss : tensor(0.3037, grad_fn=<SumBackward0>) update_model loss : tensor(0.2928, grad_fn=<SumBackward0>) after copying up_m to ma_m main_model loss : tensor(0.2928, grad_fn=<SumBackward0>) update_model loss : tensor(0.2928, grad_fn=<SumBackward0>) main predict : tensor([[ 0.0212, 0.0366, 0.0054, -0.0330], [ 0.0189, 0.0316, 0.0087, -0.0346], [ 0.0257, 0.0296, 0.0014, -0.0305], [ 0.0172, 0.0313, 0.0057, -0.0288], [ 0.0251, 0.0353, 0.0046, -0.0318]], grad_fn=<ThAddmmBackward>) update predict : tensor([[ 0.0212, 0.0366, 0.0054, -0.0330], [ 0.0189, 0.0316, 0.0087, -0.0346], [ 0.0257, 0.0296, 0.0014, -0.0305], [ 0.0172, 0.0313, 0.0057, -0.0288], [ 0.0251, 0.0353, 0.0046, -0.0318]], grad_fn=<ThAddmmBackward>) label : tensor([[0.2898, 0.5942, 0.0620, 0.7024], [0.2417, 0.4856, 0.7626, 0.2824], [0.9442, 0.3513, 0.2319, 0.2829], [0.7488, 0.9602, 0.2700, 0.4687], [0.7492, 0.6154, 0.5258, 0.2099]]) Update_model doesn’t learn at all. How this could happen?
st99242
Juna: optimizer = tc.optim.RMSprop(main_model.parameters(), lr=0.00025, alpha=0.99, eps=1e-6) Juna: out = update_model.forward(a) You are not optimizing the correct parameters (main_model instead of update_model)
st99243
Oh yeah, I just realized what I had mistaken and just about to erase this posting!!! Thank you for replying though!!
st99244
Hello Everyone, I am new to Pytorch and I wanted create some novel architecture. jump_arch.PNG719×268 10 KB I wanted to create something like the second architecture so I try to save the tensors at every block inside a list like [i, c, p, fc, o] so that I can use the calculated tensors for a new connection. But first, I have a problem when I try to do .backward() My forward function goes like this def forward(self, inputs): tensor_list.append(inputs) for i in range(len(self.nnModList)): x = self.NNList[i] (tensor_list[i]) tensor_list.append(x) and loss.backward(retain_graph=True) or def forward(self, inputs): tensor_list.append(inputs) for i in range(len(self.NNList)): x = self.NNList[i] (tensor_list[i]) tensor_list.append(x.detach()) It works but does not seem to converge unlike doing the forward without the list. How can I make the code above work like the normal?
st99245
Could you explain more about why you need to save the tensor in a list? Does the following code do what you want? def forward(self, inputs): x = self.conv(inputs) # combine features and output ('concat' is just an example) x = torch.cat([x, inputs]) # supposing their dimensions match x = self.pool(x) x = self.fc(x) return x
st99246
Hi @kaixin, I have the a class for concatenation. I wanted to save tensors into a list so that I can use the tensors again in another connection. For example, input - hidden1 - hidden2 - hidden3 - out plus hidden1 is connected to hidden3 also x = [] x.append(operation(input, hidden1)) #list 0 x.append(operation(x[0], hidden2)) #list 1 x.append(operation(x[1], hidden3)) #list 2 x.append(operation(x[0], hidden3)) #list 3 x.append(combine(x[2], x[3])) #list 4 x.append(operation(x[4], out)) #list 5 return x[5]
st99247
Premise I just wanted to pin this topic, so that it can be used for future reference. Recommendations If you are a PyTorch user, I would recommend to add soumith as source server to your Anaconda (or Miniconda) conda config --add channels soumith Then, to get the latest PyTorch and vision package via conda, you can simply conda update pytorch torchvision PyTorch will be installed in $HOME/anaconda3/lib/python3.5/site-packages/torch this is because you want to use Python 3 (since Python 2 is going to die soon). Questions If you want the latest PyTorch update, I believe you should install from source. (Am I correct? Will it be installed in the same directory, like when we were luarocks make the old Torch?) The location of torchvision is… unknown. I couldn’t find where Anaconda put it. torchvision.__file__ says $HOME/anaconda3/lib/python3.5/site-packages/torchvision-0.1.6-py3.5.egg/torchvision/__init__.py but such location does not exist. Nevertheless, my IDE can find those files in that location, when exploring the source code. Another thing I’m puzzled about is the following location a RuntimeError spits out /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.7_1485445763020/work/torch/lib/THNN/generic/SpatialConvolutionMM.c
st99248
Yes, installing it from source will install it in the same place as anaconda does. torchvision should be exactly there where __file__ shows you. When you compile the libs, the compiler will put the compile time path of the .c files in the error messages. Since it’s Soumith who’s responsible for building the binaries, his name shows up there. See this issue 76.
st99249
About 2, that’s kind of not what I see here. >>> f = open(torchvision.__file__) Traceback (most recent call last): File "/home/atcold/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-95-16f43d841fa3>", line 1, in <module> f = open(torchvision.__file__) NotADirectoryError: [Errno 20] Not a directory: '/home/atcold/anaconda3/lib/python3.5/site-packages/torchvision-0.1.6-py3.5.egg/torchvision/__init__.py' >>> f2 = open(torch.__file__) # succeed
st99250
How about /home/atcold/anaconda3/lib/python3.5/site-packages/torchvision/__init__.py? If that doesn’t exist you can use find (terminal command) to look for a torchvision directory under /home/atcold/anaconda3/lib/python3.5/site-packages. It has be somewhere there.
st99251
Oh, maybe I’ve figured it out… atcold@GPU0 ~/anaconda3/lib/python3.5/site-packages $ ls -daF torch* torch/ torch-0.1-py3.5.egg-info/ torchvision-0.1.6-py3.5.egg torchvision.pth There is no directory. Just a pth and an egg.
st99252
Hi, is this still relevant? I added soumith to my conda channels but pytorch 0.3 (released a few days ago) still does not show up when I run conda update pytorch torchvision
st99253
FYI. In order to install the latest torch and torchvision, now, you do conda install pytorch torchvision -c pytorch You can also read this post ( Pytorch 0.3 version is released).
st99254
For me this did not work. It always tried to downgrade my pytorch and torchvision to some rather ancient version. I installed it again in a separate environment using pip then which worked.
st99255
This worked for me! conda update pytorch torchvision -c pytorch The following NEW packages will be INSTALLED: cudatoolkit: 8.0-3 The following packages will be UPDATED: pytorch: 0.2.0-py36h53baedd_4cu80 soumith [cuda80] --> 0.3.0-py36_cuda8.0.61_cudnn7.0.3h37a80b5_4 pytorch torchvision: 0.1.9-py36h7584368_1 soumith --> 0.2.0-py36h17b6947_1 pytorch
st99256
If the dependencies are not met, conda will not update to recent pytorch. What I did was the following. conda install pytorch=0.3.0 -c pytorch ( This gave the missing dependencies) Install the missing dependencies from Anaconda Cloud ( in my case they where numba, blaze ) conda update pytorch torchvision -c pytorch
st99257
Hubert: this is no longer working. PackageNotFoundError: Package not found: ‘pytorch’ I can no longer edit the original post. Now you need to use this command instead (basically, you need to replace soumith with pytorch). conda config --add channels pytorch
st99258
antspy: Hi, is this still relevant? I added soumith to my conda channels but pytorch 0.3 (released a few days ago) still does not show up when I run conda update pytorch torchvision Yeah, the soumith channel is now called pytorch. See post above.
st99259
Just a general note, it’s probably better to do the torch.__file__ checks with via isfile and abspath: >>> import torch >>> import os >>> os.path.isfile(torch.__file__) True >>> os.path.abspath(torch.__file__) '/Users/sebastian/miniconda3/lib/python3.6/site-packages/torch/__init__.py'
st99260
Hey guys. What is the recommended way of upgrading to PyTorch V1.0 using conda? After adding the pytorch channel and trying to update this message appears: # All requested packages already installed. Any suggestions?
st99261
I would recommend to create a new conda environment and install there your 1.0 preview. In that way you can just delete it once the 1.0 stable version will be released and your other code is still executable. Have a look here 83 to learn how to manage environments.
st99262
Thanks for your reply. How does one go about installing the 1.0 preview? After installing the nightly version from source I end up with version 0.4.1
st99263
Hello everyone, I need to make sure that a given Parameter tensor from a Module is kept sorted. This tensor is updated by the optimizer at each step, but is there an elegant way to have some “callback” function called whenever it is modified, so that I may sort it when necessary ? thanks ! antoine
st99264
Solved by SimonW in post #5 You can still change values of a parameter in a no_grad block, or via its .data.
st99265
Yeah just do it everytime on calling the forward function. first sort the parameter and then proceed…
st99266
Thanks for your answers. This is not so easy, because that tensor is a Parameter, which means I cannot just change its values, apparently. Furthermore, I would like this behaviour of that member from my module to be “built-in”: I don’t want a user having to manually sort it each time he-she calls an optimizer step ! is there some more way to track that a class member for a module has been changed ?
st99267
You can still change values of a parameter in a no_grad block, or via its .data.