user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
deadwalker7539
I am trying to use resnet18 and densenet121 as the pretrained models and have added 1 FC layer at the end of each network two change dimensions to 512 of both network and then have concatenated the outputs and passed to two final FC layers.this can be seen here:class classifier(nn.Module): def __init__(self,num_class...
ptrblck
Your current implementation misses the relu as well as adaptive pooling layer from the DenseNet implementation as usedhere, which would create a tensor of [batch_size, 1024, 7, 7] for the output of self.densenet.features. Also, you might want to concatenate the activation tensors in dim1 (feature …
alameer
I am using torchvision.transforms to transforms a dataset. I am wondering what other methods available to do similar data transforms:transforms = Compose([RandomChoice([functional.hflip,functional.vflip])]) dataset_train.duplicate_and_transform(transforms)
ptrblck
Thetorchvision.transforms docsgive you an good overview for all available transformations.
talhak
I’m trying to replicatethe tutorial posted on Mediumthat demonstrates the utilization of an LSTM network for sentiment analysis. During the execution via PyTorch, getting this error:RuntimeError: CUDA error: device-side assert triggered. Could you please explain me what is the reason for this error?Full error stacktrac...
ptrblck
Is your code working fine on the CPU? If so, could you rerun the code with CUDA_LAUNCH_BLOCKING=1 python script.py args and post the stack trace here, please?
omrjml
Is there a way to re-permute the indices for SubsetRandomSampler at each epoch without re-initialising the DataLoader at each epoch? I am loading a large dataset so do not want to reload it at every epoch.my dataloader function is:def train_dataloader(args): train_dataset_file = "{0}/train_data_{1}.hdf5".format(arg...
ptrblck
Do you want to shuffle the passed indices in the SubsetRandomSampler or would you like to shuffle the global indices again and create new subsets? In the former case the indices would already be reshuffled in each epoch as seen here: class MyDataset(Dataset): def __init__(self): pass …
GB_K
Hello.I saw the codecudnn.fastest = Truein the repo.https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch.What is the meaning of cudnn.fastest?Thank you for your answer in advance.
ptrblck
It shouldn’t have any effect, as torch.backends.cudnn.fastest is not implemented. In your IDE orhereyou can see, that benchmark, deterministic, and enabled are known flags. benchmark = True will use cudnnFind to profile all available Kernels and select the fastest one. The repository seems to o…
LeErnst
Hello guys,i am trying to access an indexed tensor in the following way:x = tr.tensor([True]*10, dtype=tr.bool) y = tr.tensor([True]*10, dtype=tr.bool) x[3] = False y[~x] = False # works fine x[y][3] = False # does not change the tensor x, but why?Obviously the second indexingx[y][3]creates a copy of the tensor x...
ptrblck
You could try to replace the sequential indexing with x[y.nonzero()[3]] = False which should yield the desired result based on your example.
Saifeddine_Barkia
Hello, I have trained my model using this code!python train_bap.py train\ --model-name inception \ --batch-size 12 \ --dataset car \ --image-size 512 \ --input-size 448 \ --checkpoint-path checkpoint/car \ --optim sgd \ --scheduler step \ --lr 0.001 \ --momentum 0.9 \ --weigh...
ptrblck
This error will be raised, if you’ve stored the state_dict from the nn.DataParallel model and are now trying to load it to a plain model. You could usethis approachto remove the .module from the keys or alternatively store the state_dict via: sd = model.module.state_dict() torch.save(sd, PATH)
iamharshit
Hi everyone,I am making a CNN and I need to load weights from a preexisting .npy file.Up until now I have made this function to do it.def load_weights(): params = net.state_dict() pathtoweights = os.path.join(os.path.abspath("."), "saved_models", "numpy", "weights.npy") pretrained_weights = np.load(pathtowe...
ptrblck
Your approach should work, as seen in this example: lin = nn.Linear(1, 1) sd = lin.state_dict() print(sd) > OrderedDict([('weight', tensor([[-0.5414]])), ('bias', tensor([0.8279]))]) sd['weight'].copy_(torch.tensor([[1.]])) print(lin.state_dict()) > OrderedDict([('weight', tensor([[1.]])), ('bias'…
ML0401
Hello folks,I am a little bit confused about the weight initializations. As I am training my network (resnet18) from scratch, I like to initialize the weights by an uniform distribution, with the following function:def init_weights(m): if isinstance(m, nn.Conv2d): nn.init.kaiming_uniform_(m.weight, nonlinea...
ptrblck
Some layers such as batchnorms and the bias parameter of other layers cannot be used in init methods, which require a multi-dimensional parameter. The weight of nn.BatchNorm2d is by default now initialized with ones, while the bias with zeros, which seems to be the recommended way now. Pooling lay…
localh
I am wondering what is the right way to use a sampler likeWeightedRandomSamplerfor imbalanced classification problems.Specifically, I am unclear as to whether I only use sampling during:TrainingTraining + ValidationTraining + Validation + Testing (whereby each gets its own sampler to capture the distribution in its res...
ptrblck
I think the common use case would be to use it during the training only. The validation dataset should act as a good proxy for the final model performance on the unseen test data. So I would try to keep the data distribution of the validation and test datasets as close as possible. Since your test…
Mayank_Jha
Hi there,I want to train a NN using the output of another already trained NN. I think I am not able to do it right. new to pytorch. kindly help.In the code below, the already trained NN is called “model” (hence, usd in eval() mode), and the network to be trained is “modelFCNN” (a fully connected NN).I have conctenated...
ptrblck
Thanks for the code. Using your code and just passing some random values into the models, I can get valid gradients in both models: model = Network(2, 2) modelFCNN = NetworkFCNN(2, 1) criterion1 = torch.nn.MSELoss() data = torch.randn(1, 2) y_pred_ref = modelFCNN(data) # concatenate the tens…
VahidZarghami
Hello guysHere is my local binary pattern function:def lbp(x):imgUMat = np.float32(x) gray = cv2.cvtColor(imgUMat, cv2.COLOR_RGB2GRAY) radius = 2 n_points = 8 * radius METHOD = 'uniform' lbp = local_binary_pattern(gray, n_points, radius, METHOD) lbp = torch.from_numpy(lbp).long() return lbpHere I call lbp ...
ptrblck
I can’t reproduce this issue, and this code works fine on my machine: def lbp_transform(x): radius = 2 n_points = 8 * radius METHOD = 'uniform' imgUMat = np.float32(x) gray = cv2.cvtColor(imgUMat, cv2.COLOR_RGB2GRAY) lbp = local_binary_pattern(gray, n_points, radius, METHOD)…
fgauthier
I have a dataset of around 200 images. However, the format of my image is not standard because it has 6 dimensions.One image would look like this (before being cast to tensor and being stack in a 3d Tensor):[img0, img1, img2, img3, img4, img5]. (They are all grayscale PIL Image )However my dataset is quite small and I ...
ptrblck
You could use the functional API of torchvision.transforms as given inthis example. This would make sure to apply the same “random” transformation on all image slices. Let me know, if this would work for you.
ML0401
Hello,to save memory I am trying to train a resnet18 model in half precision. Therefore, I converted my inputs and my model. I also changed the BachNorm2d layers back to normal floating tensors with the following lines:resnet18.half() for layer in resnet18.modules(): if isinstance(layer, nn.BatchNorm2d): la...
ptrblck
Calling model.half() might work, but can easily create overflows and thus NaNs. We recommend to use theautomatic mixed-precision training, which takes care of these issues and also stabilizes the training using loss scaling. You can use it in the nightly binaries or by building PyTorch from sourc…
Sudarshan_Babu
class ConditionLayer(nn.Module): def __init__(self, layer_template, layer_name): super(ConditionLayer, self).__init__() self.layer_template = layer_template self.layer_name = layer_name self.set_params(*self.layer_template) def set_params(self, cout, cin=None, height= None, widt...
ptrblck
Python lists and dicts won’t properly register submodules and parameters, so you should use nn.ModuleList, nn.ModuleDict, nn.ParameterList, or nn.ParameterDict` instead.
Imran_Rashid1
I have seen some code where they use bothmodel.model_state_dict()andmodel.generator_state_dict(). I know that model_state_dict gives you the weights of the model neural network but I am unsure about the latter (generator_state_dict) as I cannot find any documentation on this. Can anyone shed some light on to this or at...
ptrblck
Neither of these two methods is a built-in method of nn.Module, so you would need to look into the custom model definition and search for these functions. nn.Module provides the .state_dict() method, which will return all registered parameters and buffers of this model.
mastacash
Hi! I am new to pytorch and I am trying to recreate the same simple neural net model as scikit-learn.neural_network.Sklearn modelmlp = MLPRegressor() mlp.fit(x,y) _out: MLPRegressor(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,_ _ beta_2=0.999, early_stopping=False, epsilon=1e-08,_ _ hidd...
ptrblck
You have a small mistake in your model, i.e. nn.MSELoss expects the model output and the target to have the same shape. If that’s not the case the tensors will be broadcasted if possible. In your case tr_y is has only one dimension ([100]), while pred has two ([100, 1]). Change the loss to loss = …
AnupKumarGupta
Hi. I am trying to perform an adversarial attack on a model, where I have to calculate gradients of loss over inputs, something like this:model.eval() for prediction != target: prediction = model(input) loss = criterion(prediction, target) loss.backward() input = input - k * (input.grad())But, follo...
ptrblck
Could you post a (minimal) model definition including all necessary shapes and arguments to reproduce this issue? The predictions shouldn’t be affected in any way. The GPU will still be used, if you disable cudnn. As the call suggests cudnn won’t be used and the native CUDA implementations wil…
harshini_sewani
I am currently using a hybrid model using pytorch by hybrid I mean Autoencoder and CNN and here is my model :convnet((fc_encoder): Sequential((0): Linear(in_features=9950, out_features=200, bias=True))(decoder): Sequential((0): Linear(in_features=200, out_features=9950, bias=True))(con1): Conv1d(1, 2, kernel_size=(5,),...
ptrblck
If I’m not mistaken, you are passing the inputs first to the Autoencoder and pass this output to the CNN. The code for this looks generally alright and you wouldn’t need to use two losses, if your complete model only returns a single output. Note that the last linear layers are used without any no…
ucals
I have a tensor like this example (x):tensor([[[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]])Using a tensor mask like this:tensor([[0, 1, 0, 0], [0, 0, 1, 0], [1, 1, 0, 0]])I want to gather the ...
ptrblck
You could create a bool mask and index the input tensor as: x = torch.tensor([[[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]) mask = torch…
Giannhs_Vlasso
tldr:I want to transfer trained weights from a conv layer like:self.conv_init = nn.Conv1d(num_in_channels, num_hidden, 1)to a new one with more input channels (initializing the rest with 0’s or according to some initialization scheme) - and everything else remaining same, like eg. :self.conv_init = nn.Conv1d(num_in_cha...
ptrblck
You could load the state_dict before any manipulation of the first conv layer to make sure all other layers are properly restored. Once this is done, you could replace the first conv layer with a new one and reassign the parameters manually. This code snippet give you an example: ref = nn.Conv2d(3…
bendangnuksung
Is there a way to find if a model is a half-precision or full precision model?
ptrblck
By default PyTorch will initialize all tensors and parameters with “single precision”, i.e. float32. If you are not using the mixed precision training utilities or are calling .half(), to(torch.float16)etc. in your code, the model should stay in FP32. To check it, you could iterate all parameters …
chenjesu
I have tried both MSE and KLDiv losses, and everything I can think of / search for online.The model always starts with a real number output and during training immediately gravitates toward 0 or 1, even though most of the target values are fractional numbers.Here is my model (apologies for any typos, I am typing this o...
ptrblck
I would guess this is the “nature” of the sigmoid activation, as the gradients will have the highest value at f(x=0) = 0.5, which would push the output towards the limits. Usually you would use this activation for a binary or multi-label classification use case. If you are dealing with a regressio…
satanarmy
After monitoring CPU RAM usage, I find that RAM usage increases for all epoch. During an epoch run, memory keeps constantly increasing. RAM isn’t freed after epoch ends. Usage keeps increasing when new epoch comes. Hence, memory usage doesn’t become constant after running first epoch as it should have. Eventually after...
ptrblck
It seems you are storing the complete computation graph in this line of code: epoch_loss += l1_loss If you want to use epoch_loss for printing/debugging purposes (i.e. without wanting to call epoch_loss.backward() in the future), you should detach the l1_loss before accumulating it via: epoch_los…
bPangolin
When I am doing gradient accumulation, the BatchNorm2d layers are not properly accumulated, right? Though, I don’t entirely understand exactly what is going on. The running mean and std deviation are reset on each consecutive batch, correct?If the BatchNorm2d layers are not properly accumulated, does that also disrupt ...
ptrblck
No idea at the moment and you could use torch.autograd.set_detect_anomaly(True) at the beginning of the script to get a stack trace, which should hopefully point to the first NaN creation. momentum is an argument in all batchnorm layers, which you can directly pass to them: nn.BatchNorm2d(num_fe…
ptnewbie
I have two models defined as:model1 = Net1()model2 = Net2()opt1 = Adam(model1.parameters(),…)opt2 = Adam(model2.parameters(),…)When training, the model2 uses the output of model1 as input, and the two models have a different loss. I tried to train them:output1 = model1(data)output2 = model2(output1)loss1 = Loss(output1...
ptrblck
The code looks generally alright. If you don’t want loss2.backward() to calculate gradients in model1, you could detach output1 before passing it to model2 via: output2 = model2(output1.detach()) This will make sure to cut the computation graph at this point.
ptnewbie
I want to compute a block-based std on the image, but I don’t know which way is efficient and whether the gradient of std can be backpropagated.For example, I have images: 10x1x20x20 (NCHW), I want to compute the std within 3x3 window on the images and compute each std in this 3x3 matrix and do backpropagation. Can any...
ptrblck
You could useF.unfoldto create these 3x3 windows from the image and compute the std for each of these windows. You should be able to backpropagate through torch.std.
Aiman_Mutasem-bellh
Dear@AllI’m trying to apply Transformer tutorial fromHarvardnlp, I have 4 GPUs server and, I got CUDA error: out of memory for 512 batch size.# For data loading. from torchtext import data, datasets if True: BOS_WORD = '<s>' EOS_WORD = '</s>' BLANK_WORD = "<blank>" SRC = data.Field(tokenize=bpemb_ar.e...
ptrblck
Try to reduce the batch size and check which batch size would fit and how much memory is used. Your GPUs might have not enough memory for the code you are using or are you using exactly the setup the authors were also using?
Hwarang_Kim
Im trying to run U-Net. My data set has 3 classes (2 classes + background) so I made the mask which contains class indices for each pixel like [[0,1,2,1,2,0,...,1],[0,1,1,0,0,...,1]...[0,1,1,0,1,...,2]]. The mask shape is (512,512), and class indices are 0, 1, 2 (0 for background). But I wonder how the model works! My ...
ptrblck
You should use nn.CrossEntropyLoss and can have a look at thedocsto see how the loss formula is implemented. I would recommend to skip the spatial dimensions for now and just take a look at the standard multi-class classification use case, where the output has the shape [batch_size, nb_classes] a…
Capo_Mestre
Hello. There are many examples of neural networks for MNIST hand-written digits classification problem, where the output is a 10-element softmax-vector with one maximum value corresponding to the prediction. This is the case where a label for a particular data-sample is just a number (one-element label, that can take v...
ptrblck
The model output wouldn’t necessarily need to change for the mentioned use cases, but the loss functions and targets. E.g. if you would like to predict N floating point values, your model could output a tensor in the shape [batch_size, N] and you could use e.g. nn.MSELoss for this regression task. …
Zhuolin_Yang
Hi all, I was trying to distribute several models (say 8) into 8 gpu devices. For each model models[i], I calculated the sum of output as follows:for i in range(args.num_models): input_var = input_var.to("cuda:%d" % (i)) target_var = target_var.to("cuda:%d" % (i)) criterion = nn.CrossEntropyLoss().to("cuda:...
ptrblck
Try to push the losses to the same device before accumulating them. Also, which PyTorch version are you using, as I cannot reproduce this issue locally (and also thought it would be fixed by now).
natelang
I am currently working on a transfer learning problem with a resnet-50. Below is my code for the training. It seems to be working, but the accuracy goes from 0 to 1 in second batch and then stays at 1 for the remaining batches and epochs.import time epochs = 3 device = torch.device("cuda:0") # Define Optimizer and Los...
ptrblck
There seem to be some issues: Could you move the data to another folder, without the hidden .ipynb_checkpoints folder? Currently this folder seems to be recognized as class0, which is most likely wrong. It also seems that you are dealing with a single class folder called 1. If that’s the case even…
seyeeet
I want to calculate the differences between adjacent elements of a tensorXin 1 D.e.g if my tensor has a dimension ofBxCwhereBis batch size andCis a channel.functiondiff(X)should outputt[X(2)-X(1) X(3)-X(2) ... X(c)-X(c-1)].How can I do it in pytorch?
ptrblck
This code should work to compute the difference in the C dimension: B, C = 10, 5 x = torch.arange(B * C).view(B, C) result = x[:, 1:] - x[:, :-1]
Imen
def train(net, data, epochs=10, n_seqs=10, n_steps=50, lr=0.001, clip=5, val_frac=0.1, device=torch.device(‘cpu’),name=‘checkpoint’, early_stop=True, plot=False):# initialize the process group """ Training loop. """ net.train() # switch into training mode opt = torch.optim.Adam(net.parameters(), lr=lr) # initialize opt...
ptrblck
I guess get_batches might not return anything, so that the complete training and thus the loss calculation will be skipped and will later raise this error in: train_history['loss'].append(loss.item())
bfeeny
Regarding ReduceLROnPlateau():optim = torch.optim.AdamW(model.parameters(), lr=param['lr'], amsgrad=True) scheduler = ReduceLROnPlateau(optimizer=optim, mode='max', patience=1, verbose=True, factor=0.5) val_roc = torch.tensor(15.0, device=device) scheduler.step(val_roc) scheduler.get_last_lr()-------------------------...
ptrblck
You could create a feature request for get_last_lr for this scheduler and meanwhile use the 'lr' attribute of the parameter group of the optimizer directly: print(optimizer.param_groups[0]['lr'])
alameer
I would like to split images using Open CV then feed to the by PyTorch model to count object in each image. I am getting the following error message when running the code: TypeError: pic should be PIL Image or ndarray. Got <class ‘bool’>import os import numpy as np import torch from PIL import Image from torch.utils.d...
ptrblck
cv2.imwrite will return a bool value to indicate, if the write process was successful or not, which you are reassigning to sample before passing to self.transform. Remove the assignment and rerun the code.
vishnu_vardhan1
Hi, I am using Cats and Dogs dataset by microsoft. The dataset consists of 25,000 images where all the images of cats contain in cats folder and all the images of dogs contain in the Dogs folder.However, I split the data into train,valid and test data as given below:data_transf = transforms.Compose([transforms.CenterCr...
ptrblck
You could create multiple ImageFolders for training, validation, and testing, and pass the corresponding transformation to each of these. Once these datasets are created, you could reuse the SubsetRandomSampler approach and create the DataLoaders. Since ImageFolder will load the data lazily, you s…
Manoel
I’m trying to compute the mean and the std of my dataset. I foundthis topicand implemented some ideas. However, when I applied the normalization on the dataset and checked the values. Then I found out that most values weren’t on the range[-1, 1], some greater than 1 and 2.Is it normal? Or should it be best just use the...
ptrblck
That’s expected, since Normalize calculates the standard scores of the input (also known as z-scores) by subtracting the mean and dividing by the standard deviation.This Wikipedia articleexplains it further.
shangguan91
i want to load data by def get_data. First code is a example for getting data and transfrom if data is Gotik. however, i want to def get data and return data and labels, it wont work.train_files = os.listdir('/content/drive/My Drive/Churches_new/Train') data_list = [] for f in files: if f[-3:] == "obj": d =...
ptrblck
What is currently not working? Do you get any errors are unexpected results?
ML0401
Sorry, for bothering you again.I am trying to train a resnet18 model to classify images into three different classes. Therefore, I wrote a class train_one_epoch. I would like to calculate the accuracy of the training during one epoch, so I wrote a class accuracy, too. I know, that this kind of accuracy class only siuts...
ptrblck
Changing the out_features of an already initialized module won’t work: resnet18.fc.out_features = 3 since the internal parameters were already created. You should create a new nn.Linear module and assign it to the .fc attribute: model = models.resnet18() mdoel.fc = nn.Linear(512, 3)
Ahmed_Abdelaziz
I have one scores tensor with gradients attached to it and I have a corresponding lengths tensor wheresum(lengths) = len(scores)I would like to scatter these scores in a matrix in a diagonal way such thatlength_so_far = 0 for i in lengths: adj[i][length_so_far:length_so_far+lengths[i]] = scores[length_so_far:length...
ptrblck
This should work, if I understand the use case correctly: lengths = torch.tensor([2, 3, 4, 5]) scores = torch.arange(1, lengths.sum()+1).float() idx = torch.repeat_interleave(torch.arange(len(lengths)), lengths) out = torch.zeros(len(lengths), len(scores)) out.scatter_(0, idx.unsqueeze(0), scores…
swpd
Hi,I’m confused that torch.nn.ConvTranspose1d is extremely slow when running on GPU, even slower than CPU.Code to reproduce:$ cat test_trans_conv.pyimport torch x = torch.randn(1, 64, 40000) if torch.cuda.is_available(): x = x.cuda() trans_conv = torch.nn.ConvTranspose1d(64, 32, kernel_size=4, stride=2, padding=1) ...
ptrblck
No, there is no user facing API to do so. Yes, ran it with the default setup first and compared it to benchmark mode, which didn’t yield a speedup. It’s a cudnn “data gradient” kernel, which computes the gradient for the input activation.
Santhosh_Kumar1
Recently, I installed a ubuntu 20.04 on my system. Since it was a fresh install I decided to upgrade all the software to the latest version. So, InstalledNividia driver 450.51.05version andCUDA 11.0version. To my surprise, Pytorch for CUDA 11 has not yet been rolled out.My question is, should I downgrade the CUDA packa...
ptrblck
As explainedhere, the binaries are not built yet with CUDA11. However, the initial CUDA11 enablement PRs are already merged, so that you could install from source using CUDA11. If you want to use the binaries, you would have to stick to 10.2 for now.
karl7
I use BCEWithLogitsLoss for multi-label and multi-task learning, but when training, after 2 epochs, everythin will not change…only in the 1st and 2nd epoch, the traing acc increased, even though the validation acc, loss not changed.From the 3rd epoch, everything will not change,when i use BCEWithLogitsLoss, I have read...
ptrblck
It seems you are working on a multi-label classification with 40 labels (based on the number of loss functions you are creating). Inside the model you are reusing the same nn.Sequential block (self.fc) for all tasks. Is this intended or would you like to initialize own layers for each task?
numpee
Hi all,Is there a way normalize (L2) the weights of a convolution kernel before performing the convolution?For a fully connected layer, I’d go about doing something like:# __init__() weights = nn.Parameter(torch.Tensor(in_size, out_size)) # forward forward(x): w = F.normalize(weights) out = torch.mm(x, w) ...
ptrblck
You could use the same approach, but call F.conv2d instead of torch.mm to perform a convolution. Also, the input and weight shapes would be different, since F.conv2d expects an input of [batch_size, channels, height, width] and a weight of [out_channels, in_channels, height, width].
samin_hamidi
I am training and testing an autoencoder. I run the exact same code in Jupyter notebooks and also in Googlecolab. I have these settings:np.random.seed(0)random.seed(0)torch.manual_seed(0)torch.cuda.manual_seed(0)torch.cuda.manual_seed_all(0)torch.backends.cudnn.enabled = Falsetorch.backends.cudnn.benchmark = Falsetorch...
ptrblck
Not necessarily, if different hardware and potentially software versions (CUDA, PyTorch) are used. You could run some tests and see, if you would be getting the same random numbers on both platforms in the first place.
SU801T
Hi,I have defined a pretrained resnet50 for data parallelism using multiple classes and use nn.CrossEntropyLoss() .model = models.resnet50(pretrained=True) model = torch.nn.DataParallel(model) for p in model.parameters(): p.requires_grad = False num_ftrs = model.module.fc.in_features model.module.fc = nn.Linear(n...
ptrblck
Thedocswill give you some information about these loss functions as well as small code snippets. For a binary classification, you could either use nn.BCE(WithLogits)Loss and a single output unit or nn.CrossEntropyLoss and two outputs. Usually nn.CrossEntropyLoss is used for a multi-class classif…
uertenli
Hi!I am working on making deep model computations in parallel to achieve a faster running model that is supposed work fast in.eval()mode. I tried this tutorial:https://pytorch.org/tutorials/intermediate/model_parallel_tutorial.htmlI ran this code presented in the tutorial and I could obtain faster working models throug...
ptrblck
You could see the timing relatively between the CPU and GPU workload. E.g. if the GPU workload is small (due to a small model), you might see the overhead of the kernel launches as well as other CPU operations such as list(...), torch.stack(...), data loading, etc. To isolate the actual runtime of…
Kale-ab_Tessera
I have a ModuleList, with Linear and Batchnorm layers. I wanted to call namednamed_parameters()and only get the grads of the linear layers as follows:for name, param in model.named_parameters(): if(isinstance(param, nn.Linear)): grads[name] = param.gradThis doesn’t work sincety...
ptrblck
You could iterate model.named_modules() and check the returned module to be an nn.Linear instance: for name, module in model.named_modules(): if isinstance(module, nn.Linear): print(name, module.weight.grad)
joehays
Hello,I have 2 Quadro K4200 nvidia GPUs. They have a compute capability (CC) of 3.0. I’ve found many posting that indicate that I need to build PyTorch from source because a CC of 3.0 is too old. I have now built from source but am getting this common error:RuntimeError: CUDA error: no kernel image is available for exe...
ptrblck
I don’t think you would need to modify cpp_extension.py, as it should only be used for custom C++/CUDA extensions, not the base build. Try to build PyTorch via: TORCH_CUDA_ARCH_LIST="3.0" python setup.py install
roy.mustang
I’m quite new to PyTorch. I have a dataset which is an ImageFolder. my dataset contains some folders which are the classes and each folder has some images.I want to split the data into the train_set and test set. but I want to pick 20 percent of each class randomly and put them into test_set. I have the flowing code.da...
ptrblck
You could use sklearn.model_selection.train_test_split with the stratify argument to create the training and testing indices.
satanarmy
When we have alpha channel present in images, reading the data with ImageFolder converts it to RGB. I’m a Pytorch noobie. How would one write custom Datalodaer/Dataset to read images with 4 channels?
ptrblck
ImageFolder uses the pil_loader by default, if accimage is not the used backend and if no other loader was specified. This loader converts the images to RGB as seenhere. To use the RGBA channels, you could write a custom loader (basically just copy-paste the pil_loader and remove the convert call…
Javier_Rodriguez_Pui
Hi everyone, I am trying to do the inverse of a tensor element-wise.like this:sample[i].pow_(-1)Unfortunately, the precision that I am looking for is not achieved although is float64 type.Data example:Having this tensor:tensor([[[[1631., 1635., 1639., …, 4023., 4025., 4027.],[1629., 1634., 1638., …, 4020., 4022., 402...
ptrblck
Your output might just be cropped and you could increase the printed decimals via torch.set_printoptions(precision=10).
shangguan91
from torch_geometric.datasets import ShapeNetdataset = ShapeNet(root=‘/tmp/ShapeNet’, categories=[‘Airplane’])dataset[0]Data(pos=[2518, 3], y=[2518])Dear all, i am handling data of point cloud, i want to implement ConvPoint:https://github.com/aboulch/ConvPoint/blob/master/networks/network_classif.pyHowever, there is o...
ptrblck
You could copy-paste the linked model and modify it as you wish. Alternatively you could also use this model as the base class and derive your custom model from it, but it depends on your coding preference I guess.
braindotai
How can I apply transformations like, Resize, CenterCrop, RandomCrop, RandomHorizontalFlip etc… to a read video, of type torch.tensor with four dimensions -> (channels, frames, height, width). (Its okay if I’d have to reshape this…)
ptrblck
You could create custom transformations, which would apply the torchvision.transforms in a loop on each sample (or rewrite the transformations so that they would work on batched inputs). torchvision has some internalvideo transforms. Since the API isn’t finalized, this code might break and shouldn…
ayrts
Hello,When I usetorchvision.datasets.ImageFolderon a large dataset (~120 000 images) with two folders (fake & real), the size of the total dataset pytorch uses is equal to the size of the real folder (exactly 68 850).Since I output a csv file after training, I found that the number of fake images is exactly 30 000 (and...
ptrblck
Could you check the file extensions of all files and make sure that they are using thesupported formats? Also, could you post the folder structure here, please?
Pragya
Hi all,I’m a newbie with NN and PyTorch and trying to implement a small network as shown in the following code. The problem is if I’m calculating Test accuracy at intermediate epochs, my final test accuracy is increasing, compared to if I only estimate it at the last epoch. It looks like maybe there is some test data l...
ptrblck
Thanks for the code. It seems that the additional call of the test method inside the training loop calls into the pseudo-random number generator and thus changes the order of the training data in the next step. This will result in a bit noise during the training, which thus yields a different end …
mercer_Alex
pytorch vision: 1.5.1Only OneCycleLR can’t be import and others are normalAm I writing it wrong ?image1001×123 6.98 KB
ptrblck
Are you getting an error when you execute the import statement or is this just a warning from your IDE? OneCycleLR was added ~11 months ago, so it should be in 1.5.1.
Sudarshan_Babu
I am trying to change the value in my model’s state dict, but even after updating the state dict, the value does not change, any help would be appreciated.sd = model.state_dict() sd['encoder.layer.11.output.LayerNorm._running_mean'] = layer_norm_stats['encoder.layer.11.output.LayerNorm._running_mean'] # Layer norm st...
ptrblck
The values in the model parameters won’t be changed, if you assign a new tensor to the key in the state_dict. You could either load the manipulated state_dict afterwards or change the parameter’s value inplace as shown here: model = nn.Linear(1, 1) print(model.weight) > Parameter containing: tenso…
Megh_Bhalerao
Hi everyone,I have a question with regards to reproducibility of results in PyTorch. In my main file (trainer.pyfile), I am doing the following:torch.cuda.manual_seed(seed_val) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = FalseI am doing this ensure that my results match atleast upto some ...
ptrblck
It should be sufficient to set the seed after the first import of PyTorch. As long as the control flow stays the same (i.e. the calls to the pseudo-random number generator are the same), you should get the same outputs (besides of course the limitations mentioned in thereproducibility docs).
f10w
Hello,I observed in PyTorch’s source code some functions that follow the pattern below (for examplethis one):def my_function(a, b, c, d=None, e=None): if not torch.jit.is_scripting(): tens_ops = (a, b, c) if any([type(t) is not Tensor for t in tens_ops]) and has_torch_function(tens_ops): ...
ptrblck
torch.jit.is_scripting() can be used as a guard for Python-only methods, which are not exportable. Since the JIT cannot export all arbitrary Python objects, you could thus use different “paths” in your code for the Python execution and the scripting of the mdoel. handle_torch_function sounds like …
ChrisLiu2
This is the environment I’m running in:CUDA 10.1Python 3.7Titan XPytorch 1.5.1The network used to work normally, but after I added a method in my model to compute graph normalizations, this error starts to happen.The error tracing with CUDA_LAUNCH_BLOCKING=1 gives:’Traceback (most recent call last):--------------------...
ptrblck
Is your model running fine on the CPU? This should give you a better stack trace than the current one. If it’s running fine of the CPU, could you check, if you might be running out of memory and reduce the batch size if possible, since sometimes library errors might mask an actual OOM issue?
rcshubhadeep
Hello All,This is my first post and I am sorry if either I posting in a wrong place or this post is too trivial. But I can’t really figure out what is going wrong here. I will come to the point. I have a tensor looking like thisX = torch.ones((6, 8)) X[:, 2:6] = 0 X tensor([[1., 1., 0., 0., 0., 0., 1., 1.], [1...
ptrblck
Your manual approach is not reducing the loss in the first call: loss = (Y_hat - Y) ** 2 so loss will have the shape [1, 1, 6, 7] and later you will sum this loss. However, nn.MSELoss uses the reduction='mean' by default, which would yield a lower loss value and thus also gradients with a smaller…
VahidZarghami
Hi I got this error can anyone help me please?UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`. In PyTorch 1.1.0 and later, you should call them in the opposite order: `optimizer.step()` before `lr_scheduler.step()`. Failure to do this will result in PyTorch skipping the first value of the...
ptrblck
As the warning explains, you should call sdcheduler.step() after optimizer.step() was called (starting with PyTorch >= 1.1.0). In your current code you are calling scheduler.step() directly in the first lines of the train_one_epoch method. Move it after the optimizer.step() method and the warning s…
braindotai
How to convert batch of videos containing image sequences, where shape of each batch is -(batch_size, 3, num of images in a video, height of image, width of image)and I want to convert it into -(batch_size, 3 * num of images in a video, height of image, width of image)so its like combining 1st and 2nd dimensions…Also I...
ptrblck
You could use the view operation as: N, C, T, H, W x = torch.randn(B, C, T, H, W] x = x.view(x.size(0), -1, x.size(3), x.size(4))
shangguan91
GitHubrusty1s/pytorch_geometricGeometric Deep Learning Extension Library for PyTorch - rusty1s/pytorch_geometricDear all, i intend to replicated the example by using GCN model for IMDB-Binary. however, i am not able to print the accuracy and epoch loop at the end, some guidance plsLoading data:import argparse import ...
ptrblck
I assume you would like to get the output of the print statement inthese lines of code? It seems cross_validation_with_val_set is never called and instead the run method is executed from points.train_eval, which is undefined in your code.
ChrisLiu2
I have a neural network that needs to compute results sequentially, it reads in an initial state that’s learnable, and calculate step by step results based on last steps’ result. During training, there are no errors. But as I get to 2nd epoch, the time it takes to run backwards() starts to rise unreasonably. 1st epoch ...
ptrblck
You could try to check all tensors for a valid .grad_fn and detach every tensor, which is not needed anymore. If the backward pass yields the slowdown this might indeed point towards a growing computation graph. Do you see an increase in memory usage while you are training the model? Just a wild …
ML0401
Hello,I am new to pytorch and I am trying to import binary files (matlab matrices which are images) to train a standard resnet18 with. What is the best way to do this? Is there a way to import binary files with torchvision.datasets or do I have to write my own dataloader? Is it possible to train the network with these...
ptrblck
You could usescipy.io.loadmatto load the MATLAB files. Once you have loaded them as numpy arrays, you would have to transform them to tensors via torch.from_numpy(). I would recommend to write a custom Dataset as describedherefor this use case.
shangguan91
hallo, i could not install the nearest neighbor library, can not found the library in the folder.The intruction said that i could compile, however there is error as well.GitHubaboulch/ConvPointContribute to aboulch/ConvPoint development by creating an account on GitHub.
ptrblck
Which error message do you get when you try to build the repository? Note that you might get a faster and better answer, if you create an issue in the linked repository, so that the original authors would have a chance to support you.
derJaeger
Hi there,I am not sure how gradient clipping should be used with torch.cuda.amp. Right now, when I include the line clip_grad_norm_(model.parameters(), 12) the loss does not decrease anymore. This is probably just me getting something wrong but I could not find any documentation about hot it should be used.Here is a fu...
ptrblck
You can find the gradient clipping example for torch.cuda.amphere. What is missing in your code is the gradient unscaling before the clipping is applied. Otherwise you would clip the scaled gradients, which could then potentially zero them out during the following unscaling.
naveenreddy61
I am noticing that runtime for loops is very high compared to broadcasting pytorch.Below, I am posting code snippet to explain my point:I am finding the mse for 100,000 random datapoints using for loop vs using broadcasting using cuda.There is big difference in running time ~25s vs ~0.0006s.What explains this big diffe...
ptrblck
The difference between the code snippets seems to be the sequential vs. parallel execution. Each CUDA operation will launch a kernel, which will create some overhead. This overhead of the kernel launch is often not visible, if the actual workload on the GPU is large. However, in your first exampl…
Flint
Okay, but isn’t it odd. I already included the transforms.Resize() in the transforms.Compose() as seen here# define transforms if augment: train_transform = transforms.Compose([ transforms.Resize(img_size), transforms.RandomHorizontalFlip(0.3), transforms.ToTensor(), ...
ptrblck
Note that Resize will behave differently on input images with a different height and width. From thedocs: size ( sequence orint) – Desired output size. If size is a sequence like (h, w), output size will be matched to this. If size is an int, smaller edge of the image will be matched to th…
kaimss
I use single machine with 4 gpus to train my models, and then I save paramaters of the model withtorch.save(aemodel.state_dict(), file). And when I useaemodel.load_state_dict(torch.load(output_path + 'ae.pkl', map_location='cpu'))to load its paramaters, error occurs:Traceback (most recent call last): File "Run.py", l...
ptrblck
This error might be raised, if you were using multiple processes (e.g. via DistributedDataParallel) and didn’t guard the storing of the checkpoint against multiple writers. You could use theImageNet exampleto only use the first process to store the checkpoint.
lisyuan
I found some issue in cuda memory allocation when I follow the tutorial official website guidelinedevice = torch.device("cuda:0") x = torch.ones(2, 2, requires_grad=True, device =device) print(x)In this situation,the memory in gpu:0 is 863MB only when I create a 2 by 2 tensor arrayx.tensor([[1., 1.], [1., 1.]],...
ptrblck
The majority of the mentioned used memory comes from the creation of the CUDA context, which cannot be freed. You should also be able to see this memory usage by creating an empty CUDATensor. The caching allocator will reserve some memory which will be used later and you cannot disable it at the …
ben_mi
Hi everyone! I’m trying to implement the global pair loss function from “Recognition of Action Units in the Wild with Deep Nets and a New Global-Local Loss”.I have to look at all possible pairs of the predictions. If the values in a pair are the same, then g_predictions = 1. If they are different, then g_predictions = ...
ptrblck
Your initialization might be “unlucky”, as I’ve got some valid gradients in a couple of iterations (I also got a full zero gradient output): tensor([[ 0.0000, 0.0000, 0.0000], [ 6.8986, 10.3479, 10.3479], [ 0.0000, 0.0000, 0.0000], [13.0105, 19.5157, 19.5157], [ …
braindotai
Can anyone plz provide me the link for the latest pytorch version compatible with cuda 9.0And also the steps to install it.
ptrblck
PyTorch 1.1.0 supported CUDA9.0 and the conda wheel can be downloadedhere. Why do you need this particular CUDA version? Would you be able to update to 9.2?
4158ndfkvBHJ1
Hello everybody,I have been struggling for a few days now to get the scatter function working as I want. I’m really sorry, I tried to understand the documentation but I failed. My usecase is the following :I have a [1,height, width] sized tensor, it’s a semantic mask for a segmentation network. Every pixel takes a valu...
ptrblck
Your workflow sounds right and this code snippet should work: h, w = 3, 3 mask = torch.randint(0, 7, (1, h, w)) res = torch.zeros(7, h, w) res.scatter_(0, mask, 1.) Could you check it locally and verify, that the result contains the expected values?
adi8862
I’m currently trying to detect in advance if a particular model + gpu + PyTorch version combination will run into an out-of-memory issue without actually running the model on the device.torch.cuda.max_memory_allocated() is working well to verify if I can correctly predict the minimum memory requirements of the model te...
ptrblck
I don’t think there is a reliable way to calculate the real GPU memory usage without running the code. Depending on your hardware, CUDA version, PyTorch version etc. the CUDA context would need a different memory footprint. While the difference might be small, this would already add some version de…
Nawel
Hi, I am just trying apex for the first time and running into the following error when training camembert using fast-bert:Found param roberta.embeddings.word_embeddings.weight with type torch.FloatTensor, expected torch.cuda.FloatTensor.I also get this indication, but i still don’t know how to deal with it:When using a...
ptrblck
Unfortunately, you won’t be able to use mixed-precision training without a GPU. The error message points towards an expected CUDATensor, while a CPUTensor was found. That being said, once you get access to a GPU, we recommend to try out the native mixed-precision support from the current master b…
localh
I have a binary dependent variable and I am unclear as to:get BCEWithLogitsLoss to workincorporate pos_weight (how exactly do I calculate the weights, is it of the total data set?) One class has 7000 observations and the other has 2224 in the total data set. Should it just be a tensor thats like: torch.tensor([0.3, 0.7...
ptrblck
You could deal with a binary classification use case in different ways: You could use a single output and treat the output as the logit (or probability) representing the nagative and positive class. For this use case you would use nn.BCEWithLogitsLoss (or nn.BCELoss, if you are applying a sigmoid …
EdinMahmutovic
So I have some long code, but I’ll give a snippet of the code that gives problems. I have build a DQN learning agent and I am training it on a Tesla V100 GPU.This is the line of code where the problem occurs:q_eval = self.Q_eval.forward(state_batch, state_seq_batch, tensor_batch_index) q_eval = q_eval[batch_index, acti...
ptrblck
No, the error message would give you the failing operation. However, the stack trace might point to the wrong line of code, due to the asynchronous behavior. You could rerun the code with: CUDA_LAUNCH_BLOCKING=1 python script.py args to get the proper stack trace with the offending operation.
shangguan91
https://github.com/valeoai/LightConvPoint/blob/master/examples/README.mdHey, i am reexperimenting with modelnet40, however,ERROR - ModelNet40 - Failed after 0:00:00!Traceback (most recent calls WITHOUT Sacred internals):File “train.py”, line 84, in maindevice = torch.device(_config[“device”])TypeError: Device() receive...
ptrblck
It seems that _config["device"] contains a None entry, while a valid device (or device string) is needed. You could either make sure the _config dict contains a valid device or alternatively specify the device manually e.g. via: device = 'cuda' if torch.cuda.is_available else 'cpu'
Rahul_R
Does running multiple copies of a model (like resnet18) on the same GPU have any benefits like parallel execution? I would like to find the loss/accuracy on two different datasets and I was wondering if it can done more efficiently on a single GPU. I am currently evaluating the datasets sequentially.Thanks!
ptrblck
Most likely you won’t see a performance benefit, as a single ResNet might already use all GPU resources, so that an overlapping execution wouldn’t be possible. If you want to try it nevertheless, you could have a look at theCUDA streams docs. Note however, that you would be responsible for proper …
Wesley_Neill
This is probably a silly question but…I am installing PyTorch on my laptop, which does not have a GPU. Ive been using a pre-installed version of PyTorch on Kaggle and GCP.I assume I should select ‘None’ for CUDA on the “getting started” page?I still want access to any methods or libraries that deal with CUDA liketorch....
ptrblck
The CPU package will include these method, so that you can write device-agnostic code. If you try to execute a CUDA operation, an error will be raised. However, no errors should be raised for utilitz functions e.g. to check of a GPU is available.
mflova
Hi!I am currently implementing the Monte Carlo sampling in order to calculate not only the output of the network but also its variance. To do so, it is needed to run the CNN with dropout enabled and input the same image like 20 times (which is, of course, 20 time slower compared to typical method). These outpus then ar...
ptrblck
Assuming that each image tensor has the shape [channels, height, width], you could use expand or repeat to create a tensor with the shape [20, channels, height, width]: x = torch.randn(3, 224, 224) x = x.unsqueeze(0) x1 = x.expand(20, -1, -1, -1) print(x1.shape) > torch.Size([20, 3, 224, 224]) # …
S_M
Hi everyone, I want to use the gradient of a vector during test or validation epochs. Would anyone describe me by an example of how to compute the gradient of a vector in test mode?thanks
ptrblck
Yes, loss.backward() using the test data would compute the gradients in the same way as during training. optimizer.step() would then update all parameters with their gradients, which would create a data leakage, since you would be training on the test dataset.
Bo_Ni
Hi,I have a customized GCN-Based Network and a pretty large graph (40000 x 40000). Basically, There is no problem with forwarding passing (i.e the GPU memory is enough); but cuda ran out of memory when loss.backward() is executed. The error message is as followingTraceback (most recent call last): File "main.py", li...
ptrblck
Your assumption sounds reasonable, since the first backward call will use additional memory to store the gradients. You could reduce the batch size and rerun it or alternatively you could also trade compute for memory via torch.utils.checkpoint. The malloc stack trace points again to the CUDACachi…
Chiara
I’m using the MNIST dataset for image classification as done herehttps://medium.com/dair-ai/building-rnns-is-fun-with-pytorch-and-google-colab-3903ea9a3a79(in the “RNN for image classification” bit).The data has shape 28x28, which means that i have 28 timesteps (rows in the image) and 28 inputs (number of columns) . Th...
ptrblck
You could pass the time steps one by one instead of the complete batch in these lines of code: lstm_out, self.hidden = self.basic_rnn(X, self.hidden) # apply loop here out = self.FC(self.hidden) Note that you could pass each row to the linear layer to get the logits, but this would change your mod…
shakasaki
Hello there,I’ve looked around for quite some time and could not find a similar post to this. I am trying to train a CNN for super-resolution on a cluster with CPU’s. Unfortunately, I do not have access to GPU’s right now.So I am using torch.multiprocessing and trying to run a for loop, as explained here :https://githu...
ptrblck
You could try to use a DistributedSampler for the Hogwild example as described inthis post.
zhousj
i implement instance norm by pytorch basic operations. but the result is different from torch.nn.InstanceNorm2d. Can anyone help me out? Below is my code:##########################import torchimport numpy as npx = torch.rand((8, 16, 32, 32))a = torch.nn.InstanceNorm2d(256)a.eval()with torch.no_grad():b = a(x)x_mean = t...
ptrblck
I think nn.InstanceNorm2d might use the biased variance, so changing the variance calculation to: x_var = torch.var(x, unbiased=False, axis=(2,3), keepdims=True) should work (I haven’t checked the source code of nn.InstanceNorm2d, but batchnorm layers use the biased variance, so I just tested your…
jasonyoung
I am currently working on classEmbedding()in PyTorch and I looked at its implementation.In theforward()method, it calls theF.embedding()method:https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/sparse.py#L124.Then I found thatF.embedding()method finally calls thetorch.embedding()method:https://github.com/p...
ptrblck
It should eventually call intothis methodfor the forward pass.
Se_di
Hey,I’m getting this error but i don’t understand why it has a problem with ‘action_value = torch.tanh(self.action_values(x))’ when I use relu or hardtanh there is no problem.class NAF(nn.Module): def __init__(self, state_size, action_size,layer_size, n_step, seed): super(NAF, self).__init__() self....
ptrblck
The issue is created by the inplace unsqueeze_ call on action_value, but is raised in the tanh. If you use action_value = action_value.unsqueeze(-1) instead, your code should work.
shangguan91
quite frustrated, i am having problems, implementing GCN model.firstly, i have download those init.commits, upload to colab and then run by !python …pythen i have to install packages. After i finished all , the last script give me error of re not defined.i imported re, still do not work… help, is my procedure right?fr...
ptrblck
It seems that the import re is missing in /content/3D/support_functions.py. Could you add it there and rerun the script? I assume that you are importing some functions from support_functions. Is that correct?
costa98
I have a neural network whose goal is to create a small video. Each time i run the nn it return an image (tensor converted in image using plt.imgshow()), and i have to create a GIF using those images
ptrblck
You could store each image separately and use an external program to create the GIF or use OpenCV (or another lib) in Python.This StackOverflow threadhas some suggestions.
jhh3
Hi,I’m looking at QuartzNet in NeMo and trying to probe some of the internal tensors. I see that I can useevaluated_tensors = neural_factory.infer(tensors=[a,b,c])to run inference and return the evaulations of a,b,c, but I can’t figure out how to get a list of the intermediate activation tensors, or to get a pointer to...
ptrblck
For a general PyTorch model you could use forward hooks to get the intermediate activations as describedhere. Since NeMo seems to be using a PyTorch model internally, you would have to access its layers to register the hooks.
Scott_Hoang
Hi everyone,I want to solstice some useful advice on how to debug a strange model behavior in my training. Recently, I have taken up a ML project, and in an effort to speed up training time, I converted the original training script’s Data parallel with torch’s distributed data-parallel with Nvidia Apex. My new model wi...
ptrblck
I would recommend to scale down the problem first e.g. by removing apex (and potentially other utilities) and test if the DDP model is working as expected. Note that we also recommend to use the native automatic mixed precision training in the current master branch or from the nightly binaries. You…
Y_Y
Hi all,If I only want to run forward() with same inputs and different weights in parallel, then merge the output after all forward() is done. How can I do this in Pytorch? It looks like I might be able to use cuda stream?https://pytorch.org/docs/stable/notes/cuda.html#cuda-streamsBut I’m not sure if this is the right w...
ptrblck
You could use streams, but would have to make sure to properly synchronize the code to avoid race conditions. Depending on the actual workload on the device, your speedup might not be huge, e.g. if the first model already uses the device sufficiently.
Aviv_Shamsian
Hi all,I have trained FRCNN usingtorchvision.models.detection.fasterrcnn_resnet50_fpnand now I want to use it’s feature extraction layers for something else.To do so I first printedfrcnn.modules()and see that the model has 4 major components:0) GeneralizedRCNNTransformBackboneWithFPNRPNROI HeadsI tried first to use bot...
ptrblck
You don’t necessarily need to wrap it in an nn.Sequential module, as it is already a working module. However, since the FeaturePyramidNetwork is used internally, you will get the OrderedDict as the output as seen inthis line of code. Which means, your previous code would work for this submodule.
Jordan_Howell
Hello,I’ve had a model running without error. I increased my training data size and now, I’m getting the below error.The error shows up after the last epoch is ran on the training data.I read to changetorch.no_grad()toroof_model.eval()but that didn’t seem to help.Traceback (most recent call last): File "<ipython-inp...
ptrblck
This error is raised, if a batchnorm layer cannot calculate the running statistics from a scalar value. Usually you would see it during training (model.train()) e.g. if the batch contains a single sample. This might be the case, if the length of your dataset is not divisible by the batch size with…
radek
I am attempting to implement the following operation from thispaper:image1402×339 74.9 KBThis is what it looks like in code:class FrontEnd(nn.Module): def __init__(self): super().__init__() self.bn = nn.BatchNorm1d(80, affine=False) self.register_parameter('alpha', torch.nn.Parameter(torch.t...
ptrblck
Thanks for the data! I loaded it and executed the provided code snippet, however I’m getting all finite outputs (even with executing the training loop several times). Which PyTorch version are you currently using? I tried to reproduce it with 1.6.0.dev20200611 and it’s working fine.