user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
haoran-hash
The code snippet is below.屏幕截图 2021-09-21 0011471395×115 27.8 KB屏幕截图 2021-09-21 001219943×310 27.8 KB屏幕截图 2021-09-21 0012341291×597 130 KBThe ‘transforms’ argument can’t use?
ptrblck
Related issueThe linked object detection tutorial links to thereferences/detection/transforms.py, which implement transformations accepting an input and target tensor, so you would need to copy these fles (or git clone) to your workspace.
hilbert_deng
In my case, before the iteration I got several tensor which will be calculated through the whole training stage. As I noticed, the memory keeps increasing, even though I use .cpu(). The code structure is like allowings:tensor_for_accumulate = [ ]for iter in range(10):…tensor_current = …tensor_for_accumulate += tensor_c...
ptrblck
If tensor_current is attached to the computation graph (i.e. if its .grad_fn attribute returns a valid function) then all computation graphs will be stored with tensor_current in tensor_for_accumulate. Pushing tensor_current to the CPU doesn’t change anything if the operations were performed on the …
Gabriella_m
Hi I want to ask somebody if can explain to me what these two lines of code do with image and how can i take this transofrmation back.mask_np have shape - (3, 384, 512)mask_np = numpy.array(masks[group_idx][image_idx]).mean(axis=0).astype(int) mask_one_hot = numpy.eye(self.classes_count)[mask_np]
ptrblck
It’s a bit hard to certainly explain what this code is doing, as all objects are undefined. However, based on the used operations my guess is that mask_np would contain class indices, while mask_one_hot represents the one-hot encoded mask as seen here: # setup classes_count = 10 nb_samples = 3 # t…
thepurpleowl
Consider the forward passdef forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xIn model forward passes, if we use tensor transformations such as view(as shown in the...
ptrblck
Yes, all the mentioned operations will be tracked by Autocrat such that the gradient will be passed to the corresponding values during the backward pass.
talhaanwarch
I have 288 images, and i am using batch size of 4. So I think my steps_per_epoch is 288//4.I have plotted LR as followimport matplotlib.pyplot as plt opt = torch.optim.Adam(model.parameters(), lr=1e-4,weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer,pct_start=0.33, max_lr=1e-3,steps_per_epoc...
ptrblck
You could see the changing behavior by iterating the scheduler for 720 steps, since you’ve specified steps_per_epoch=72 and epochs=10. From the docs: epochs (int): The number of epochs to train for. This is used along with steps_per_epoch in order to infer the total number of steps in the cycle i…
Rituraj_19_Dutta_100
import torch import torch.nn as nn from torch.nn import ReLU, LeakyReLU import torch.nn.functional as F def conv(dim=2): if dim == 2: return nn.Conv2d return nn.Conv3d def trans_conv(dim=2): if dim == 2: return nn.ConvTranspose2d return nn.ConvTranspose3d def convolve(in_...
ptrblck
Your second code snippet is unfortunately not executable (the first one is and works fine), so I guess some of the input tensors do not have the float32 dtype and raise this error. Check the types of all tensors in your training loop and make sure they are floating point types.
blakebullwinkel
I am trying to train a GAN with the algorithm below but am getting the following error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [30, 1]], which is output 0 of TBackward, is at version 2; expected version 1 instead.I know that the pr...
ptrblck
This line of code looks strange: g_loss.backward(retain_graph=True) as it would keep the computation graph in G alive. Since you are also not detaching fake in: fake_loss = criterion(D(fake), fake_labels) these operations: d_loss = (real_loss + fake_loss)/2 + norm_penalty d_loss.backward(retain…
Mona_Jalal
Is this warning something I should worry about or try to resolve?[W pthreadpool-cpp.cc:90] Warning: Leaking Caffe2 thread-pool after fork. (function pthreadpool)Full log:Specifically, I am not sure which line of my code is causing it:(fashcomp) [jalal@goku fashion-compatibility]$ python main.py --name test_baseline --l...
ptrblck
The issue is already fixed as describedhere. You could either update to the nightly binary, wait for the 1.9.1 release (which is already in RC4) or build from source.
asha97
I am trying to work on video dataset , so when I read the video using the functiontorchvision.io.read_videoI am getting the ouput in form of a tuple. (I only want to work with video frames).If i try to pass elements from tuple one by one tor2plus1d=models.video.r2plus1d_18(pretrained=False, progress=True)I am getting t...
ptrblck
Based on the error message a 5D input tensors is expected. As described in thedocsthe tensors should have the shape [batch_size, 3, T, H, W], where T represents the number of frames while H and W were set to 112 in the pretrained models.
Noman-Tanveer
I have an iterable dataset object with all of my data files. How can I split it into train and validation set. I have seen a few solutions for custom datasets but iterable does not supportlen()operator.torch.utils.random_sample()andtorch.utils.SubsetRandomSample()don’t work.def __init__(self): bla bla...
ptrblck
I don’t think you could split the samples in the IterableDataset as it’s used for e.g. streams of data. In case your dataset is predefined, you could check if the stream source is able to split and shuffle the data.
NeuralFoX
Hello, I am a beginner in PyTorch.I am trying to learn by building a toy example with custom data. Here is my code:import torch import torch.nn as nn import torch.optim as optim data={}; for iter in range(10): data[iter]=[torch.tensor([1]).long().type(torch.LongTensor),torch.tensor([2]).long().type(torch.LongTensor)] ...
ptrblck
PyTorch assumes that the first argument to a method has the “right” dtype and thus claims that Long is expected in the model parameter. However, you should use FloatTensors to train the model in order to be able to calculate gradients (which are defined for floating point types). Transform the dat…
Latope2-150
Hi,I am experiencing a surprising behavior when converting a binary PIL image to BoolTensor through numpy.import numpy as np import torch from PIL import Image, ImageDraw mask = Image.new(mode='1', size=(6, 6), color=False) draw = ImageDraw.Draw(mask) draw.polygon([(2, 2), (4, 2), (4, 4), (2, 4)], fill=True) np_mask ...
ptrblck
This seems to be related tothis issueas it seems that the BoolTensor is transformed to a ByteTensor where True represents 255. Feel free to add your use case to this issue.
ElQadasi
I want to print the indices of the batch where I use SubsetRandomSampler.train_dataset = datasets.MNIST(root=’./train’, train=True,download=True,transform=transform)train_loader = DataLoader(train_dataset, batch_size=32,sampler=SubsetRandomSampler(range(len(train_dataset))))for train_x, train_label in train_loader:# I ...
ptrblck
You could create a custom Dataset and return the index with the data and target tensors in the __getitem__ method. To do so, take a look atthis tutorialand or override the MNIST dataset with your custom __getitem__ implementation.
fangwei123456
Name Version Build Channelpytorch 1.7.1 py3.8_cuda110_cudnn8_0 pytorchCodes:import torch device = 'cuda:0' x = torch.rand([2, 3, 4], device=device).transpose(0, 2) y = torch.zeros_like(x) args_list = [x, y] ret_list = [] for item in args_list: if...
ptrblck
You are creating new tensors in: item = item.contiguous() and replace them directly in each iteration, which could (and in your case will) reuse the data_ptr. If you print item.data_ptr() of x and y or item before the contiguous() call you would see that they are different.
akib62
You can see thedtypeof theb_yisInt64and I am getting an errorTraceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/home/Opps...
ptrblck
Double post fromherewith solution.
akib62
I have a code (fromhere) to classify the MINST digits. The code is working fine. Here they usedCrossEntropyLossandAdamoptimizer.The model code is given belowclass CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d( ...
ptrblck
I guess you are transforming b_y to float before applying one_hot, not after? This works: # Train the model criterion = nn.MSELoss() for i, (images, labels) in enumerate(loaders['train']): b_x = images # batch x b_y = labels # batch y ohe_target = torch.nn.functional.one_hot(b_y, n…
Arsham_mor
I was looking for simple example ofSiamese Networksand I found thisarticleat hackernoon.input batch first go throughnn.ReflectionPad2d(1)as shown below:class SiameseNetwork(nn.Module): def __init__(self): super(SiameseNetwork, self).__init__() self.cnn1 = nn.Sequential( nn.ReflectionPad2...
ptrblck
I guess the ReflectionPad2d layers were added as nn.Conv2d supported zero padding only in the past (in new PyTorch versions you can specify the padding_mode). I don’t know if the author has explained this architecture in a research paper, but would guess that this padding type worked better than ze…
machina
Here is the start and end the .th file that my weights are stored in :PATH = './pytorch_resnet_cifar10/pretrained_models/resnet32-d509ac18.th' net = resnet32().to(device) print(torch.load(PATH))Output:{'state_dict': OrderedDict([('module.conv1.weight', tensor([[[[ 4.0355e-01, -5.4608e-01, -6.8499e-01], [-1.0...
ptrblck
net.load_state_dict expects the actual state_dict as its input while you are passing your custom dict to it. Try to use: net.load_state_dict(torch.load(PATH)['state_dict']) and it should work.
qingye_meng
import torchfrom transformers import BertModel, BertForMaskedLMdef convert_onnx():model_path = ‘…/bertLM_model_pytorch/pytorch_model.pt’dummy_input0 = torch.LongTensor(16, 128).to(torch.device(“cuda”))dummy_input1 = torch.LongTensor(16, 128).to(torch.device(“cuda”))dummy_input2 = torch.LongTensor(16, 128).to(torch.devi...
ptrblck
I guess the error is caused in: model=BertForMaskedLM.from_pretrained(model_path) which most likely does not expect a path to a state_dict, so check the docs for this method and make sure to pass the right arguments to it.
avalon1511
Hi, I have model A which is pretrained and Model B which is new. Model B has all of the layers of model A + an extra layer.I want to load the weights from Model A → B for the layers they have in common.I implemented the following:pretrained_path = torch.load(path to pretrained model) new_model_dict = model.state_dic...
ptrblck
In case you are using the same layer names, you could iterate the named_modules in both models and load the state_dict per layer. If that’s not the case, you could create a mapping between the names of the pretrained modelA layers and the modelB layers and do the same. This would avoid the strict=Fa…
jkking
Hi,I’m working on training a light GAN on Google Colab and thus need to resume training over a couple of sessions. I can save and load the generator and discriminator state dicts A-OK, but get the following error when trying to load the adam optimizer state dicts:--------------------------------------------------------...
ptrblck
You are storing the state_dict methods in: torch.save(g_optimizer.state_dict, '/content/drive/MyDrive/GAN_Temp/g_optim.pth') torch.save(d_optimizer.state_dict, '/content/drive/MyDrive/GAN_Temp/d_optim.pth') and would need to call this method to store the actual state_dict: torch.save(g_optimizer.…
Hiro_Protagonist
n = 10x = torch.zeros(n)x = x[:n//2].cuda()at this point, we have leaked memory on the cpuI am using this gist:A simple Pytorch memory usages profiler · GitHubto profile. It basically traverses objects accessible by gc and checks where they are.x points to a buffer on gpuIn [5]: mem_report() ...
ptrblck
I cannot reproduce this behavior and see: Before running your code: ================================================================= Element type Size Used MEM(MBytes) Storage on GPU ----------------------------------------------------------------- ----------------------------------------------…
thavens
device: gtx 1070tensor info:variable shape of approx: [150, 6]dtype: torch.int16I’ve also tested float32 but got the same resultstq = tqdm(trainset) for i in tq: optimizer.zero_grad() tic = time.time() pred = model(i[0].to(device)) toc = time.time() #This is what is taking so long i[1] = i[1].cu...
ptrblck
CUDA operations are executed asynchronously, so you would need to synchronize the code before starting and stopping each timer via torch.cuda.synchronize(). Otherwise the times will be accumulated in blocking operations and are thus wrong.
cjfghk5697
System informationEnvironment: ColabErrorimage1483×531 15.5 KBI want to solve this error.Error Codecolab.research.google.comGoogle ColaboratoryIn detailI try EfficientNetB0. And I use ConV2D. train dataset is work well. But test dataset not work. I think It’s problem Padding data type. But I don’t know how can solve t...
ptrblck
You are passing the DataLoader directly to the model in: result=model(test_loader) while you would have to iterate the DataLoader and pass the input tensors to the model. Take a look atthis tutorialfor a simple example. In your case something like: for data, target in test_loader: output …
ZimoNitrome
Looking at thePyTorch implementation of DCGANbut also GANs in general…To me it would seem intuitive to set G in train and D in eval when training G, and vice versa while training D. However, I don’t see this done in any GAN implementations.Not switching to train/eval mode, it would seem that doing backprop on D(G(noise...
ptrblck
No, since model.eval() and model.train() do not change the gradient calculation or the backpropagation in general. Instead the behavior of certain layers is changed. E.g. dropout layers are disabled during eval() and batchnorm layers will use their internal running stats to normalize the input acti…
rodrigers
Hi,I am facing a problem when executing two Python scripts (same script but different arguments) on different GPUs.Basically, what happens is that when I run the two scripts, I got a “RuntimeError: CUDA error: out of memory” message. However, if I run only a single instance, the script works.Please, could someone help ...
ptrblck
You could try to increase the number of workers, but note that it could also slow down your code in case too many processes are open or if the bottleneck is created by reading the data from the SSD (as more workers cannot speed up the bandwidth).
rajeshpiryani
To write checkpoint in TensorFlow, first it will build the computational graph, the nodes and operations and how they are connected to each other and then it will use session.Following codes storing the checkpoint in TensorFlow:import os import tensorflow.compat.v1 as tf import numpy as np def savecheckpoint(var_name,...
ptrblck
I don’t know what the TF code is exactly doing, but in PyTorch you can save and load numpy arrays as well and adding them to a dict is also a valid idea: a= np.random.randn(10) checkpoint = { 'np_arr': a } torch.save(checkpoint, 'tmp.pth') b = torch.load('tmp.pth')['np_arr'] print(all(a == b)…
Jonas_ar
Hello everyone,I want to change or reset the weights of specific layers to see the effect on the object classification accuracy of some models.I basically want to test the fault resillience of certain object classification models and simulate a bitflip that changes the weights in one or multiple layers.Right now I impl...
ptrblck
tensor.normal_ should work
daniel125
Hi, I have implemented the following model:# Solution for CIFAR-10 dataset, using NN with one hidden layer import torch import torchvision import torch.nn as nn import matplotlib.pyplot as plt import torch.nn.functional as F import torchvision.transforms as transforms from torch.backends import cudnn from torchvision....
ptrblck
The GPU is already used for the model forward and badckward passes. However, since your model is really small, the CPU workload might be the bottleneck and would thus cause a low GPU utilization. E.g. using some imaginary numbers: GPU forward + backward pass takes 1s data loading and processing …
Aymen_Sekhri
Hello EveryoneI hope you are doing awesome, I am stuck on a big problem, I read lots of blogs about it but there isn’t a real solution.The problem is when I loop through my data loader (I am usingChexpert dataset) I find NoneType objects instead of images.The structure of the dataset isThe root directory is CheXpert-v1...
ptrblck
I’m not sure what exactly “it does not work” mean regarding the last code snippet, i.e. if the check is not working or if you are seeing None samples and are unsure how to fix it. In any case, I would try to narrow down why None objects are returned and try to fix this afterwards. To do so, use a b…
Rituraj_19_Dutta_100
I’m using Transposed Convolutions in my network and I want to keep the shape of the output 3rd(indexing from 1) dimension same as in input. How can I do that with ConvTranspose3d() ?import torch import torch.nn as nn x = torch.randn(1,3,1,128,128).cuda() layer = nn.ConvTranspose3d(in_channels=3,out_channels=3,kernel...
ptrblck
You can specify the kernel_size, stride, dilation, and padding for each dimension separately and using a single scalar value is a convenient way to set all dimensions to the same value. This should thus work: x = torch.randn(1,3,1,128,128).cuda() layer = nn.ConvTranspose3d( in_channels=3, …
fanl
Hi everyone,I come across the following error occasionally:File “/root/.pyenv/versions/3.6.8/lib/python3.6/site-packages/mmcv/runner/hooks/optimizer.py”, line 259, in after_train_iterscaled_loss.backward()File “/root/.pyenv/versions/3.6.8/lib/python3.6/site-packages/torch/tensor.py”, line 195, in backwardtorch.autograd...
ptrblck
Any invalid memory read or write can cause this issue. The mentioned out of range indexing is a common issue, which could also be caused by e.g. race conditions etc. I don’t think it can (at least this would be the first time an OOM is causing the memory violation).
x06lan
train.pyimport math from numpy.core.fromnumeric import shape import torch import matplotlib.pyplot as plt import json import numpy as np import torch.nn as nn import torch.nn.functional as F import torchvision.transforms.functional as TF import numpy as np import cv2 import time from PIL import Image import random impo...
ptrblck
You would need to make step 3 differentiable, i.e. render the image through PyTorch (or a library built on top of PyTorch such asPyTorch3Dwhich seems to implement a differentiable renderer) as I expect that Blender breaks the computation graph.
JVedant
Hi, I am trying to create a custom dataset that loads multi-page tiff files (shape=(h, w, d, c)). Here the channel’s value is 4 and so when applying transforms.ToTensor() on the image, it shows an error ofValueError: Caught ValueError in DataLoader worker process 0. Original Traceback (most recent call last): File "/...
ptrblck
ToTensor() checks image arrays to have 2 or 3 dimensions to make sure they are either grayscale or color images. Based on your description you are using a volume (with an additional depth dimension) so depending on your use case you could transform the numpy array to a tensor manually via x = torch.…
Aayushktyagi
Hi,I am applying edge operation on 10% of images on the dataset. Suppose these are 6 classes.How do I ensure that edge operation is applied to samples from each class?(each class should have at least 1 images with edge operation applied to it)Sample code below:class cannyedge(object): def __init__(self, threshold1 ...
ptrblck
Since you are randomly applying the transformations you won’t have a guarantee to apply it, but could estimate the likelihood of getting a transformed sample for each class. Based on your description you could e.g. apply the transformations separately to at least one sample per class and let the ot…
ArshadIram
I want to calculate the loss between two images that are``But the problem is that:x shape is [128, 11, 28, 28] and x’ shape is [128,1,28,28].``How can I calculate the loss between these two images?Any help would be appriciated.
ptrblck
You could broadcast the second tensor to the same shape as the first one and could then apply e.g. nn.MSELoss. The right approach depends on the actual use case and the desired loss function, i.e. since both tensors have a different shape, what should the loss represent?
AntMorais
Hello everyone,I want to use the code in theObject Detection Finetuning Tutorialto train and test a Mask-RCNN model ontorchvision.datasets.Cityscapes.I am having trouble with thetrain_one_epochfunction, similarly to what is happening in this issue'train_one_epoch' gives error while using COCO annotations · Issue #1699 ...
ptrblck
It seems that the targets are expected in the “COCO format”, sothis repositorymight be useful, which seems to convert Cityscapes to COCO.
Aymen_Sekhri
Hello Everyone,Actually, I followed many Pytorch tutorials and I found that most of them speak about how to implement Custom Datasets and I am wondering why they are so important?Especially in computer vision where All datasets follow certain organizational patterns and there are built-in functions to load the data eas...
ptrblck
While some public datasets follow a specific pattern (and thus can be loaded using a torchvision dataset), a custom Dataset gives you the ability to load your custom dataset using any logic you want. I.e. you don’t have to follow a specific folder structure, can apply transformations using differen…
SU801T
Hi,I get this error:RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device(‘cpu’) to map your storages to the CPU.I’m not sure if I am saving my outputs incorrectly, however, I...
ptrblck
I don’t quite understand why this error is raised in the posted code, as it’s pointing to a deserialization in a non-CUDA installation. Based on the code snippet I assume you might be using CUDA tensors? If so, could you push them to the CPU before trying to store them via pandas?
Kasi_Chennupati
Hii have created a simple Linear AE and using adam optimizeri have two functions to minimizeloss1 = reconstruction lossloss 2 = centroids and encoded space euclidean distanceso I created something like below pytorch version 1.9.0+cu102loss1 = 0.8*criterion(decoded, image) loss2 = torch.sum(torch.cdist(encoded, dist_m...
ptrblck
That sounds valid and I don’t know why retain_graph=True would be needed. Based on your description you are executing forward passes through the models, calculate losses, accumulate them, and call backward on the final loss. I don’t see why the graph should be kept alive and where the “backward th…
meshghi
Hello, I’m implementing a research paper, and I need to calculate the F.cross_entropy for each class separately as I will be using them later separately before joining them as the final loss (like the attached image). I was wondering how I could do it? Thanks.
ptrblck
I’m not entirely sure, but you could try to use the unreduced loss via reduction='none', apply your custom operations, and reduce it afterwards.
atax
Hi,I’m trying to adapt the architecture fromhereto run on 3D volumes of size 182 x 218 x 182 (a.k.a. more channels than the standard RGB, and uneven height-width ratio).Here are my Encoder, Decoder and Autoencoder:class Encoder(nn.Module): def __init__(self, num_input_channels : int, ...
ptrblck
The new error doesn’t seem to be an equivalent error, since the forward pass is failing due to an expected shape mismatch in the Encoder. Change: nn.Linear(2*16*c_hid, latent_dim) to nn.Linear(41216, latent_dim) and the model works for me: num_input_channels, width, height = 182, 218, 182 …
Hatem
I get the following errorRuntimeError: upsample_bilinear2d_backward_out_cuda does not have a deterministic implementationIs there a workaround?
ptrblck
The workaround would be to use the CPU implementation, i.e. push the data to the CPU before applying this method and back to the GPU afterwards for now assuming that you need the deterministic outputs for debugging (as it would slow down your code).
louisabraham
I have a deterministic code that gives the same result between runs on the same machine.I tried to launch it on two machines:my macbook pro m1 with intel python 3.8 and torch=1.9.0google colab with python 3.7 and torch=1.9.0+cu102It gives different results in most cases.However, if I set the optimizer to Adam and use 1...
ptrblck
There is no guarantee to get deterministic results on different hardware architectures, since e.g. the pseudorandom number generator implementation could be different. I don’t quite understand this claim. Since you are not using deterministic algorithms, you shouldn’t expect to get deterministic r…
Capo_Mestre
Hello,I use two different custom functions to load the network parameters. I load the network into two different variables ‘network1’ and ‘network2’.When I compare them asnetwork1 == network2, the result isFalseeven though state-dictionaries seem to coincide, although I havent checked every single entry. Is this a supp...
ptrblck
I assume you would like to compare the parameters and buffers of these models to make sure they re “equal”? If so, you would have to compare these tensors directly as I think you are now comparing the ids of the Python objects instead.
Adwaitt
Hello guys, you can find my code below. It throws the following error “Expected more than 1 value per channel when training, got input size torch.Size([1, 256])”This is my data generator code:class datagen(Dataset): def __init__(self, df, tfms): super(datagen, self).__init__() self.x = df['x'] ...
ptrblck
This view operations looks wrong: x = x.view(1, 64000) since you are flattening the tensor such that it’ll have a batch size of 1. To keep the batch size equal, use x = x.view(x.size(0), -1) instead. In case you would still run into the batchnorm issue, check if the last batch returned by the Da…
AM.MO
this the model config.CNN((hidden_layers): Sequential((0): Conv2d(1, 32, kernel_size=(9, 9), stride=(1, 1), padding=(4, 4))(1): ReLU()(2): Conv2d(32, 32, kernel_size=(9, 9), stride=(1, 1), padding=(4, 4))(3): ReLU()(4): Conv2d(32, 32, kernel_size=(9, 9), stride=(1, 1), padding=(4, 4))(5): ReLU()(6): Conv2d(32, 32, kern...
ptrblck
PyTorch models don’t have a shape dependency regarding the batch dimension, so you would be able to pass the test inputs with a batch size of 1 to the model.
avalon1511
I have a Generator defined as:class Generator(nn.Module): def __init__(self, ngpu): super(Generator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False), ...
ptrblck
You could create a new custom nn.Module and add it into the nn.Sequential container: class ShiftLayer(nn.Module): def __init__(self, b): super().__init__() self.register_buffer('b', b) def forward(self, x): return x + self.b class Generator(nn.Module): …
Mari
Hi,How can I freeze network in initial layers except two last layers? Do I need to implement filter in optimizer for those fixed layers? if yes how?class Net_k(nn.Module):#The __init__ function stack the layers of the #network Sequentially def __init__(self): super(Net_k, self).__init__() self...
ptrblck
You can set the .requires_grad attribute of the parameters of the first layers to False to freeze them. You don’t necessarily need to filter out frozen parameters, as they won’t be updated, but could do it via e.g torch.optim.SG(filter(lambda p: p.requires_grad, model.parameters()), lr=...).
Nil_MSh
Hi! I’ve trained a ResNet model and now I’m using it on another dataset and I need access to all the activation values for each neuron for each image. How can i do that?This is the part of my code that concerns the model:def conv3x3(in_channels, out_channels, stride=1): return nn.Conv2d(in_channels, out_channels, k...
ptrblck
You can use forward hooks as describedhereto get intermediate activations.
ekoplin
Hi, I’m trying to define a new sampler based on torch.poisson which is implemented in cpp. The idea is compile it using cpp_extension from torch. I got compilation errors when trying to include Aten module in cpp. The example code and the returned message can be found below. How can I call that cpp function from pytorc...
ptrblck
The error is raised in: /home/eric/Desktop/test_1/main.cpp:15:10: fatal error: ATen/CPUGenerator.h: No such file or directory since ATen/CPUGenerator.h was moved inthis PR, so you would need to use the new file name.
hotpanda
OS: ubuntu 16.04Cuda: 10.2pytorch: 1.8.0I ran the demohttps://pytorch.org/tutorials/recipes/recipes/amp_recipe.html#a-simple-network.default precision training time is 1.760 sec and mixed precision training time is 0.833. 2x speed up. But when I use torch.nn.Conv2d, amp training is slower than default model. please tel...
ptrblck
Thanks for the update! I’ve added some missing warmup iterations, since you are using cuDNN’s benchmark mode, so the first iteration will see a slowdown due to the internal profiling. I can reproduce the slower kernel execution time in FP16 using the default memory format, but see a speedup using m…
4158ndfkvBHJ1
Hello everybody,I have a dataloader, with a__getitem__function, that reads as follows:def __getitem__(self, index): # pre-processing annotation with torch.no_grad(): annotation = torch.zeros((self.image_size[0], self.image_size[1])) points = np.loadtxt(os.path.join(self...
ptrblck
The DataLoader will add the batch dimension to the sample in dim0. Based on your description it seems that you are using batch_size=1 which is why the additional dimension with a size of 1 is added. I don’t know what the other dimension represent, but if you are manually already trying to add a bat…
Hasan_Khan
I am trying to produce the inference results oftacotron2andwaveglowmodel on CPU. I have changed all thecuda tensorstocpuindenoiser.py,glow.pyand all the files in which changes were required, But still I am getting thisNo CUDA GPUs are available error.I have attached the screen shot of the error. Please help e figure ou...
ptrblck
I don’t know what exactly you’ve changed, but this code works for me without a GPU: import torch print(torch.cuda.is_available()) waveglow = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_waveglow', model_math='fp32') waveglow = waveglow.remove_weightnorm(waveglow) waveglow.eval()…
The_duke
Hi all, first post here.I am getting the error in the title when I am calling loss.backward:criterion = nn.MSELoss()…train_epoch_loss = 0 train_epoch_acc = 0 model.train() for X_train_batch, y_train_batch in train_loader: X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(dev...
ptrblck
.argmax is not a differentiable function, so you are detaching the model output in: y_train_pred = model(X_train_batch).argmax(dim=1).float() which will raise the error. I don’t know what kind of use case you are working on, but in case it’s a multi-class classification, pass the raw logits to n…
Sarmad_GTU
[WinError 1455] The paging file is too small for this operation to complete. Error loading “C:\Users\gtu\anaconda3\envs\Deeplearning\lib\site-packages\torch\lib\caffe2_detectron_ops_gpu.dll” or one of its dependencies.How can I overcome this error?
ptrblck
I don’t use Windows, butthis issuecame as a direct result searching for your error message.
DanteTemplar
How to beautifully implement cross-validation in pytorch, while using different transformers for validation and training selection?Are there solutions that only change the dataloader iterator, that is, do not require many changes in the fitting code?
ptrblck
skorchis a sikit-learn compatible PyTorch wrapper, which should allow you to apply the scikit-learn cross-validation utilities directly.
Krishna_Garg
I am trying to installcondaforcudatoolkit=11.2on google colab using:conda install pytorch cudatoolkit=11.2 -c pytorch -c nvidiaBut why does it install oldpytorch=1.0.0version not something>1.6?If I try to force installpytorch=1.6, it gives the following error:UnsatisfiableError: The following specifications were found ...
ptrblck
No, you cannot install the PyTorch binaries built with CUDA11.2, since they are not available. If you want to use this specific CUDA version, you could build from source. Alternatively, you could install the nightly binaries with CUDA11.3 using: pip install --pre torch -f https://download.pytorch…
Lost_Wanderer
Hello PyTorch developers,I am trying to replace GRU’s with LSTM’s in an Encoder-Decoder architecture and it results in an error. I don’t understand why the error is there.Could someone shed some light on what is going on here?Here’s the code which works, along with its outputs. The code pertains to Exercise 5, Chapter ...
ptrblck
I don’t know where the required shape of 7 is coming from, but from the docs: h_n: tensor of shape (D∗num_layers,N,H out) containing the final hidden state for each element in the batch. Given that you are using num_layers=2 and bidirectional=False, dim0 is expected to have the shape 2.
hossein
Hello,I’m training a CNN network and these are my results for the first 14 epochs:As you can see, despite that my train loss rose to 1.3 from epoch 2 to 3, my train accuracy increased, while it should be decreased! (there are other epochs like what I said. for example, between epoch 8 and 9, between epoch 10 and 11). I...
ptrblck
This might be expected, as the loss and accuracy do not strictly depend on each other. I.e. the range of the logits also defines the loss, while only the argmax logit defines the prediction (and thus changes the accuracy) as seen in this small example: # setup criterion = nn.CrossEntropyLoss() # …
Ilya_Kotlov
Hi, I defined in this way my two dataloaders, one random and one sequential and i’ve started to suspect there is a data leak (although not necessarily).Could you give it a glimpse ? Do the dataloaders seem to be doing what I’ve intended without data leaks ?Thank you in advance.P.S I’ve adapted some existing code, so ma...
ptrblck
I don’t see any way this code would leak memory, so would assume it’s fine.
sad_robot
I’ve got a model with 110M parameters, and I’m training it on a very small dataset (like 500 examples).Yet that is enough to crash Pytorch on a K80 GPU with 11GB VRAM.What is going on here? 110M x 4 (float size) = 440M = 0.440 GB + minuscule dataset size != 11GB VRAM…Thanks for your help
ptrblck
The memory usage is model-dependent and often the majority of the memory is used by the forward activations, not the parameters or gradients. E.g. inthis postI’ve posted some stats about the used model and you can see that the activations use: 6452341200 / 138357544 ~= 47 times more memory tha…
YoYoYo
I am training a progressive GAN model with torch.backends.cudnn.benchmark = True. The ProGAN progressively add more layers to the model during training to handle higher resolution images.I notice that at the beginning of the training the GPU memory consumption fluctuate a lot, sometimes it exceeds 48 GB memory and lead...
ptrblck
Yes, you could use it for better performance especially if you are dealing with static input shapes (or a few different ones). Each new input shape (and conv setup) will rerun the heuristics and will thus slow down your code. Afterwards this setup will be cached. Yes, it’s coming from running d…
robeast
Dear community,I am working in the field of deploying PyTorch models. Our customers provide us models which have beenjit.scipt(...)-ed and saved as*.ptfiles. This is the common model exchange interface they have defined for us.The “unholy” thing that I’m trying to achieve now is to concatenate two such scripted models ...
ptrblck
I had something like this in mind: # save model1 = nn.Linear(10, 5) model2 = nn.Linear(5, 2) model1 = torch.jit.script(model1) model2 = torch.jit.script(model2) torch.jit.save(model1, 'model1.pt') torch.jit.save(model2, 'model2.pt') # load class MyModel(nn.Module): def __init__(self, model1…
helloybz
Hi.In pytorch implementation, LSTM takes droupout argument for its constructor, which determines the probability of dropout.Any ideas on whether dropouts are ignored in evaluation mode? Ex) model.eval()
ptrblck
Yes, it should be disabled: # no dropout model = nn.LSTM(10, 10, 2, dropout=0.0) x = torch.randn(10, 10, 10) out1, _ = model(x) out2, _ = model(x) print((out1 - out2).abs().max()) > tensor(0., grad_fn=<MaxBackward1>) # dropout model = nn.LSTM(10, 10, 2, dropout=0.5) x = torch.randn(10, 10, 10) out…
helloybz
Hi.I’m trying to useDistributedDataParallelin a single GPU node, for practice.I checked my model’s size right after initializing it bysum([p.numel()*4 for p in model.parameters()])/1024/1024, and it says1140.xxxand then I wrapped the model withDistributedDataParallelbydmodel =DistributedDataParallel(module=model, ...)....
ptrblck
That’s great debugging! I’ve checked the behavior with@mcarilliand he confirms that the Reducer will create gradient buckets for each parameter, so that the memory usage after wrapping the model into DDP will be 2 x model_parameter_size. Note that the parameter size of a model is often much smal…
jastern33
Cross-postingfrom stackoverflow, because it wasn’t getting much attention there. There’s an open bounty, and if anyone answers over there, I’m happy to award it to you.The question is: when I use distributed data parallel, I see double the memory usage (almost exactly) on distributed data parallel compared to single-GP...
ptrblck
You are most likely seeing the same effect describedhere.
Haozhi
My optimization problem is as follows:a = torch.rand(2, 2, requires_grad=True) b = torch.rand(1, requires_grad=True) # f is a very time-consuming function which I don't # want to do it every iteration. c = f(b) for i in range(N_epoch): for j in range(N_iteration): # loop over all batches L = loss(da...
ptrblck
I’m not sure how your use case works exactly, but to keep the computation graph (and the intermediate tensors) alive, you could use backward(retain_graph=True).
Xiangtaokong
Is dropout in pytorch a pseudo-random operation?For example, ‘out’ is a tensor with [n,c,h,w]out=self.lrelu(self.conv_1(out)) out1 = F.dropout(out, 0.1, training=True) out2 = F.dropout(out, 0.1, training=True) out3 = F.dropout(out, 0.1, training=True) print(out1) print(out2) print(out3)When I run the above cod...
ptrblck
F.dropout will randomly sample the mask in each call using the internal pseudo random number generator. If you seed the code, you would thus get the same random numbers and the result would be equal for different runs of the script.
Fred2
I have a computer with both a NVIDIA Geforce RTX 3070 and an Intel UHD Graphics 630. The Intel chip came disabled, with the manufacturer suggesting that the NVIDIA drive the monitors.If I use the NVIDIA GPU to drive my displays (Windows desktop, IDE, web browser, etc), is that taking any appreciable amount of resource...
ptrblck
A disadvantage of using your 3070 for the display is that you would be using GPU memory, which is usually more limited than the host RAM. E.g. in my plain Ubuntu20.04 setup my GPU is using ~1.2GB for the display output (Xorg, gnome-shell, firefox etc. are reported by nvidia-smi).
Mona_Jalal
could someone please confirm if this change (## refers to old code)# measure accuracy and record loss ##losses.update(loss_triplet.data[0], num_items) ##accs.update(acc.data[0], num_items) ##emb_norms.update(loss_embed.data[0]) ##mask_norms.update(loss_mask.data[0]) losses.update(loss_triplet....
ptrblck
Remove the .data usage, as it could break your code and use .item() instead: losses.update(loss_triplet.item(), num_items) accs.update(acc.item(), num_items) emb_norms.update(loss_embed.item()) mask_norms.update(loss_mask.item())
jpainam
Hi, I’m working with the new library PytorchVideo. And I’m using ResNet3DMy input sequence for a single batch size istorch.Size([1, 3, 16, 224, 224])and I was expecting to get after the average pool layertorch.Size([1, 2048, 16, 1, 1])but I gottorch.Size([1, 2048, 13, 1, 1]). I can’t figure out how the sequence length ...
ptrblck
No, that’s not the case and is the difference between the 2D and 3D layers. While the 2D layers apply the kernel on the H and W dimension for an input of [N, C, H, W], 3D layers will use a 3D kernel applied on D, H, W for an input of [N, C, D, H, W].
Mona_Jalal
Is this code correct or what arguments should I pass to the adaptiveavgpool2D and softmax? I suspect it is wrong since it is giving me lower than expected accuracyself.layer_attend1 = nn.Sequential(nn.Conv2d(64, 64, stride=2, padding=1, kernel_size=3), nn.AdaptiveAvgPool2d(1), ...
ptrblck
The docs describe each input argument (nn.AdaptiveAvgPool2d,nn.Softmax) so you can see that the former is using the argument as the output_size while the latter uses it as the dim argument. In case you are unsure what these arguments do, write a small code snippet to check its usage, e.g. via: po…
PytorchLearning
Hi allI was looking at the new Pytorch profiler, and I am trying to learn GAN model at the same time.Since GAN models contains two models: a Discriminator model and a Generator model.How can I see the Pytorch profiler of the GAN model? Do I have to see the Pytorch profiler of each model alone or can I see the Pytorch p...
ptrblck
I think you could reuse the provided code snippets from the blog post, e.g. something like this should work: with torch.profiler.profile( schedule=torch.profiler.schedule( wait=2, warmup=2, active=6, repeat=1), on_trace_ready=tensorboard_trace_handler, w…
KouWeiBin
I have trained a model using python and the network was defined as follow:class ResidualFeatureNet(torch.nn.Module): def __init__(self): super(ResidualFeatureNet, self).__init__() # Initial convolution layers ...
ptrblck
Based on this error message it seems you are passing a list of tensors to the model while a tensor is expected so you would have to check the inputs to the model.
dataloader
My data is not distributed in train and test directories but only in classes. I mean:image-folders/ ├── class_0/ | ├── 001.jpg | ├── 002.jpg └── class_1/ | ├── 001.jpg | └── 002.jpg └── class_2/ ├── 001.jpg └── 002.jpgIs it the right way to approach the problem (What this does...
ptrblck
The creation of the indices looks wrong and you could check if by using: data = np.zeros(100) valid_size = 0.2 test_size = 0.1 indices = np.arange(len(data)) split = int(np.floor(valid_size * len(data))) train_idx, valid_idx = indices[split:], indices[:split] split = int(np.floor(test_size * len(…
turian
I am using Google GCP GPUs, and it appears the only machine image they provide is CUDA 11.0 (!). Only pytorch <= 1.7 supports CUDA 11.0.I am creating a Dockerfile for my project. However, some of my library’s dependencies want pytorch 1.9, so they upgrade from pytorch 1.7 GPU version to pytorch 1.9 CPU version.I think ...
ptrblck
Yes, you should be able to use a CUDA10.2 docker container, as its driver requirement would be met by the newer CUDA11 driver. I don’t know what a Google machine image is and how hard it would be to build it. You could reuse theDockerfilefrom the PyTorch repository. Also, did you try to install …
Taewoo_Suh
I am trying to run a depth map super resolution model on Google Colab.However, when I run the model, none of my weights update at all, despite the loss being computed properly and all of the layers getting gradients.I have compared each of the model’s named parameters before and after the optimizer.step() function, and...
ptrblck
Yes, you could do this and post the executable code snippet here in case you get stuck. Your current code is not execuable, i.e. I cannot just copy-paste it, run it, and reproduce the issue, which would be possible if you use random tensors and post the missing parts of the code.
DanteTemplar
Do I want to apply transformations to augment data inside theCustomDataloaderclass in Pytorch, or should I do it in theCustomDatasetclass? I would be grateful if you could show an example of how to use it correctly.
ptrblck
You would usually create a custom Dataset and would not change anything in the DataLoader.This tutorialshows how to create a custom Dataset and how to apply the transformations in the __getitem__ method.
Rhett_Ying
Hi,I’d like to obtain the underlying cudaStream_t pointer from torch.cuda.Stream().cuda_stream in python, then pass such obtained pointer into my cpp code which does not depend on torch. I’d like to use such pointer to call cudaStreamSynchronize(ptr).Is this possible and safe to use like this? just reinterpret_cast<cud...
ptrblck
Yes, I believe you can create the pointer via: cuda_stream = torch.cuda.Stream().cuda_stream ctypes.c_void_p(cuda_stream)
MingSun-Tse
Hi, I run the following code for testing my model on a single GPU:model.eval() for i, x in enumerate(test_inputs): t0 = time.time() with torch.no_grad(): y = model(x) print(f'forward time: {time.time() - t0:.4f}s')The model is a simple MLP with 11 layers,#neuronsin each layer is 1024. Inputs is a te...
ptrblck
It’s not an “issue”, but just how asynchronous execution works. The wrong timings are created since the CPU can launch the CUDA kernels and continue executing the host code until a synchronization is needed. In the meantime the GPU is working in the background. If you thus start the timer, launch …
ljmzlh
Say i have a float tensor A with dim[n][n], and 2 int tensor X,Y with dim[N].each value in X,Y is a int between [0,n-1]now i want to create a tensor B with dim[N,N], satisfying B[i][j]=A[X[i]][Y[j]]help me, plz
ptrblck
Yes, this should work: batch_size, N = 4, 5 A = torch.randn(batch_size, N, N) x, y = torch.randint(0, N, (batch_size, N)), torch.randint(0, N, (batch_size, N)) B = torch.zeros(batch_size, N, N) # loop approach for b in range(batch_size): B[b]=A[b,x[b].unsqueeze(1),y[b]] # avoiding loops C =…
jagandecapri
ProblemGiven a dataset consisting of 48-hour sequence of hospital records and a binary target determining whether the patient survives or not, when the model is given a test sequence of 48 hours record, it needs to predict whether the patient survives or not.DataI have constructed a dummy dataset as following:input_ = ...
ptrblck
I assume you want to index the last time step in this line of code: which is wrong, since you are using batch_first=True and according to thedocsthe output shape would be [batch_size, seq_len, num_directions * hidden_size], so you might want to use self.fc(lstm_out[:, -1]) instead.
JanoschMenke
Hi Guys,I am trying to find a solution, I am trying to perform a regression on some images.How would I go about adapting theImageFolderorDatasetFolderto read in the numeric values rather than the classes.I was thinking to just include the target value in the name of the image
ptrblck
The best approach would be to create a custom Dataset as describedhereand implement the logic to create the target (e.g. by reading them from the image names etc.) manually. ImageFolder uses the folder structure to create the class indices, so it wouldn’t be a good fit for your use case (changing…
pytorching
My code works when disabletorch.cuda.amp.autocast.But when I enabletorch.cuda.amp.autocast, I found that the normalization step overflows (float16)x = x - x.mean(), wherex.shape = [5665, 48]andx.mean()returnsnan.Is there any way to solve this problem?
ptrblck
No, that’s not the case as seen in my example, as I’m already using the max. float16 values and they are not accumulating to Inf (internally float32 will be used so the overflow will not happen). Thanks for the new link as I was able to download the data. Your input data already contains Inf val…
111555
class CWT(nn.Module): def __init__( self, widths, wavelet="ricker", channels=1, filter_len=2000, ): """PyTorch implementation of a continuous wavelet transform. Args: widths (iterable): The wavelet scales to use, e.g. np.arange(1, 33) ...
ptrblck
The error message indicates that the str argument is not recognized for padding in conv2d, so you might need to update to PyTorch 1.9.0 to be able to use this argument type.
111555
========== fold: 0 training ==================== fold: 0 training ==========CQT kernels created, time used = 0.0120 secondsCQT kernels created, time used = 0.0118 secondsDownloading: “https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/tf_efficientnet_b7_ns-1dbc32de.pth” to /root/.cache/tor...
ptrblck
The error message indicates that you are trying to torch.stack tensors with a different shape, which is not possible and you would need to make sure all tensors have the same shape. Your code is not really readable, but it seems the DataLoader throws this error in its collate_fn, which would indica…
ArshadIram
def __init__(self): super(CNNLenet, self).__init__() self.conv1 = nn. Sequential( nn.Conv2d(1,16, 5,1,2), nn.ReLU(), nn.MaxPool2d(2) ) self.conv2 = nn.Sequential( ...
ptrblck
The forward method of your model returns a tuple via: return output, x # return x for visualization which creates the issue in loss = criterion(outputs, labels). I assume you want to use output to calculate the loss, so use: output, x = model(inputs) loss = criterion(output, l…
Asa-Nisi-Masa
Hi. I have the following problem. Suppose I have a tensor M of shape (N, 5) and a vector v of size (N).I am looking for a vectorized solution that would tell me if the nth row of M contains the nth element of v. Example:M = torch.tensor([ [0, 1, 2, 3, 4], [7, 5, 3, 4, 8], [0, 1, 9, 7, 5], [1, 4, 7, 2, 5...
ptrblck
You could unsqueeze v compare the tensors directly (v will be broadcasted) and then check the columns for any match: print((M == v.unsqueeze(1)).any(1)) > tensor([ True, True, False, False])
rrm39
I am trying to create a script with nested neural nets, and I’m wondering how to ensure that the losses for each net are propagated to the right place.As an overall structure to my code: I define an autoencoder net A, then train it for 100 epochs. Every 10 epochs, I evaluate the partially trained autoencoder net A on a...
ptrblck
This would be the case if you pass the output of netA to netB directly since both models are treated as any other nn.Module (e.g. nn.Conv2d). If you want to train netB alone without calculating the gradients in netA and updating its parameters, you can detach netA’s output via: out = netA(input) …
edshkim98
Hi, I am curious about calculating model size (MB) for NN in pytorch.Is it equivalent to the size of the file from torch.save(model.state_dict(),‘example.pth’)?Please refer to the image below from PointNet++image1222×220 30.1 KB
ptrblck
I wouldn’t depend on the stored size, as the file might be compressed. Instead you could calculate the number of parameters and buffers, multiply them with the element size and accumulate these numbers as seen here: model = models.resnet18() param_size = 0 for param in model.parameters(): para…
ptrblck
Alexander_Soare:I know this supposedly works for people with CUDA 11.1 (while I’m on 11.0) but before I ruin my life by trying to upgrade my CUDA I thought I’d check here to make sure I’m not missing anything else.Your local CUDA toolkit won’t be used unless you are building PyTorch from source or a custom CUDA extensi...
ptrblck
You have most likely another PyTorch installation with CUDA10.2 in your current environment, which conflicts with the new one. Try to either uninstall all source builds, pip wheels, and conda binaries in the current environment or create a new virtual environment and reinstall PyTorch again.
pytorchnewb
Hi, what’s the idiomatic PyTorch way of putting tensor fields on custom models on the GPU? An example should clarify what I’m asking.Say I have a class like this:class MyModel(nn.Module): def __init__(self): # ... self.my_tensor = torch.rand(...) def forward(self, x): # ... out = out + self.my_tens...
ptrblck
All nn.Parameters and buffers (registered via self.register_buffer) will automatically be pushed to the specified device when calling model.to(device). The difference would be that the former are trainable (requires_grad is set to True by default) while the latter do not. In case you don’t want to s…
Lost_Wanderer
Hello PyTorch users,I have been trying to solve Exercise 3, Chapter 8.5 from Dive into Deep Learning book. I got stuck on that exercise and I was hoping you can help me. I will explain the exercise below.Exercise goes as follows:Modify the prediction function such as to use sampling rather than picking the most likely ...
ptrblck
Based on the error message you are running into a device assert so you could either run the script via CUDA_LAUNCH_BLOCKING=1 python script.py args from the terminal to isolate the failing operation or run it on the CPU.
Superklez
As the title says, what’s the difference when settinginplace = Trueinnn.ReLUandnn.Dropout? Would it affect training in some way?Edit: If I were to usenn.Conv2dornn.Dropoutinnn.Sequential, it wold be better to useinplace=True, correct?Edit 2: I meantnn.ReLU, notnn.Conv2d.
ptrblck
nn.Conv2d wouldn’t have the inplace argument (at least not in the torch.nn.Conv2d definition). The inplace argumen in e.g. nn.Dropout layers (or other functions) will apply the method on the input “inplace”, i.e directly on the values in the same memory locations without creating a new output. Thi…
111558
There is a bug when I run total_loss.backward() in my main.pyWhat can I do to fix the bug?I do not use any -= or += but I still got thisthis is my codedef forward(self): point_cls = torch.reshape(self.point_cls, (4, 4096, 2)) point_regression = torch.reshape(self.point_regression, (4, 4096, 2)) ...
ptrblck
I guess this line of code: l2[:, pn] = 0.05 * l2[:, pn] - point_cls[b, pn, 1] might be causing the issue, as you are assigning the new values inplace to l2. As a workaround you could append the results to a new list and create the tensor afterwards.
Mona_Jalal
I am confused as to why we want to feed an image to a set of stacked resnet blocks versus feeding it to a bunch of convolutional blocks as we do so traditionally?Also, how should we stack resnet blocks to each other? Is there any code sample or paper that does this?I drew this diagram for illustration:Screen Shot 2021-...
ptrblck
If this model is taken from another research paper, I would expect a definition of the “ResNet Block”, but my best guess would be e.g.: model = models.resnet18() print(model.layer1) > Sequential( (0): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=…
Bled_Clement
I have the following dataloader below:def load_dataset(size_batch, size): data_path = "/home/bledc/dataset/test_set/crops_BSD" transformations = transforms.Compose([ transforms.Grayscale(num_output_channels=1), transforms.ToTensor() ]) train_dataset = datasets.ImageFolder( r...
ptrblck
load_dataset would be a function, which returns the DataLoader not a class. I would claim it depends on your coding style and wrapping the DataLoader creation into a function might allow you to move it into another file more easily. This class definition would be used to create a custom Dataset …
Sarmad_GTU
Hi allI am working on a semantic segmentation problem using satellite imageI want to ask about data augmentation (offline or on the fly ) when I apply it like adding noise or change the contrast so we apply it to both image and mask but in this case, the values of the mask pixels (pixel-wise class value ) changed (ex: ...
ptrblck
Spatial transformations applied on the input image should also be applied on the mask tensor to make sure that the input pixel location still correspond to the mask (e.g. rotaions, resizing etc.). Besides that you should treat the mask as a classification target and should not change its values.
adizhol
What kind of padding does pytorch use for torch.nn.functional.interpolation, and how to control it?For example, how to set reflectace padding or zero-padding?
ptrblck
I don’t think that F.interpolate uses any padding, as it should create the indices corresponding to the desired output shape inside the valid input size. If you want to pad the input manually, you could use F.pad, where mode indicates the desired padding mode.