id
stringlengths
3
8
text
stringlengths
1
115k
st48568
Hello , I want to train a CNN for regression, because the output is a continuous variable, but I got this message: element 0 of tensors does not require grad and does not have a grad_fn I saw Forums where appears the same problem, but I still don’t find the solution Can anyone help me?? Here is my code #class SimpleNet(nn.Module): class CNN(nn.Module): def __init__(self): #super(SimpleNet, self).__init__() super(CNN, self).__init__() self.conv1= nn.Conv2d(in_channels=3, out_channels=96, kernel_size=5, stride=1) self.relu1= nn.ReLU() self.norm1= nn.BatchNorm2d(96) self.conv2 = nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2) self.relu2 = nn.ReLU() self.norm2= nn.BatchNorm2d(256) self.conv3 = nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, stride=1, padding=1) self.relu3 = nn.ReLU() self.conv4 = nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, stride=1, padding=1) self.relu4 = nn.ReLU() self.conv5 = nn.Conv2d(in_channels=384, out_channels=64, kernel_size=3, stride=1, padding=1) self.relu5 = nn.ReLU() self.pool1= nn.MaxPool2d(kernel_size=2, stride=2) self.fc1 = nn.Linear(in_features=4096, out_features=4096) self.fc2 = nn.Linear(in_features=4096, out_features=4096) #self.fc3 = nn.Linear(in_features=4096, out_features=238) self.fc3 = nn.Linear(in_features=4096, out_features=1) def forward(self, x): x=x.float() out = self.conv1(x) out = self.relu1(out) out = self.norm1(out) out = self.conv2(out) out = self.relu2(out) out = self.norm2(out) out = self.conv3(out) out = self.relu3(out) out = self.conv4(out) out = self.relu4(out) out = self.conv5(out) out = self.relu5(out) out = self.pool1(out) out = out.view(-1, 4096) out = self.fc1(out) out = self.fc2(out) out = self.fc3(out) return out # Model model = CNN() CUDA = torch.cuda.is_available() if CUDA: model = model.cuda() loss_fn = nn.MSELoss() #optimizer = Adam(model.parameters(), lr=0.001, weight_decay=0.0001) optimizer = torch.optim.SGD(model.parameters(), lr=0.001, weight_decay=0.0001) #Training CNN import time num_epochs = 2 #Define the lists to store the results of loss and accuracy train_loss = [] test_loss = [] train_accuracy = [] test_accuracy = [] for epoch in range(num_epochs): #Reset s variables to cero in each epoch start = time.time() correct = 0 iterations = 0 iter_loss = 0.0 model.train() # Training Mode for i, (input, lab) in enumerate(train_load): # Convert torch tensor to Variable input = Variable(input) lab = Variable(lab) lab = torch.DoubleTensor(25) lab = lab.type(torch.cuda.FloatTensor) # GPU CUDA = torch.cuda.is_available() if CUDA: input = input.cuda() lab = lab.cuda() optimizer.zero_grad() # clean gradient outputs = model(input) outputs = torch.DoubleTensor(25) outputs = outputs.type(torch.cuda.FloatTensor) loss = loss_fn(outputs, lab) iter_loss += loss.item() loss.backward() # Backpropagation optimizer.step() # update weights torch.cuda.empty_cache() iterations += 1 # Save function loss train_loss.append(iter_loss/iterations) #Test loss = 0.0 correct = 0 iterations = 0 model.eval() for i, (input, lab) in enumerate(test_load): # Convert torch tensor to Variable input = Variable(input) lab = Variable(lab, requires) lab = torch.DoubleTensor(25) lab = lab.type(torch.cuda.FloatTensor) CUDA = torch.cuda.is_available() if CUDA: input = input.cuda() lab = lab.cuda() outputs = model(input) outputs = torch.DoubleTensor(25) outputs = outputs.type(torch.cuda.FloatTensor) loss = loss_fn(outputs, lab) # Calculate the loss loss += loss.item() torch.cuda.empty_cache() iterations += 1 # Record the Testing loss test_loss.append(loss/iterations) stop = time.time()
st48569
It seems you are overwriting the model output in these lines: outputs = model(input) outputs = torch.DoubleTensor(25) outputs = outputs.type(torch.cuda.FloatTensor) If you create a new outputs tensor with a constant value, the computation graph will be detached and you won’t be able to update the parameters. Could you explain a bit, why you would like to do it? PS: I’ve formatted your code for better readability. If you want to post code snippets, you can wrap them in three backticks ```
st48570
Thanks so much for your answer You are right, the next two lines after “outputs’” don’t make sense. It was the problem
st48571
Hey, can you please check my code and let me know how to correct this error? %%time loss_arr = [] loss_epoch_arr = [] max_epochs = 30 for epoch in range(max_epochs): for i, data in enumerate(trainloader, 0): inputs, labels = data inputs, labels = inputs.to(cuda0), labels.to(cuda0) opt.zero_grad() outputs = model(inputs) _,labels = torch.max(labels.data, 1) _, pred = torch.max(outputs.data, 1) loss = soft_dice_loss(pred, labels) loss.backward() opt.step() loss_arr.append(loss.item()) loss_epoch_arr.append(loss.item()) print('Epoch: %d/%d, valid Dloss: %0.2f, Train DLoss: %0.2f' % (epoch, max_epochs, evaluation(validloader, model), evaluation(trainloader, model))) plt.plot(loss_epoch_arr) plt.show() “RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn”
st48572
the indices returned by torch.argmax or by torch.max as the second return value are not differentiable as seen here: outputs = torch.randn(10, 10, requires_grad=True) _, preds = torch.max(outputs, dim=1) print(preds.grad_fn) > None To calculate the dice loss you could pass F.softmax(outputs, dim=1) as the predictions. Also, don’t use the .data attribute, as it might have unwanted side effects since Autograd won’t be able to track these operations.
st48573
Thank you for very quick response. But after modifying my code, I am getting an another error. %%time loss_arr = [] loss_epoch_arr = [] max_epochs = 30 for epoch in range(max_epochs): for i, data in enumerate(trainloader, 0): inputs, labels = data inputs, labels = inputs.to(cuda0), labels.to(cuda0) opt.zero_grad() outputs = model(inputs) pred = torch.nn.functional.softmax(out, dim=1 ) # _,labels = torch.max(labels, dim=1) # _, pred = torch.max(outputs, dim=1) loss = soft_dice_loss(pred, labels) loss.backward() opt.step() loss_arr.append(loss.item()) loss_epoch_arr.append(loss.item()) print('Epoch: %d/%d, valid Dloss: %0.2f, Train DLoss: %0.2f' % (epoch, max_epochs, evaluation(validloader, model), evaluation(trainloader, model))) plt.plot(loss_epoch_arr) plt.show() “RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling backward the first time.”
st48574
Are you running backward multiple times in each iteration somewhere? E.g. is soft_dict_loss calling loss.backward already?
st48575
At one point an intermediate tensor is still needed in a sequential backward call. Could you post a minimal, executable code snippet to reproduce this error, so that we could debug it?
st48576
The error was due to the use of .data attribute. But it runs perfectly fine if i just given output directly to backpropogate. %%time import copy #loss_arr = [] loss_epoch_arr = [] max_epochs = 30 train_loss =[] valid_loss = [] min_loss = 100 for epoch in range(max_epochs): for i, data in enumerate(trainloader, 0): inputs, labels = data inputs, labels = inputs.to(cuda0), labels.to(cuda0) opt.zero_grad() outputs = model(inputs) # _,labels = torch.max(labels.data, 1) # _,pred = torch.max(outputs.data, 1) loss = soft_dice_loss(labels, outputs) loss.backward() opt.step() if min_loss > loss.item(): min_loss = loss.item() best_model = copy.deepcopy(model.state_dict()) #print('Min loss %0.2f' % min_loss) del inputs, labels, outputs torch.cuda.empty_cache() #loss_arr.append(loss.item()) loss_epoch_arr.append(loss.item()) train_loss.append(evaluation(trainloader, model)) valid_loss.append(evaluation(validloader, model)) print('Epoch: %d/%d, Train DLoss: %0.2f, valid Dloss: %0.2f' % (epoch, max_epochs, evaluation(trainloader, model), evaluation(validloader, model))) plt.plot(loss_epoch_arr, ‘r’) plt.plot(train_loss, ‘b’) plt.plot(valid_loss, ‘g’) plt.show() I am not understanding why there is problem with using torch.max? Does using output directly for backpropogation has any effects on accuracy?
st48577
Akshay_A_J: I am not understanding why there is problem with using torch.max? You can calculate the gradients for the returned values in torch.max, but not the returned indices as this operation is not differentiable: x = torch.randn(10, 10, requires_grad=True) val, idx = torch.max(x, dim=1) print(val, idx) > tensor([1.4675, 2.2521, 1.3766, 1.8801, 1.5437, 1.3367, 0.8476, 0.7166, 1.0904, 1.5543], grad_fn=<MaxBackward0>) tensor([3, 9, 4, 8, 3, 1, 0, 2, 1, 2]) As you can see, the val tensor contains a valid .grad_fn, while the idx tensor does not. Also, where did you use the .data attribute? It shouldn’t be used at all generally, as Autograd cannot track the operations on this attribute, but I also thought you’ve already removed the usage in the previous code snippet.
st48578
I have tried loading a distilbert model in pytorch over 3 different GPUs (GeForce GTX 1080 ti, tesla k80, tesla v100). According to the pytorch cuda profiler, the memory consumption is identical in all of these GPUs(534MB). But “nvidia-smi” shows different memory consumption for each of them (GTX 1080 ti- 1181MB, tesla k80 - 898MB, tesla v100- 1714MB). I chose v100, hoping to accommodate more processes because of it’s extra memory. Because of this, I am not able accommodate any more processes in v100 compared to k80. Versions: Python 3.6.11, transformers==2.3.0, torch==1.6.0 Any help would be appreciated. Following are the memory consumption in the GPUs. ----------------GTX 1080ti--------------------- 2020-10-19 02:11:04,147 - CE - INFO - torch.cuda.max_memory_allocated() : 514.33154296875 2020-10-19 02:11:04,147 - CE - INFO - torch.cuda.memory_allocated() : 514.33154296875 2020-10-19 02:11:04,147 - CE - INFO - torch.cuda.memory_reserved() : 534.0 2020-10-19 02:11:04,148 - CE - INFO - torch.cuda.max_memory_reserved() : 534.0 The output of “nvidia-smi” : 2020-10-19 02:11:04,221 - CE - INFO - | ID | Name | Serial | UUID || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | 2020-10-19 02:11:04,222 - CE - INFO - | 0 | GeForce GTX 1080 Ti | [Not Supported] | GPU-58d5d4d3-07a1-81b4-ba67-8d6b46e342fb || 50C | 15% | 11% || 11178MB | 1181MB | 9997MB || Disabled | Disabled | ----------------Tesla k80--------------------- 2020-10-19 12:15:37,030 - CE - INFO - torch.cuda.max_memory_allocated() : 514.33154296875 2020-10-19 12:15:37,031 - CE - INFO - torch.cuda.memory_allocated() : 514.33154296875 2020-10-19 12:15:37,031 - CE - INFO - torch.cuda.memory_reserved() : 534.0 2020-10-19 12:15:37,031 - CE - INFO - torch.cuda.max_memory_reserved() : 534.0 The output of “nvidia-smi” : 2020-10-19 12:15:37,081 - CE - INFO - | ID | Name | Serial | UUID || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | 2020-10-19 12:15:37,081 - CE - INFO - | 0 | Tesla K80 | 0324516191902 | GPU-1e7baee8-174b-2178-7115-cf4a063a8923 || 50C | 3% | 8% || 11441MB | 898MB | 10543MB || Disabled | Disabled | ----------------Tesla v100--------------------- 2020-10-20 08:18:42,952 - CE - INFO - torch.cuda.max_memory_allocated() : 514.33154296875 2020-10-20 08:18:42,952 - CE - INFO - torch.cuda.memory_allocated() : 514.33154296875 2020-10-20 08:18:42,953 - CE - INFO - torch.cuda.memory_reserved() : 534.0 2020-10-20 08:18:42,953 - CE - INFO - torch.cuda.max_memory_reserved() : 534.0 The output of “nvidia-smi” : 2020-10-20 08:18:43,020 - CE - INFO - | ID | Name | Serial | UUID || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | 2020-10-20 08:18:43,020 - CE - INFO - | 0 | Tesla V100-SXM2-16GB | 0323617004258 | GPU-849088a3-508a-1737-7611-75a087f18085 || 29C | 0% | 11% || 16160MB | 1714MB | 14446MB || Enabled | Disabled |
st48579
Different GPU architectures (in combination with different CUDA versions) might use different memory footprints for the CUDA context. What is the unit of the torch.cuda.memory... output? 1.7GB are too much for the context alone on a V100 and it should be around ~800-1000MB.
st48580
cibin_john_joseph: torch.cuda.memory_reserved() The unit of torch.cuda.memory… output is Megabytes. (converted from bytes)
st48581
Thanks for the update. I cannot reproduce it with CUDA10.2.89, PyTorch 1.6, NVIDIA driver 450.51.06 and the creation of a CUDATensor creates a CUDA context of ~940MB on a V100-SXM2 32GB using the conda binaries. Building from source using CUDA11.1 and a newer PyTorch version creates a context of ~816MB.
st48582
Thanks for the response. The version of NVIDIA driver that I use is 440.95.01. The versions of the python libraries in my virtual environment are: boto3==1.16.6 botocore==1.19.6 certifi==2020.6.20 chardet==3.0.4 click==7.1.2 future==0.18.2 GPUtil==1.4.0 idna==2.10 jmespath==0.10.0 joblib==0.17.0 numpy==1.19.2 pkg-resources==0.0.0 python-dateutil==2.8.1 regex==2020.10.23 requests==2.24.0 s3transfer==0.3.3 sacremoses==0.0.43 sentencepiece==0.1.92 six==1.15.0 torch==1.6.0 tqdm==4.51.0 transformers==2.3.0 urllib3==1.25.11 Unfortunately, I cannot share the original code here. Sharing another code which could be used to recreate the same issue. import os import sys import GPUtil from transformers import DistilBertTokenizer, DistilBertModel import torch from io import StringIO class Capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) del self._stringio # free up some memory sys.stdout = self._stdout def get_torch_cuda_memory_info(): with Capturing() as stdout_captured: GPUtil.showUtilization(all=True) for stdout in stdout_captured: print(stdout) print('\ntorch.cuda.max_memory_allocated() : ' + str(torch.cuda.max_memory_allocated()/ (1048576))) print('torch.cuda.memory_allocated() : ' + str(torch.cuda.memory_allocated() / (1048576))) print('torch.cuda.memory_reserved() : ' + str(torch.cuda.memory_reserved() / 1048576)) print('torch.cuda.max_memory_reserved() : ' + str(torch.cuda.max_memory_reserved() / 1048576)) if __name__ == "__main__": device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('device : ',device) model = 'distilbert-base-uncased' tokenizer = DistilBertTokenizer.from_pretrained(model) model = DistilBertModel.from_pretrained(model).to(device) get_torch_cuda_memory_info() The output @v100 is: To use data.metrics please install scikit-learn. See https://scikit-learn.org/stable/index.html device : cuda | ID | Name | Serial | UUID || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 0 | Tesla V100-SXM2-16GB | 1562919007687 | GPU-4ed687c6-bd14-8e65-d88d-a4e5b1638697 || 35C | 5% | 9% || 16160MB | 1452MB | 14708MB || Enabled | Disabled | torch.cuda.max_memory_allocated() : 254.234375 torch.cuda.memory_allocated() : 254.234375 torch.cuda.memory_reserved() : 272.0 torch.cuda.max_memory_reserved() : 272.0 The output @k80 is: To use data.metrics please install scikit-learn. See https://scikit-learn.org/stable/index.html device : cuda | ID | Name | Serial | UUID || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 0 | Tesla K80 | 0321216031679 | GPU-a7886e31-16b5-8601-d40f-3c04a9b8501f || 39C | 21% | 6% || 11441MB | 635MB | 10806MB || Disabled | Disabled | torch.cuda.max_memory_allocated() : 254.234375 torch.cuda.memory_allocated() : 254.234375 torch.cuda.memory_reserved() : 272.0 torch.cuda.max_memory_reserved() : 272.0
st48583
Using 440.33.01 on V100 16GB GPUs I get these results: PyTorch 1.7.0 + CUDA10.2 binaries (built for 'sm_37', 'sm_50', 'sm_60', 'sm_61', 'sm_70', 'sm_75', 'compute_37'): | ID | Name | [...] | [...] || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 0 | Tesla V100-DGXS-16GB | [...] | [...] || 36C | 13% | 8% || 16158MB | 1331MB | 14827MB || Disabled | Disabled | [...] torch.cuda.max_memory_allocated() : 254.234375 torch.cuda.memory_allocated() : 254.234375 torch.cuda.memory_reserved() : 272.0 torch.cuda.max_memory_reserved() : 272.0 PyTorch master + CUDA10.2 (built for 'sm_70', 'sm_75', 'compute_75'): | ID | Name | [..] | [...] || GPU temp. | GPU util. | Memory util. || Memory total | Memory used | Memory free || Display mode | Display active | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 0 | Tesla V100-DGXS-16GB | [...] | [...] || 37C | 9% | 7% || 16158MB | 1083MB | 15075MB || Disabled | Disabled | [...] torch.cuda.max_memory_allocated() : 254.234375 torch.cuda.memory_allocated() : 254.234375 torch.cuda.memory_reserved() : 272.0 torch.cuda.max_memory_reserved() : 272.0
st48584
I want to know whether the plotted diagram is informal or not.Please answer how I solve the problem if it is wrong.Thanks in advance!
st48585
Hi all, I am using a 3 dense layer architecture for a multi-classification problem. I am able to calculate the metrics(recall and precision), but my use case requires one of the metrics to be higher. I wanted to know how can we tune an MLP classifier for such use case?
st48586
It’s hard to suggest ways without knowing how your data looks like. A few things which have worked for me in the past: Ensure that train, valid, and test data come from the same distribution. The model is trained correctly (ie no underfitting and no overfitting). Improve precision: Analyse the confusion matrix. Look at the examples which are misclassified (FPs) and mine data with data similar to misclassified examples (FP mining). Retrain model. Improve recall: Again look at the confusion matrix to look for FNs. It maybe the case that there are very few examples from one of the classes hence the model is not learning to classify that class. Add more data (or oversample) and train again. In most cases there’s a tradeoff between precision and recall.
st48587
The following code worked before the 1.7.0 update, and now it fails. @classmethod def __torch_function__(self, func, types, args=(), kwargs=None): if kwargs is None: kwargs = {} args = [a.tensor() if hasattr(a, 'tensor') else a for a in args] test = func(*args, **kwargs) print(test.dtype) return TestTensor(test.float()) # Fails if the above print statement is commented out. results in this error message: 25 test = func(*args, **kwargs) ---> 26 print(test.dtype) 27 return TestTensor(test.float()) 28 AttributeError: 'torch.Size' object has no attribute 'dtype' How do I fix this?
st48588
Turns out it’s because of a change in that’s listed in the docs here: https://pytorch.org/docs/stable/notes/extending.html 30, but not in the release notes. One should be careful within __torch_function__ for subclasses to always call super().__torch_function__(func, ...) instead of func directly, as was the case before version 1.7.0. Failing to do this may cause func to recurse back into __torch_function__ and therefore cause infinite recursion.
st48589
I’m trying to write a fairly simple MNL model that allows for choice sets to be different sizes. For each choice ‘session’, the data include a single target (1 if chosen, else 0) and an (N, C) array of C features. By different size choice sets, I mean that N can vary across sessions. However, DataLoader requires that all elements of a batch have the same shape. I’ve written the Dataset to add padding to the end and return a mask to denote which parts of the tensor are just padding and shouldn’t be used in the model. However, I’m not sure how to adjust the model to exclude the padding rows. Below I’ve included the Dataset and Model classes (stripped down to be as minimal as possible to help convey what I’m trying to do). Any advice would be wonderful – still new to pytorch so may be missing something obvious class ChoiceDataset(Dataset): def __init__(self, filename, choice_var, feature_vars): choiceData = pd.HDFStore(filename) self.sessions = choiceData["sessions"] self.length = len(choiceData["sessions"]) self.n_y = len(choiceData["items"]) # number of *all* items, which may or may not be individual session self.n_x = len(feature_vars) self.choiceVar = choice_var self.features = feature_vars self.data = choiceData.select("data") def __getitem__(self, idx): # Get all data for all alternatives in this session session = self.data[self.data.index==idx] x_f = torch.tensor(session[self.features].values) # Add padding so all tensors returned to DL will have same dimensions, (n_y, n_x) x_f_padded = F.pad(input=x_f, pad=(0, 0, 0, self.n_y-x_f.shape[0]), mode='constant', value=0) # Create a boolean mask for values that aren't part of the padding (same shape as x_f_padded) x_f_mask = torch.cat((torch.BoolTensor(x_f.shape[0], self.n_x).fill_(0), torch.BoolTensor(self.n_y-x_f.shape[0], choice_data.n_x).fill_(1))) # Get the index of which item chosen (nn.NLLLoss takes single value, not full tensor of 0s and one 1) label = torch.tensor(np.argwhere(session[choice_data.choiceVar].values>0).item()) return (x_f_padded, x_f_mask, label) def __len__(self): return self.length class MultinomialLogit(torch.nn.Module): def __init__(self,m): super(MultinomialLogit,self).__init__() self.linear = torch.nn.Linear(m,1,bias=False) self.lsmax = torch.nn.LogSoftmax(1) def forward(self,x): ## This currently uses *all* values, included the padding -- want to ignore padding y_pred=self.linear(x.float()) y_pred=self.lsmax(y_pred) return y_pred.squeeze()
st48590
The best solution I’ve found so far is to ditch the mask and instead add a feature that takes value 1 if the row is padded (not real data), 0 otherwise, and then include that feature in the model. While it’s not the most efficient, in simulations doing this made it possible to recover the correct weights on the other features successfully.
st48591
Hi, when I use nn.CrossEntrypyLoss(), is it necessary to define the nn.Softmax as the last Layer by Forward or is it in CrossEntropyLoss included? For example: Which should be the correct version: def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = self.avgpool(x) x = self.fc1(x) x = nn.Softmax(x, dim=1) return x or: def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = self.avgpool(x) x = self.fc1(x) return x
st48592
Solved by Abhilash_Srivastava in post #2 nn.Softmax is not required in this case. Your second example should work fine.
st48593
Kla: when I use nn.CrossEntrypyLoss(), is it necessary to define the nn.Softmax as the last Layer by Forward or is it in CrossEntropyLoss included? nn.Softmax is not required in this case. Your second example should work fine.
st48594
A torchaudio advisor suggested I post my request for advice here. I want to try a deep learning solution to create a morse code decoder. I am at the beignining stages to create a training set of images and have lots of options as to how to do it. I am looking for suggestions from experts to hopefully get a working result that is useful. After playing around with audio spectrograms of received morse code signals, it appears that I I should select small images from the spectrograms following along a narrow frequency band, maybe something like 50Hz x 5secs. This would translate to about an 8 x 512 slice assuming a 1024 FFT and 44100 audio sampling rate. Is this reasonable? I suspect the slices need to overlap about 50% . The below spectrogram shows 10 seconds captured on a busy Sunday afternoon. The 22kHz audio capture translates to 512 audio channels [vertical height] and most code signals are about 2-3 channels wide. The spectrogram is showing only the 3 kHz bandpass of audio from the ham radio. Figure_1complex800×500 93.7 KB Visual code patterns for strong signals are easily seen and I can make images of individual letters and letter combinations. Should I stick to gray scale for learning?. How should the training handle the multiply letter patterns in each time slice? I am beginning to wonder how to handle overlapping information in adjacent images but hope that might be handled with a post filtering merge process. Individual letter patterns can widely differ in length, for e.g. “e” is dit, where as “0” is 5 dah dah dah dah dah. That is 18 times longer. As seen in the image, the code is also sent at different speeds. Tones rarely overlap and most have clean patterns. The torchaudio spectrogram worked about the same as examples for Numpy/Scipy or commercial Audacity. program and it appears that slices of a few seconds can be handled even on a raspberry pi. Converting to tensors from image numpy was easy and scaling to -1 to 1. I am wondering how fast the decoder can actually run. Need suggestions for designing the traiining sets and likely more when get to actual training. Anyway suggestions would be appreciated for selecting the images and numbering or labelling the result patterns.
st48595
Below code will create a mask for x class get_mask(nn.Module): def __int__(self, in_c): self.conv1 = nn.Conv2d(in_c, 1 , 3, 1) self.norm = nn.BatchNorm2d(2) def forward(self, x): p = 1 p2d =(p, p, p, p) x = self.conv1(F.pad(x,p2d)) x = self.normalize(x) return F.sigmoid(x) How modify the network to output a binary mask(zeros and ones) instead of F.sigmoid(x)?
st48596
If you don’t need to backpropagate through it, you could just apply a threshold on the sigmoid output of e.g. 0.5. Do you just need the binary outputs for some accuracy calculation or visualization?
st48597
No, I need to backprop. I want to use to this mask to mask out invalid pixels in x while calculating loss.
st48598
Ah OK, then I misunderstood your question, sorry. In that case you could create your mask vector (with zeros and ones) and multiply it with the loss. Something like this should work: model = nn.Conv2d(3, 1, 3, 1, 1) x = torch.randn(1, 3, 5, 5) mask = torch.empty(1, 1, 5, 5).random_(2) target = torch.empty(1, 1, 5, 5).random_(2) criterion = nn.BCELoss(reduction='none') output = torch.sigmoid(model(x)) loss = criterion(output, target) loss = loss * mask loss.mean().backward()
st48599
Sorry, maybe I confused you. I need something link this: model = nn.Conv2d(3, 1, 3, 1, 1) mask = torch.sigmoid(model(x)) # but I need mask to be binary instead of values between 0 and 1 masked_img = mask * x # point-wise loss = cal_loss(masked_img, x) loss.mean().backward()
st48600
I think link 62 could give us a hint, in your case, mask = torch.relu(torch.sign(torch.sigmoid(model(x))-0.5)) should return mask with elements ∈ {0,1}. Besides, as discussed in link 22, the derivative of sign(.) is always 0, suppose y = M(x1) * H(x2), where M(): mask layer H(): some hidden layer as Note that, since M(x1) ∈ {0,1}, thus only the positive mask layer outputs take part in back-propagation. b.t.w. how to insert equations in pytorch forum?
st48601
I think there might be a slight mistake in the example. Not important because directionally correct but I believe that instead of being: loss.mean().backward() you should write: loss = loss / torch.sum(mask) loss.backward()
st48602
I have tensors X of shape BxNxD and Y of shape BxNxD. I want to compute the pairwise distances for each element in the batch, i.e. I a BxMxN tensor. How do I do this? There is some discussion on this topic here: https://github.com/pytorch/pytorch/issues/9406 43, but I don’t understand it as there are many implementation details while no actual solution is highlighted. A naive approach would be to use the answer for non-batched pairwise distances as discussed here: Efficient Distance Matrix Computation 61, i.e. import torch import numpy as np B = 32 N = 128 M = 256 D = 3 X = torch.from_numpy(np.random.normal(size=(B, N, D))) Y = torch.from_numpy(np.random.normal(size=(B, M, D))) def pairwise_distances(x, y=None): x_norm = (x**2).sum(1).view(-1, 1) if y is not None: y_t = torch.transpose(y, 0, 1) y_norm = (y**2).sum(1).view(1, -1) else: y_t = torch.transpose(x, 0, 1) y_norm = x_norm.view(1, -1) dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t) return torch.clamp(dist, 0.0, np.inf) out = [] for b in range(B): out.append(pairwise_distances(X[b], Y[b])) print(torch.stack(out).shape) How can I do this without looping over B? Thanks
st48603
Hi, my solution was: def pairwise_distances(x, y): ''' Modified from https://discuss.pytorch.org/t/efficient-distance-matrix-computation/9065/3 Input: x is a bxNxd matrix y is an optional bxMxd matirx Output: dist is a bxNxM matrix where dist[b,i,j] is the square norm between x[b,i,:] and y[b,j,:] i.e. dist[i,j] = ||x[b,i,:]-y[b,j,:]||^2 ''' x_norm = x.norm(dim=2)[:,:,None] y_t = y.permute(0,2,1).contiguous() y_norm = y.norm(dim=2)[:,None] dist = x_norm + y_norm - 2.0 * torch.bmm(x, y_t) return torch.clamp(dist, 0.0, np.inf) but after a comparison with the “direct expansion” approach the approximation was so high that I didn’t use it (maybe there is a bug that I cannot see).
st48604
The issue was in the slicing on the norms. I’ve reconciled the reshapes and confirmed equivalence to the original non-batch pairwise_distances function: def batch_pairwise_squared_distances(x, y): ''' Modified from https://discuss.pytorch.org/t/efficient-distance-matrix-computation/9065/3 Input: x is a bxNxd matrix y is an optional bxMxd matirx Output: dist is a bxNxM matrix where dist[b,i,j] is the square norm between x[b,i,:] and y[b,j,:] i.e. dist[i,j] = ||x[b,i,:]-y[b,j,:]||^2 ''' x_norm = (x**2).sum(2).view(x.shape[0],x.shape[1],1) y_t = y.permute(0,2,1).contiguous() y_norm = (y**2).sum(2).view(y.shape[0],1,y.shape[1]) dist = x_norm + y_norm - 2.0 * torch.bmm(x, y_t) dist[dist != dist] = 0 # replace nan values with 0 return torch.clamp(dist, 0.0, np.inf)
st48605
I put this in my loss function and when I try to train my model with this, the weights become NaN after a few iterations. However, when I remove torch.bmm(x, y_t) , the model is able to train. Does anyone know what in torch.bmm() can cause this issue to occur? At first I thought maybe I had to normalize my inputs x,y but that did not make a difference. I also tried using a much lower learning rate but it does not make a difference.
st48606
Hi, I am new to pytorch. I want to know how to overlap copying data to/from the GPU, with performing computations on the GPU ? Thanks very much!
st48607
Hi, You can use the non_blocking argument to either the copy_ or to() or cuda() functions to be able to do that.
st48608
I am trying to implement a Dropout layer using pytorch as follows: class DropoutLayer(nn.Module): def __init__(self, p): super().__init__() self.p = p def forward(self, input): if self.training: u1 = (np.random.rand(*input.shape)<self.p) / self.p u1 *= u1 return u1 else: input *= self.p And then calling a simple NN.sequential: model = nn.Sequential(nn.Linear(input_size,num_classes), DropoutLayer(.7), nn.Flatten()) opt = torch.optim.Adam(model.parameters(), lr=0.005) train(model, opt, 5) #train(model, optimizer, epochs #) But I’m getting the following error: TypeError: flatten() takes at most 1 argument (2 given) Not sure what I’m doing wrong. Still new to pytorch. Thanks.
st48609
Solved by Vish2020 in post #3 Hi the error has been resolved, I simply needed to call nn.Flatten() first on the multidimensional array in order to convert into a 2d array after which dropout is called. Thx.
st48610
During the training your custom dropout layer would only return the scaled drop mask without the input, while during evaluation nothing would be returned. Could you post the complete stack trace for the flatten error?
st48611
Hi the error has been resolved, I simply needed to call nn.Flatten() first on the multidimensional array in order to convert into a 2d array after which dropout is called. Thx.
st48612
The recommended way of serializing a PyTorch model is to store its state_dict, which contains all parameters and buffers. While this should be enough to recreate the model, load the state_dict, and create new predictions, you might want to e.g. continue the training of this model. In this case, it might be useful to store some hyperparameters (which are not already included in e.g. the optimizer’s state_dict) to properly restore the training routine.
st48613
ptrblck: buffe If we save the following dict in a checkpoint, I believe we save all parameters and hyperparameters. Is it correct? model.state_dict() optimizer.state_dict() scheduler.state_dict()
st48614
I have a torch tensor with shape (batch_size, number_maps, x_val, y_val). The tensor is normalized with a sigmoid function, so within range [0, 1] . I want to find the covariance for each map, so I want to have a tensor with shape (batch_size, number_maps, 2, 2). As far as I know, there is no torch.cov() function as in numpy. How can I efficiently calculate the covariance without converting it to numpy? I tried the following, but I’m pretty sure it’s not correct: def get_covariance(tensor): bn, nk, w, h = tensor.shape tensor_reshape = tensor.reshape(bn, nk, 2, -1) x = tensor_reshape[:, :, 0, :] y = tensor_reshape[:, :, 1, :] mean_x = torch.mean(x, dim=2).unsqueeze(-1) mean_y = torch.mean(y, dim=2).unsqueeze(-1) xx = torch.sum((x - mean_x) * (x - mean_x), dim=2).unsqueeze(-1) / (h*w - 1) xy = torch.sum((x - mean_x) * (y - mean_y), dim=2).unsqueeze(-1) / (h*w - 1) yx = xy yy = torch.sum((y - mean_y) * (y - mean_y), dim=2).unsqueeze(-1) / (h*w - 1) cov = torch.cat((xx, xy, yx, yy), dim=2) cov = cov.reshape(bn, nk, 2, 2) return cov
st48615
Hi, PyTorch 1.6 does not seem to detect CUDA. I installed it with the following command: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch Code example When I want to test whether CUDA is available: >>> torch.cuda.is_available() False System Info python -m torch.utils.collect_env returns Collecting environment information... PyTorch version: 1.6.0 Is debug build: No CUDA used to build PyTorch: 10.2 OS: Arch Linux GCC version: (GCC) 10.2.0 CMake version: Could not collect Python version: 3.8 Is CUDA available: No CUDA runtime version: Could not collect GPU models and configuration: GPU 0: GeForce RTX 2080 Ti Nvidia driver version: 455.28 cuDNN version: Probably one of the following: /usr/lib/libcudnn.so.8.0.4 /usr/lib/libcudnn_adv_infer.so.8.0.4 /usr/lib/libcudnn_adv_train.so.8.0.4 /usr/lib/libcudnn_cnn_infer.so.8.0.4 /usr/lib/libcudnn_cnn_train.so.8.0.4 /usr/lib/libcudnn_ops_infer.so.8.0.4 /usr/lib/libcudnn_ops_train.so.8.0.4 Versions of relevant libraries: [pip3] numpy==1.18.5 [pip3] torch==1.6.0 [pip3] torchtext==0.7.0 [pip3] torchvision==0.7.0 [conda] blas 1.0 mkl [conda] cudatoolkit 10.2.89 hfd86e86_1 [conda] mkl 2020.2 256 [conda] mkl-service 2.3.0 py38he904b0f_0 [conda] mkl_fft 1.2.0 py38h23d657b_0 [conda] mkl_random 1.1.1 py38h0573a6f_0 [conda] numpy 1.19.2 py38h54aff64_0 [conda] numpy-base 1.19.2 py38hfa32c7d_0 [conda] pytorch 1.6.0 py3.8_cuda10.2.89_cudnn7.6.5_0 pytorch [conda] torchtext 0.7.0 pypi_0 pypi [conda] torchvision 0.7.0 py38_cu102 pytorch My specifications OS: Arch Linux PyTorch version: 1.6 Python version: 3.8 CUDA/cuDNN version: 11.1 and 10.2 (tested with both) GPU models and configuration: GeForce RTX 2080 Ti Thank you in advance for your help.
st48616
Solved by Wmog in post #8 Thank you. Effectively, I downgraded to the Linux Kernel 5.8.5 from Arch Linux Archive, I removed nvidia, then I first installed linux-headers-5.8.5, then nvidia-dkms; it is worth noting that linux-headers-5.8.5 must imperatively be installed before nvidia-dkms, otherwise the kernel headers of the L…
st48617
Can you try it with pip install: pip install torch torchvision, take from this link 9
st48618
@appleparan Of course I had already checked whether CUDA is properly installed, here is the output: +-----------------------------------------------------------------------------+ | NVIDIA-SMI 455.28 Driver Version: 455.28 CUDA Version: 11.1 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 GeForce RTX 208... Off | 00000000:03:00.0 On | N/A | | 0% 43C P8 12W / 260W | 185MiB / 11016MiB | 1% Default | | | | N/A | +-------------------------------+----------------------+----------------------+` ... @Toby Same problem with PyTorch installed with pip install torch torchvision.
st48619
Since you are an arch user, are you using Linux kernel 5.9? Linux 5.9 has problems with CUDA. If so, try downgrading to Linux 5.8.
st48620
As far as I know, there is no work-around instead of downgrading to Linux Kernel 5.8 (or lower) and replacing nvidia driver (nvidia) to nvidia-dkms.
st48621
Thank you. Effectively, I downgraded to the Linux Kernel 5.8.5 from Arch Linux Archive, I removed nvidia, then I first installed linux-headers-5.8.5, then nvidia-dkms; it is worth noting that linux-headers-5.8.5 must imperatively be installed before nvidia-dkms, otherwise the kernel headers of the Linux kernel 5.8.5 will be missing for nvidia-dkms. Now it works and PyTorch detects CUDA.
st48622
My model will input a batch of sequence to nn.Transformer and the output of transformer with be feeded into nn.Linear. The input sequence has different length before feeding it into nn.Transformer, so I pad the sequence to the same length in every batch adatively using collate_fn in dataloader For example: batch 1: max length of sequence in this batch is 10, padding 0 to each sequence batch 2: max length of sequence in this batch is 12, padding 0 to each sequence batch 3: max length of sequence in this batch is 15, padding 0 to each sequence Now, I have a problem because the output shape of Transformer is [seq_len, batchsize, dinput], so the input dimension of nn.Linear is dynamical because of the sequence length is different. I have seen some posts mentioned that it can use the nn.AdaptiveAvgPool to solve this problem. Now, I have two solutions and question: Transpose the output of transformer into [batchsize, dinput, seq_len] using nn.AdaptiveAvgPool1d to make shape into [batchsize, dinput, fix_num], and reshape to [batchsize, -1] to feed into nn.Linear. Is this make sense? The sequence length are different but we fix it into a fix number? Set a fixing maximum length, ex: 30, some sequence length is up to 25-30, but most of the sequence length are in length 5-10. The input data will be most of 0 (padding value). It will contain too much useless information! Does anyone compare of these two padding methods or any other good suggestion?
st48623
Hi guys: I have build a seq2seq model using nn.LSTMCELL in it. And I want to export a trained one to onnx form. However, when I do this, I have an error says: UserWarning: ONNX export failed on ATen operator _thnn_fused_lstm_cell because torch.onnx.symbolic_opset9._thnn_fused_lstm_cell does not exist .format(op_name, opset_version, op_name)) I think this maybe due to the opset nort supporting nn.LSTMCELL. Any one could help and share some advice? Thank you!
st48624
Hello, I would like to use the Cumulative Distribution Function for Gaussian Distribution. I know it can be get it as: fn = lambda x : torch.nn.GELU()(x) / x But I am afraid it is not numerical stable. Any other suggestions? Thanks!
st48625
Solved by googlebot in post #2 distributions/normal.py has it: return 0.5 * (1 + torch.erf((value - self.loc) * self.scale.reciprocal() / math.sqrt(2)))
st48626
distributions/normal.py has it: return 0.5 * (1 + torch.erf((value - self.loc) * self.scale.reciprocal() / math.sqrt(2)))
st48627
Hi, how can I find when a particular pytorch feature was added? For example, I want to know in which version torch.bucketize first became available in the API so that if we use it in our code, what version restriction we need to apply. What is the easiest way to find this out?
st48628
You could use the release notes and search for this particular method (which can be directly found as it was apparently added in 1.6 ). Alternatively, you could also check out the docs and search for this method in different versions (top left corner). If that also doesn’t help, search through the source code (grep -r or in GitHub) and use git blame to find the PR, where it was added.
st48629
Hi, I am trying to finetune a github’s (https://github.com/ericsujw/InstColorization/blob/master/README_TRAIN.md 1) image colorization pretrained model. The problem is that the training loss quickly (during the first epoch) plateaus around 0.17-0.19 depending on the dataset. There is not much colorization that happens, even inputting the images, during the training, into the model outputs poor results (not much changes in the LAB color space). I was able to finetune a model over 50 epochs, but it was only able to colorize sky (blue) and grass (green). I am not too sure why my model does not learn and any input is much appreciated. I have introduced a LeakyRelu and tried increasing and decreasing the learning rate. Cheers!
st48630
I want to split FMNIST data set into different sub-datasets containing Containing random 500 samples for each class (so in total 500*no of class). Containing random 100 samples for each class. and so on… Is there a direct way of doing this. I tried with subset but it is resulting in imbalanced dataset.
st48631
You could get the target tensor and create split indices using sklearn.model_selection.train_test_split 8, which accepts the stratify argument to create balanced splits. Once you have the indices, you could use Subsets to create the datasets.
st48632
so i just want to create a config file, say, optimizer.config, like: name: SGD lr: 0.1 momentum:0.9 and i initialize my optimizer as below: optimizer = getattr(torch.optim, config['name'])(filter(lambda p: p.requires_grad, model.parameters()), lr=config.getfloat('lr') ) i don’t want to directly set the flag momentum=config.getfloat('momentum') because i may have more parameters and i want to put them in a loop to load. but when i try to assign value to “momentum”, I found out seems i cannot use setattr: setattr(optimizer, 'momentum', 0.9) it does not work…is there any way that i can load settings from a config file for torch modules? really thanks
st48633
Can you please mention if there is an error, or what is the behavior. Also, please try: momentum = getattr(optimizer, 'momentum') momentum = 0.9 I am new to PyTorch, but I presume if the __eq__ operator is custom defined by PyTorch to do more than just assigning, if it also edits some computation graph elements, this should work.
st48634
Hi. Could someone please help understand these outputs by torch.utils.bottleneck? photo_2020-10-26_21-26-011280×716 139 KB
st48635
Hey ! I have 4 gpu in my machine. I trained a model with 1 gpu then with 4 gpu. But the training in 4 gpu is too long. I guess its because I have to load my model on each gpu (that is the things that make this so slow). Someone have a solution because loading my models in all the gpu seems to slow. Thanks
st48636
Hi @MehdiZouitine, DataParallel has a speed issue due to python GIL and its parallelization. As you mentioned, DataParallel has to recast the parameters from gpu 0 to gpu 1~3 at every forward computation. You can try DistributedDataParallel which is faster. It is the officially recommended multi-gpu scheme. Here’s the tutorial for DDP. pytorch.org PyTorch Distributed Overview — PyTorch Tutorials 1.6.0 documentation 4 Also, you can refer to a complete training/evaluation example 1.
st48637
I have worked on a couple of projects now where I have constructed a neural net for binary classification and something like this has happened. This leads me to believe it’s something to do with how I am programming it rather than the data itself. I have tried all kinds of things, even posted here before but I’m not sure why. I did not recycle my own code or anything so I don’t know how this problem persists across projects. The model is simple: # A simple binary classification model class BinaryClassifier(nn.Module): def __init__(self, input_size, hidden_size, num_classes=1): super().__init__() self.input_size = input_size self.num_classes = num_classes self.linear1 = nn.Linear(input_size, hidden_size) self.linear2 = nn.Linear(hidden_size, num_classes) self.relu = nn.ReLU() def forward(self, x): x = self.linear1(x) x = self.relu(x) x = self.linear2(x) return x I have set num_classes as 1 in order to get a probability that the label is 1. I wasn’t sure how else to structure this binary classification. I use BCEWithLogitsLoss, Adam with a StepLR scheduler model = BinaryClassifier(X_tensor.shape[1], 512) criterion = nn.BCEWithLogitsLoss() optimizer = torch.optim.Adam(model.parameters(), lr=lr) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5) It’s worth mentioning here I only added the scheduler to fix the problem and it did improve the loss but not the flattening out effect. This is how I train the model: def sub_train_(model, dataloader): model.train() losses = list() for idx, (X, y) in enumerate(dataloader): out = model(X) loss = criterion(out, y.unsqueeze(1)) optimizer.zero_grad() loss.backward() optimizer.step() losses.append(loss.item()) return np.mean(losses), model def train(model, trainloader, testloader, scheduler, n_epochs): best_model = model best_loss = math.inf ts = time.time() losses = list() for epoch in range(n_epochs): train_loss, model = sub_train_(model, trainloader) test_loss = sub_valid_(model, testloader) scheduler.step() losses.append(train_loss) if train_loss < best_loss: best_loss = train_loss best_model = model print('Epoch: {}, train_loss: {}, test_loss: {}'.format( epoch, train_loss, test_loss )) te = time.time() fig, ax = plt.subplots() ax.plot(range(n_epochs), losses) plt.show() mins = int((te-ts) / 60) secs = int((te-ts) % 60) print('Training completed in {} minutes, {} seconds.'.format(mins, secs)) return losses, best_model And every time it yields a loss plot like this: What am I doing wrong here? How can I avoid this happening? Thank you in advance to anyone who helps me out with this!
st48638
First of all, you probably want two classes. Solving a problem with one class is impossible, meaning that you always have at least two classes. In your cases: an element has a class (class 1), or it hasn’t (class 2). So num classes should be two. Make sure that your labels are constructed correctly. Also, loss flattening means that the network is learning, which is a good thing. However, because you are not running on a test set, it is very likely that your model just overfits. You can Google ‘prevent overfitting’ and you’ll find solutions such as dropout.
st48639
Hi @BramVanroy Thanks for your response! Yes my labels could be structured better. So with BCEWithLogitsLoss, what is the standard practice for how to structure the labels? At the moment I simply have a label column with a 1 or a 0, where 0 is one class and 1 is the other. What is the better way to do it? I am running it on a test set as well. Ah I hadn’t put the function in the post but I do make a call to it in my train function. However that doesn’t have any impact on the training so what can I do to make my loss decrease even further?
st48640
From what I read, we don’t have to use a one-hot vector for 2 classes when using BCEWithLogitLoss. We just need to give a single label column as you have done. So, I think the num_classes should still be 1. Like in https://towardsdatascience.com/pytorch-tabular-binary-classification-a0368da5bb89 2
st48641
The python code is Dataloader(dataset,bathsize,shuffle=true, drop_last=true, num_of_worker=3) May I ask about how to convert it into C++ please ? I checked make data loader does not have num of worker and datashuffle options ? Thanks.
st48642
Hey, I am trying to understand a example regarding training of a simple, fully connected net. The model is trained with the input “data”. output = self.model(data) loss = F.nll_loss(output, target) if loss.cpu().data.numpy()[0] > 10000: What is the loss.data doing? Somehow relating the loss to the input data? Thanks!
st48643
Solved by KFrank in post #2 Hi Johannes! I’m not sure specifically what you’re asking, but here are some comments: In loss.cpu().data, data is a deprecated property that was used to unwrap a Tensor from a Variable. (I believe this was prior to pytorch version 0.4.0.) It’s just a coincidence that the character string “d…
st48644
Hi Johannes! Johannes_L: if loss.cpu().data.numpy()[0] > 10000: What is the loss.data doing? Somehow relating the loss to the input data? I’m not sure specifically what you’re asking, but here are some comments: In loss.cpu().data, data is a deprecated property that was used to unwrap a Tensor from a Variable. (I believe this was prior to pytorch version 0.4.0.) It’s just a coincidence that the character string “data” in loss.cpu().data happens to match that in self.model(data). The two are used in different contexts, so the same character string is allowed to refer to two different completely unrelated things. In general, the line: if loss.cpu().data.numpy()[0] > 10000: seems to be garbled overkill. There is no need to retrieve the loss value from the gpu or convert it to numpy to perform the > test. In current versions of pytorch: if loss > 10000: suffices. In old (pre-0.4.0?) versions you have to unwrap the Tensor from the Variable, and extract the python non-Tensor value from the Tensor. Either: if loss.data[0] > 10000: or: if (loss > 10000).data[0]: works. Best. K. Frank
st48645
Thanks for this thorough answer! It’s exactly what I needed to understand. As this comes from the Variable: in newer versions of PyTorch, is it better to just do your training and testing with tensors? Or is there any benefit from using Variable?
st48646
Hi Johannes! Johannes_L: Or is there any benefit from using Variable? With newer version of pytorch, don’t use Variables. They are deprecated and don’t actually do anything. I think that torch.autograd.Variable is just a stub that is there for backward compatibility. If you happen to be using an old version of pytorch, but don’t use Variables, your code won’t silently fail – it will immediately complain if you try to do any kind of autograd stuff on a raw tensor. So you don’t need to use Variables “just to be safe.” Best. K. Frank
st48647
I want to find the gradient with respect fo a function w, where w is an MLP that selects part of my input data to use. Then I use another neural network for normal training. The psuedocode would be something like: x_train, y_train =w(training_data) output = model(x_train) update(model) update(w) How do I make sure that w is included in propagation?
st48648
I’m observing something That I’m not sure what to make of: So the output is a HxW matrix, and the loss is calculated by a selected number of values within this matrix. I found that as the training went on the unselected region would just go to zero. My network contains mostly convolutional layers, so I’d assume the loss of the selected pixel would propagate to enough locations to be covered. Right now I’m assuming I might not be propagating the loss through the corresponding pixel locations that are not used during the calculation of loss. Is my assumption correct? Is there a way in PyTorch to set the backprop for all values in the matrix and not just the selected ones?
st48649
Solved by YazanShannak in post #4 Values being zero is actually what is confusing indeed, my wild guess is that you’re doing some kind of batch normalization or L2loss (weight decay) that might keep the values of the other outputs closer to zero, this is just a guess, I am not completely sure what’s happening, what you could do is t…
st48650
Here’s my intuition Based on the fundamental theory of neural networks and back propagation, your network is trying to meet the objective defined by the loss function, which is to generate an output for the selected region as close to as the target, therefore the weights are updated to meet that and that only with no intention to pay attention to the surrounding region.
st48651
right, but wouldn’t the values would be kept randomized? and isn’t’ the loss value being propagated uniformly which means that the unselected region would at least get random values instead of zero?
st48652
Values being zero is actually what is confusing indeed, my wild guess is that you’re doing some kind of batch normalization or L2loss (weight decay) that might keep the values of the other outputs closer to zero, this is just a guess, I am not completely sure what’s happening, what you could do is try and debug a sample from one layer to the other and see what’s actually going on
st48653
In documentation 127, there are the code annotations as below. input = autograd.Variable(torch.randn(1, 16, 12, 12)) downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1) upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1) h = downsample(input) h.size() # (1, 16, 6, 6) output = upsample(h, output_size=input.size()) output.size() # (1, 16, 12, 12) However, the actual output.size() returns (1, 16, 11, 11). Is this normal? I think it should be (1, 16, 12, 12) because ConvTranspose2d is just opposite operation for Conv2d.
st48654
This is expected, and that’s why there is the output_size argument to ConvTranspose2d, that compensates for it. As an example, suppose there is a convolution of stride 2 and kernel size 2. When applying it to a 4x4 image, the result is a 2x2 image. Now, if you apply the same convolution to a 5x5 image, the result will also be 2x2, so for a given Conv2d, two inputs map to the same output size.
st48655
fmassa: output_size ConvTranspose2d doesn’t have output_size argument, do you mean output_padding? oh , I found output_size in source code
st48656
There is output_size argument in nn.ConvTranspose2d.forward function. Just provide desired output shape during forward pass.
st48657
I find that ‘output_padding is provided to resolve this ambiguity by effectively increasing the calculated output shape on one side. Note that output_padding is only used to find output shape, but does not actually add zero-padding to output.’ in the official ducumentsconvtranspose2d 386. So I think we can use ‘output_padding’ parameters to make output size same.
st48658
ConvTranspose2d Weight Shape vision I have a question about ConvTranspose2d.weight shape. As mentioned in the PyTorch documentation the shape of ConvTranspose2d.weight tensor is as follows: (in_channels, out_channels​, kernel_size[0], kernel_size[1]) Note that I have omitted the groups parameter in the above shape. Now, my question is that why not its shape as follows? (out_channels, in_channels, kernel_size[0], kernel_size[1]) My problem related to the position of (in_channels, out_channels). As in some resources the Transpo…
st48659
@apaszke would you please answer my above question about the shape of weight tensor in transposed convolution?
st48660
It would be great to mention this in the docs of the nn.ConvTranspose2d object 168
st48661
Hello! does anyone know what to do when working with the functional version? f.conv_transpose2d does not have an output_size argument. I need to use the functional version since I am tying weights.
st48662
output_size is used to get the right output_padding as seen in this line of code 115. However, as you can see, this method is not exposed, so you could just define the output_padding manually or use this hacky way to invoke the method: conv = nn.ConvTranspose2d(3, 1, 2, 2, bias=False) x = torch.randn(1, 3, 10, 10) # vanilla output_vanilla = conv(x) print(output.shape) > torch.Size([1, 1, 20, 20]) # output_size output_size = conv(x, output_size=(21, 21)) print(output.shape) > torch.Size([1, 1, 21, 21]) # functional API weight = conv.weight.detach().clone() output_func = F.conv_transpose2d(x, weight, stride=2) print(output_func.shape) > torch.Size([1, 1, 20, 20]) print((output_func-output_vanilla).abs().max()) > tensor(0., grad_fn=<MaxBackward1>) # hacky way to get output padding output_padding = nn.ConvTranspose2d._output_padding( self=None, input=x, output_size=(21, 21), stride=(2, 2), padding=(0, 0), kernel_size=(2, 2) ) output_func_size = F.conv_transpose2d( x, weight, stride=2, output_padding=output_padding) print(output_func_size.shape) > torch.Size([1, 1, 21, 21]) print((output_func_size-output_size).abs().max()) > tensor(0., grad_fn=<MaxBackward1>) I’m not sure, why _output_padding is wrapped in a class method and not exposed publicly, so I would rather recommend to calculate the output_padding argument manually without relying on this hacky approach.
st48663
Thanks alot! yeah I’ll start with tweaking the output_padding, but that is a good alternative.
st48664
Hi would I able to put ConvTranspose2d in Sequential and adding other layers and writing output_size. I am working on wgan, where I want to experiment with both different Upsample layer with it, Like this, I used both layers just to increase image dimensions by 2 def upconv(in_channels, out_channels, kernel_size=1, stride=1, padding=0, batch_norm=True, up=False, trans=True): layers = [] # conv_layer = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, padding_mode=padding_mode) if up: layers.append(nn.Upsample(scale_factor=scale_factor, mode=mode, align_corners=align_corners)) if trans: layers.append(nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding)) if batch_norm: layers.append(nn.BatchNorm2d(out_channels)) return nn.Sequential(*layers) but Upsample works , but for ConvTranspose2d I need to write output_size so that it would just double dimension , but It is not possible a = torch.randn((1, 32, 16, 16)) upconv(32, 16)(a, output_size=(a.shape[0], a.shape[1], a.shape[2]*2, a.shape[3]*2)) How can i do this?
st48665
I think the easiest way would be to create a custom module and pass the output_size to it, if it’s static and should be used in an nn.Sequential container as seen here: class MyConvTranspose2d(nn.Module): def __init__(self, conv, output_size): super(MyConvTranspose2d, self).__init__() self.output_size = output_size self.conv = conv def forward(self, x): x = self.conv(x, output_size=self.output_size) return x conv = nn.ConvTranspose2d(1, 1, 2, 2) x = torch.randn(1, 1, 24, 24) out = conv(x) print(out.shape) > torch.Size([1, 1, 48, 48]) out = conv(x, output_size=(49, 49)) print(out.shape) > torch.Size([1, 1, 49, 49]) my_conv = MyConvTranspose2d(conv, output_size=(49, 49)) out = my_conv(x) print(out.shape) > torch.Size([1, 1, 49, 49]) model = nn.Sequential(MyConvTranspose2d(conv, output_size=(49, 49))) out = model(x) print(out.shape) > torch.Size([1, 1, 49, 49]) If you need to set output_size dynamically, I would recommend to write a custom model and not use nn.Sequential.
st48666
Thanks for great idea. It is working. class UpOrTrans(nn.Module): def __init__(self,in_channels, out_channels, mode='up', kernel_size=1, stride=1, scale_factor=2, padding=0, batch_norm=True, **kwargs): super(UpOrTrans, self).__init__() self.mode = mode upmode = kwargs.get('upmode', 'nearest') align_corners = kwargs.get('align_corners', None) self.batch_norm = batch_norm if self.mode == 'up': self.up = nn.Upsample(scale_factor=scale_factor, mode=upmode, align_corners=align_corners) self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding) if self.mode == 'trans': self.trans = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding) if self.batch_norm: self.bn = nn.BatchNorm2d(out_channels) def forward(self, x, output_size=None): if self.mode == 'up': x = self.up(x) x = self.conv(x) if self.mode == 'trans': x = self.trans(x, output_size=output_size) if self.batch_norm: x = self.bn(x) return x
st48667
2020-10-26 16:51:25.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1600.jpg torch.Size([1, 3, 1024, 724]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 506.9 MiB 506.9 MiB 1 @profile 141 def forward(self, x): 142 553.1 MiB 46.1 MiB 1 x = self.conv1(x) 143 598.6 MiB 45.5 MiB 1 x = self.bn1(x) 144 598.6 MiB 0.1 MiB 1 x = self.relu(x) 145 612.9 MiB 14.3 MiB 1 x = self.maxpool(x) 146 147 681.8 MiB 68.9 MiB 1 x = self.layer1(x) 148 707.1 MiB 25.4 MiB 1 x = self.layer2(x) 149 755.9 MiB 48.7 MiB 1 x = self.layer3(x) 150 788.4 MiB 32.5 MiB 1 x = self.layer4(x) 151 788.4 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 788.4 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:29.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1701.jpg torch.Size([1, 3, 768, 1024]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 685.6 MiB 685.6 MiB 1 @profile 141 def forward(self, x): 142 733.6 MiB 48.0 MiB 1 x = self.conv1(x) 143 781.6 MiB 48.0 MiB 1 x = self.bn1(x) 144 781.6 MiB 0.0 MiB 1 x = self.relu(x) 145 781.6 MiB 0.0 MiB 1 x = self.maxpool(x) 146 147 854.1 MiB 72.4 MiB 1 x = self.layer1(x) 148 940.2 MiB 86.1 MiB 1 x = self.layer2(x) 149 985.1 MiB 45.0 MiB 1 x = self.layer3(x) 150 1022.6 MiB 37.4 MiB 1 x = self.layer4(x) 151 1022.6 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 1022.6 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:32.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1728.jpg torch.Size([1, 3, 1024, 576]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 817.4 MiB 817.4 MiB 1 @profile 141 def forward(self, x): 142 853.4 MiB 36.0 MiB 1 x = self.conv1(x) 143 889.5 MiB 36.0 MiB 1 x = self.bn1(x) 144 889.5 MiB 0.0 MiB 1 x = self.relu(x) 145 898.5 MiB 9.0 MiB 1 x = self.maxpool(x) 146 147 952.8 MiB 54.3 MiB 1 x = self.layer1(x) 148 1027.0 MiB 74.2 MiB 1 x = self.layer2(x) 149 1034.5 MiB 7.5 MiB 1 x = self.layer3(x) 150 1064.4 MiB 29.9 MiB 1 x = self.layer4(x) 151 1064.4 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 1064.4 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:35.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1729.jpg torch.Size([1, 3, 1024, 576]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 960.9 MiB 960.9 MiB 1 @profile 141 def forward(self, x): 142 996.9 MiB 36.0 MiB 1 x = self.conv1(x) 143 1032.8 MiB 35.9 MiB 1 x = self.bn1(x) 144 1032.8 MiB 0.0 MiB 1 x = self.relu(x) 145 1041.8 MiB 9.0 MiB 1 x = self.maxpool(x) 146 147 1095.6 MiB 53.7 MiB 1 x = self.layer1(x) 148 1149.4 MiB 53.8 MiB 1 x = self.layer2(x) 149 1149.4 MiB 0.0 MiB 1 x = self.layer3(x) 150 1151.5 MiB 2.1 MiB 1 x = self.layer4(x) 151 1144.8 MiB -6.8 MiB 1 x = self.avgpool(x) 152 153 1144.8 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:37.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1730.jpg torch.Size([1, 3, 1024, 576]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 960.4 MiB 960.4 MiB 1 @profile 141 def forward(self, x): 142 996.4 MiB 36.0 MiB 1 x = self.conv1(x) 143 1032.3 MiB 35.9 MiB 1 x = self.bn1(x) 144 1032.3 MiB 0.0 MiB 1 x = self.relu(x) 145 1041.3 MiB 9.0 MiB 1 x = self.maxpool(x) 146 147 1095.1 MiB 53.7 MiB 1 x = self.layer1(x) 148 1148.9 MiB 53.8 MiB 1 x = self.layer2(x) 149 1148.9 MiB 0.0 MiB 1 x = self.layer3(x) 150 1151.0 MiB 2.1 MiB 1 x = self.layer4(x) 151 1148.1 MiB -2.9 MiB 1 x = self.avgpool(x) 152 153 1148.1 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:40.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1873 torch.Size([1, 3, 835, 1024]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 969.1 MiB 969.1 MiB 1 @profile 141 def forward(self, x): 142 1021.4 MiB 52.3 MiB 1 x = self.conv1(x) 143 1073.6 MiB 52.3 MiB 1 x = self.bn1(x) 144 1073.6 MiB 0.0 MiB 1 x = self.relu(x) 145 1089.9 MiB 16.3 MiB 1 x = self.maxpool(x) 146 147 1168.6 MiB 78.7 MiB 1 x = self.layer1(x) 148 1223.2 MiB 54.6 MiB 1 x = self.layer2(x) 149 1272.3 MiB 49.1 MiB 1 x = self.layer3(x) 150 1280.7 MiB 8.4 MiB 1 x = self.layer4(x) 151 1280.7 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 1280.7 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:43.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1874 torch.Size([1, 3, 961, 1024]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 1127.2 MiB 1127.2 MiB 1 @profile 141 def forward(self, x): 142 1187.4 MiB 60.2 MiB 1 x = self.conv1(x) 143 1247.5 MiB 60.1 MiB 1 x = self.bn1(x) 144 1247.5 MiB 0.0 MiB 1 x = self.relu(x) 145 1262.5 MiB 15.0 MiB 1 x = self.maxpool(x) 146 147 1413.0 MiB 150.4 MiB 1 x = self.layer1(x) 148 1542.6 MiB 129.6 MiB 1 x = self.layer2(x) 149 1568.0 MiB 25.5 MiB 1 x = self.layer3(x) 150 1613.7 MiB 45.7 MiB 1 x = self.layer4(x) 151 1613.7 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 1613.7 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:48.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1875 torch.Size([1, 3, 788, 1024]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 1424.6 MiB 1424.6 MiB 1 @profile 141 def forward(self, x): 142 1473.8 MiB 49.3 MiB 1 x = self.conv1(x) 143 1523.1 MiB 49.3 MiB 1 x = self.bn1(x) 144 1523.1 MiB 0.0 MiB 1 x = self.relu(x) 145 1535.4 MiB 12.3 MiB 1 x = self.maxpool(x) 146 147 1609.6 MiB 74.2 MiB 1 x = self.layer1(x) 148 1661.2 MiB 51.6 MiB 1 x = self.layer2(x) 149 1707.8 MiB 46.6 MiB 1 x = self.layer3(x) 150 1727.7 MiB 19.8 MiB 1 x = self.layer4(x) 151 1727.7 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 1727.7 MiB 0.0 MiB 1 return x torch.Size([2048]) 2020-10-26 16:51:51.000 INFO 6976 --- [ MainThread] __init__ : Extract: /Users/admin/Downloads/1602302351103/test/1876 torch.Size([1, 3, 744, 1024]) Filename: /Users/admin/code/tezign/cbir-feature-extract/core/resnet.py Line # Mem usage Increment Occurences Line Contents ============================================================ 140 1561.1 MiB 1561.1 MiB 1 @profile 141 def forward(self, x): 142 1607.6 MiB 46.5 MiB 1 x = self.conv1(x) 143 1654.1 MiB 46.5 MiB 1 x = self.bn1(x) 144 1654.1 MiB 0.0 MiB 1 x = self.relu(x) 145 1665.7 MiB 11.6 MiB 1 x = self.maxpool(x) 146 147 1735.8 MiB 70.1 MiB 1 x = self.layer1(x) 148 1836.8 MiB 100.9 MiB 1 x = self.layer2(x) 149 1869.1 MiB 32.3 MiB 1 x = self.layer3(x) 150 1869.2 MiB 0.1 MiB 1 x = self.layer4(x) 151 1869.2 MiB 0.0 MiB 1 x = self.avgpool(x) 152 153 1869.2 MiB 0.0 MiB 1 return x This is memory usage log, tracked with “Memory-Profile” python package I have tried "self.net.eval() " and “with torch.no_grad()”, but It was not worked. And I find a weird phenomenon, When input varied size images, that Memory increasing is bigger than same size input. Does anyone have encountered the same problem? Main environment: Mac OS Python 3.7 PyTorch 1.2(also tried with PyTorch 1.5)