user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Sam_Lerman
I get this error and then it bugs:`UserWarning: ` `NVIDIA RTX A6000 with CUDA capability sm_86 is not compatible with the current PyTorch installation.` `The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70.`
ptrblck
You are most likely installing the PyTorch binaries with the CUDA 10.2 runtime, while your Ampere GPU needs CUDA 11. Select the CUDA 11.3 or 11.6 runtime in the install box, use the created install command, and it should work.
robinho
how to degenerate SGD to primitive GD? Or actually SGD(momentum=0, dampening=0, weight_decay=0, nesterov=False, maximize=False, foreach=None)=GD, where there’s no stochasticity?
ptrblck
The “stochastic” part refers to the mini-batch usage, so you could pass the entire dataset to the model and should get GD.
may1
I am trying to convert some pre-trained models to half precision for deployment.I triedmodel = model.half()and it could cast the basic FP32 CNN model into FP32 wellbut not LSTM modelI got this error when FP16 input was passed to torch.nn.LSTM layer after I called model.half()File "/~env/lib/python3.9/site-packages/torc...
ptrblck
You are right that model.half() will transform all parameters and buffers to float16, but you also correctly mentioned that h and c are inputs. If you do not pass them explicitly to the model, it’ll be smart enough to initialize them in the right dtype for you in the forward method: model.half() in…
shyZam
I am writing to migrate code from chainer framework to pytorch. I came across the below code:chainer.grad([loss_func(F.clipped_relu(X2,z=1.0),Yp)], [X2], set_grad=True, retain_grad=True)I tired looking at the pytorch documentation but was not able to find an equivalent function to implement the above code.https://docs....
ptrblck
I thinktorch.autograd.gradwould be the corresponding function.
robinho
There’s an inline function f = lambda x: 1+n(x), where n is a neural net defined by n=nn.Sequential(nn.Linear(1,10), nn.Sigmoid()).n needs to be trained and during training this f function is called all the time. Is this f function evolving with the n being trained, or is f just endowed with a frozen n without training...
ptrblck
Yes, it seems to work as I’m seeing weight updates: n = nn.Sequential(nn.Linear(1,10), nn.Sigmoid()) optimizer = torch.optim.SGD(n.parameters(), lr=1.) f = lambda x: 1+n(x) for _ in range(3): print(n[0].weight.abs().sum()) optimizer.zero_grad() x = torch.randn(1, 1) out = f(x…
Sam_Lerman
Say I want to index a tensor along an axis, but I don’t know a priori which axis. It could be:tensor[:, idx, :]Or it could be:tensor[idx, :, :]Or:tensor[:, :, idx]In these examples, the tensor has 3 possible axes. Is there a way to do this kind of indexing where both the axis and the index are variable?
ptrblck
You can use tensor.index_select as seen here: x = torch.randn(10, 10, 10) idx = torch.randint(0, 10, (2,)) ref1 = x[idx] ref2 = x[:, idx] ref3 = x[:, :, idx] out1 = x.index_select(0, idx) out2 = x.index_select(1, idx) out3 = x.index_select(2, idx) print((ref1 == out1).all()) # tensor(True) print…
Prachi
Hello all, can anyone explain to me what is happening here, I am a novice in this topic of memory management + colab:I am training a pre-trained inception V3 model for cifar10 data forepochs=10on a colab.Following is higher level script code:for each epoch:model.train()…model.eval()with torch.no_grad():……After thefirst...
ptrblck
If the validation loop raises the out of memory error, you are either using too much memory in the validation loop directly (e.g. the validation batch size might be too large) or you are holding references to the previously executed training run. Python frees variables once they leave a function sc…
CoffeeBumbleBee
I am trying to use 2 GPU’s for training.I followedthis tutorialand tested 1 GPU with batch size of 8 and image size of 512 and got the output:In Model: input size torch.Size([8, 1, 512, 512]) output size torch.Size([8, 1, 512, 512])This is maximum capacity for 1 of my GPU’s. My idea is to train on 2 GPU’s and increase ...
ptrblck
Yes, nn.DataParallel is usually creating a memory imbalance and will increase the memory usage on the default device as it’s used to store all inputs, all outputs, and to calculate the loss. We thus recommend to use DistributedDataParallel to avoid this overhead and to get a better performance com…
S_M
Hello allHow can I backpropagate loss over a specific layer of network (not the all the layers or the layers before the specific layer). I want to update the weights of a certain layer.Thanks
ptrblck
This should work: model = models.resnet18() x = torch.randn(2, 3, 224, 224) out = model(x) loss = out.mean() loss.backward(inputs=list(model.conv1.parameters())) for name, param in model.named_parameters(): print(name, param.grad)
exponential
Hello,I am trying to modify densenet for my use case by taking the output of a denseblock and concat. it with another while retaining the information. See the code below:class DenseNet(nn.Module): def __init__(self, growthRate, depth, reduction, bottleneck): super(DenseNet, self).__init__() nDenseB...
ptrblck
Your suggested interpolation will use the bilinear interpolation so would change the activation tensor. It depends on your use case if this would be acceptable or if e.g. a nearest neighbor interpolation would be preferable.
Vipin_Gautam
def pool2d(tensor, type= ‘max’):sz = tensor.size()if type == ‘max’:x = torch.nn.functional.max_pool2d(tensor, kernel_size=(sz[2]/8, sz[3]) )if type == ‘mean’:x = torch.nn.functional.mean_pool2d(tensor, kernel_size=(sz[2]/8, sz[3]) )x = x[0].cpu().data.numpy()x = np.transpose(x,(2,1,0))[0]return xTypeError: max_pool2d()...
ptrblck
The first value of the tuple is a float so use: x = torch.nn.functional.max_pool2d(tensor, kernel_size=(sz[2]//8, sz[3])) and it should work.
111466
I can not find the real full implemetnation codes of function Sigmoid_()?Colud you help me ? Thank you!
ptrblck
The CPU implementation should dispatch tothis kerneland the CUDA implementation tothis one.
robinho
I wonder if adam.step() is a single step or multiple steps towards convergence=minimization of loss? If it’s the latter, how is convergence judged?
ptrblck
It’s a single weight update step as seenhereandhere.
se7en.dreams
Hi, I have an input of shape14 x 10 x 128 x 128, where14isbatch_size,10is thesequence_lengthand each item in the sequence is of shape128 x 128. I want to learn to map this input to output of shape14 x 10 x 128, i.e., for each item in the sequence I want to learn 128-binary classifiers.Does the following model make sens...
ptrblck
The model architecture could work and the conv layers could be replaced with inear layers (but the current architecture might be easier to apply the batchnorm layers so you might want to keep it). The last reshaping might not be necessary as you are treating each time step as a separate sample in t…
Jianxin_Wang
Hi,I am trying to understand how data parallel distributes loss and gradient back to each device for a backward pass after the forward pass.I did a little experiment.class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() modules = [ torch.nn.Linear(10, 3), ...
ptrblck
The outputs will be gathered on the default device and thus the loss will also be calculated on the default device. Afterwards the gradients are scattered to all GPUs as shown in the diagram.
Aiman_Mutasem-bellh
Hello all,During installing Paytorchconda install pytorch torchvision cudatoolkit=10.1 -c pytorchit freezing(base) C:\Windows\system32>conda install pytorch torchvision cudatoolkit=10.1 -c pytorch Collecting package metadata: done Solving environment:How I can fix this issue?
ptrblck
Yes, try to use 11.3 or 11.6 as both should work.
krishna511
Can I get a straight answer why this is happening on a simpleMLPClassifer?Is it possible even? I am using the same seed same data same method.Regards
ptrblck
I don’t know how you are comparing the models and outputs as you haven’t shared any code, but note that the random number generators are not the same on CPU and the GPU, so seeing won’t create the same values. If you want to compare the outputs of different devices, store and load a state_dict so t…
Shahrullohon
When I convert torch model for mobile optimizer, it is giving different outputs. But the output is the same for torch model and jit model.import torch import torchvision from torch.utils.mobile_optimizer import optimize_for_mobile # model definition with two classes model = torchvision.models.mobilenet_v3_large() mode...
ptrblck
It looks indeed like a bug. Could you create an issue onGitHubwith a link to this topic and the minimal code snippet to reproduce the error, please?
erlebach
Hi! I need help on DataLoader to resolve what is probably a simple misconception. Below, I have a MWE illustrating my use case. I input a list of three arrays of size 1024 to a customDataset, which will return elementidxfrom each array as a sequence of three elements. I have checked thatDatasetby iterating through it a...
ptrblck
Thanks for the great MWE! The issue is a bit tricky to find, since iterating the Dataset works while the DataLoader only returns a single batch. However, after checking the implementation you can see that len(data) returns 3 and is then used by the DataLoader to define the used indices to create th…
Megh_Bhalerao
Hi all,I am trying to convert a real valued tensor to a PIL image to save on disk. When going through the documentation ofto_pil_image, I have a question in the following line in the pytorch/vision repo -github.compytorch/vision/blob/87cde716b7f108f3db7b86047596ebfad1b88380/torchvision/transforms/functional.py#L288# if...
ptrblck
I think your explanation is correct and the default assumption is an input image in the range [0, 1] if you are passing a floating point tensor (e.g. the output of ToTensor using a uint8 image) unless you want to use the F PIL.Image.mode which uses the float32 format.
CoolRabi
Hi, Im a torch newbie and attempting to assist a student with an issue they ran, when attempting to run a RNN for a special application.The error message is:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [50, 5]], which is output 0 of AsS...
ptrblck
Using retain_graph=True is wrong in most cases and usually used to try to fix the: RuntimeError: Trying to backward through the graph a second time error. Is this also the case here or do you have a valid use case to retain the graph? If not, remove it and detach the hidden state via: def forw…
rad
Hello!I am running a transformer model for traffic prediction (my own implementation ofhttps://arxiv.org/pdf/2202.03539v1.pdf) - The code is hereGitHub - radandreicristian/adn: A PyTorch implementation of the Attention Diffusion Network from "Structured Time Series Prediction without Structural Prior"..Without setting ...
ptrblck
Yes, it seems as if seeds are set inside your class somewhere. As another quick test, just print(torch.randn(10)) inside the loop before running the experiment and check if you would get at least different random values there.
aw632
Currently on stable and want to test out nightly. I use the command from the websiteconda install pytorch torchvision torchaudio -c pytorch-nightlybut got the response# All requested packages already installed.I tried again withconda update -all pytorch torchvision torchaudio -c pytorch-nightlybut the version of torch ...
ptrblck
Uninstall your current PyTorch binary and reinstall the nightly. Alternatively, create a new virtual environment and install the nightly binary there.
DRISS_ELALAOUI
please, I want to convert this piece of code from TensorFlow to PyTorch:with tf.name_scope("embedding"): self.embedding_matrix = tf.get_variable( "W", shape=[self.vocab_size, self.embedding_size], initializer=tf.contrib.layers.xavier_initializer(seed=1234)) ...
ptrblck
Something like this should work: embedding_matrix = torch.empty([self.vocab_size, self.embedding_size]) torch.nn.init.xavier_normal_(embedding_matrix) softmax_biases = torch.zeros([self.vocab_size])
eliaz
Hi,I have an issue when usingDataLoader, and I am not sure if this is an expected behavior.I usetorch==1.11.0I am trying to update labels of a datasets at each epoch.I tried:dataset.labels = new_labelsand:dataloader.dataset.labels = new_labelsBut it was not working. I found that the issue comes from the fact that I use...
ptrblck
No, I don’t think that’s easily possible, as each worker would use a copy of the dataset so manipulations would not be reflected. You would either need to recreate the DataLoader (after manipulating the Dataset) or would need to use your first approach and avoid persistent workers. There might be a…
doojin
Hi,What is different below two case? Is it the difference between being a leaf tensor or not? Or is there any other difference?I don’t know what it is, but I think both of them can calculate gradient. (If not, let me know)case1)a = torch.randn(3,4,4, device='cuda', requires_grad=True)case2)a = torch.randn(3,4,4).cuda()...
ptrblck
No, the model output will not be a leaf tensor as it’s computed by the input as well as the parameters and will thus have a history (i.e. it’s attached to a computation graph).
cijerezg
Torch 1.12 introduced the wonderful feature:torch.nn.utils.stateless.functional_call(), whose syntax is as follows:out = functional_call(model, params, inp)Namely, it allows to evaluate the NN with any parameters. However, how can I calculate the gradient with respect to the evaluated parameters of the output? It seems...
ptrblck
I’m not sure what the issue is, but it seems to work for me: model = nn.Linear(10, 10, bias=False) param = {"weight": nn.Parameter(torch.ones(10, 10))} inp = torch.randn(1, 10) out = torch.nn.utils.stateless.functional_call(model, param, inp) grad = torch.autograd.grad(out.mean(), param['weight'…
danb
When creating a Model i came across the effect that the Model would always converge to a state, where every sample in a batch would have the same output for the Model independent of the actual label. But with a batchsize of 1 the Model does also not converge/overfit.Example of what i mean with batch_size = 4 after 783 ...
ptrblck
I would try to remove the bias from your data by normalizing it. Also, the model is quite deep (which makes the convergence hard) so I would also reduce the number of layers. You could also change the learning rate and try out different optmizers such as Adam. After a few changes (and in particul…
Vedant_Roy
I have learned positional embeddings in my transformer with the following:self.positional_embedding = nn.parameter.Parameter( torch.zeros((sequence_len, d_model)), requires_grad=True )For embeddings, linear layers, and convolutions it seems like Pytorch (well, I’m using Pytorch Lightning), automatic...
ptrblck
The nn.Parameter class does not initialize the internal tensor and will use its values directly. Modules are implementing a reset_parameters function to initialize all parameters as seen in e.g.linear.py. In your use case you are explicitly initializing the positional_embedding parameter with torc…
oskean
I saw the following bit of code on Github and was curious about the behavior of the return statement in the forward() function. Specifically I’m wondering why something is subtracted, detached, and then added back. Is this a standard technique or some hack to get the computation graph to behave a certain way?import mat...
ptrblck
The code snippet would return the mi_loss in the forward pass (the loss tensor is subtracted) and would use loss the backward pass (the left-hand side is detached).
exponential
Hello guys,So I have the following code. My question is is it possible to use nn.Sequential this way?class CDH(nn.Module): def __init__(self, depth, growth_rate=12, reduction=.5, bottleneck=True, dropRate=0.0, before_Trans=True, d1_before = None): super (CDH, self).__init__ () if...
ptrblck
No, I don’t think your code would work for multiple reasons: it seems you are trying to pass an undefined tensor to a module during its initialization which is wrong: self.d1_after = self.Block1_after (self.out) since you would init the modules in the __init__ method and use them in the forward. …
divinho
It isn’t for me. I want to confirm whether that is normal or not.More specifically what I see happening is that in different builds I get different results for the same input.
ptrblck
I don’t think there is a guarantee to yield bitwise identical results between different PyTorch and library versions (e.g. different cublas, cuDNN etc.). The results should be deterministic using the same setup (PyTorch + lib versions, GPU etc.) if you stick to theReproducibility docs.
Lxnus
Hey everyone,I am currently working on a lstm which should predict a multidimensional output given any input.To clarify what I mean, I have the following setup:Input: [batch_size, seq_len, n_features] = [32, 16, 2]LSTM:def __init__(self, in_features: int, n_hidden: int, out_features: int, num_layers: int): supe...
ptrblck
You are explicitly using the last time step of the LSTM output only in this line of code: x = self.linear(x[:, -1, :]) and are thus removing the temporal dimension. You can directly pass the entire tensor to the linear layer which would then apply the layer to each time step.
yakhyo
I am trying to use video classifcation from torchvision models. The official code useskineticsdataset however when I try to use UCF-101 dataset I am getting theseruntime errors. Link to the train code:github.compytorch/vision/blob/main/references/video_classification/train.pyimport datetime import os import time import...
ptrblck
I don’t think the output_format would fix the issue, as the transformation is expected to work on [T, H, W, C] frames as seen in thedocs: transform (callable , optional) – A function/transform that takes in a TxHxWxC video and returns a transformed version. If your transformation doesn’t suppor…
li-yi-dong
I’m wondering that does compiling Pytorch needs CUDA driver or just CUDA toolkit.
ptrblck
You can use the CUDA toolkit alone to (cross-)compile PyTorch and wouldn’t even need a GPU to do so.
patrickctrf
I’m trying to reproduceGANSynthpaper and they make use of Pixel Norm, a technique that computes the norm of a single pixel among all channels per sample:Captura de tela de 2022-07-05 15-01-381050×323 45 KBHow can I have this kind of normalization in PyTorch?I tried torch.nn.functional.normalize(input, dim=1), but it no...
ptrblck
I think you could try to directly implement the normalization via: b, c, h, w = 2, 3, 4, 4 x = torch.randn(b, c, h, w) out = x / (1/x.size(1) * (x**2).sum(dim=1, keepdims=True)).sqrt() If you have any reference implementation you could compare these approaches and see if I misunderstood the form…
Stapo
I boiled down my issue to a very simple example. This network produces different values (by a small decimal) based on the batch size. Note that the values remain consistent regardless of batch size when using CPU as the device (also, is it normal that the output between using CPU and cuda is different?).import torch im...
ptrblck
There is no guarantee to create bitwise identical results for different workloads as different algorithms can be used internally on the GPU as well as CPU. If you stick to theReproducibility docsyou can expect to see deterministic results for the same workload as well as framework and library ve…
PabloVD
I have two tensors,aandb, and I want to subtract them in CUDA, inside a neural network evaluation.Each of these tensors contain ~1e5 float32 elements, specifically with shapetorch.Size([161858])and 0.647432 Mb each. When I try to subtract them in a naive way:c = a - bI get the following out of memory error:RuntimeError...
ptrblck
Could you post the exact shapes of a, b, and c? I would guess that some unwanted broadcasting might happen in the subtraction calls.
Gautam_N
Hi all,I want to preface this by saying I’m relatively new to this field, so I apologize in advance if the solution is trivial. I’m working to build a prediction model that is able to take general information about the weather and location of an accident to predict the severity of traffic caused as a result of the cras...
ptrblck
The usage of a single output dimension with F.log_softmax(x, dim=1) and nn.MSELoss won’t work for several reasons: F.log_softmax(x, dim=1) on a tensor of the shape [batch_size, 1] will always create an all zero tensor (since each “row” would have a probability of 1, thus a log prob of 0) nn.MSEL…
NancyShehata
I tried to run this PyTorch code, it doesn’t show any Epoch and also not showing any errors or warnings, can someone please help?image1600×843 26.9 KBimage895×823 16.5 KBloss_func = nn.CrossEntropyLoss()loss_funcfrom torch import optimoptimizer = optim.Adam(cnn.parameters(), lr = 0.01)optimizerfrom torch.autograd impor...
ptrblck
Yes, that’s what I meant. It shows that your DataLoader only contains 40 batches and your if condition will thus never return True since you explicitly only print the first loss value after 100 batches: if (i+1) % 100 == 0: print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' …
Andrew_Legend
Sorry if the title is a bad explanation of what I want, but I had no better way of describing itI asked a similar question yesterday, at the time of posting this and I got a solution. However it turned out that is not what I want. What I want instead is something like this example:A= [2, 3] B= [1, 2, 3] C= Function(A...
ptrblck
Broadcasting should work: A = torch.tensor([2, 3]) B = torch.tensor([1, 2, 3]) ret = A.unsqueeze(1) ** B print(ret) # tensor([[ 2, 4, 8], # [ 3, 9, 27]])
wayne1226
Now I have a tensor list with for same-size-tensor A=[a,b,c,d], say [3,224,224], what is the simplest way to merge them back to one tensor [[a,b],[c,d]] with size [3,448,448]?
ptrblck
I think F.fold should work assuming you want to create an output tensor where each “window” of the input is preserved: # setup channels = 3 h = 4 offset = channels * h * h a = torch.arange(offset).view(channels, h, h).float() b = torch.arange(offset).view(channels, h, h).float() + offset c = torch.…
jh_shim
As I know, DDP (DistributedDataParallel) works only when all parameters of the given module participate to calculate loss.In case ofnn.Embedding, I think some parameters of the module can be not used in forward pass.However, Transformers such as BERT works well with DDP.I don’t understand hownn.Embeddingcan work with D...
ptrblck
Even if not all indices of the embedding weight matrix are used, the parameter itself would still be used and would thus get a valid gradient (zeros for the unused indices), so DDP shouldn’t complain about it.
Simon_Watson
Hi All,I have built a custom autoencoder and have it working reasonably well. In an attempt to improve speed/performance, I have attempted to implement batch training.Looking at thePyTorch.orgsite, it appeared that setting the batch size in the dataloader and implementing an extra loop under the epoch loop would be eno...
ptrblck
It’s hard to tell if a speedup would be expected as the operations are quite small by themselves. While a loop would add a certain overhead, the actual dispatching of these workloads could also be visible. In any case, here is a draft of a code avoiding loops for the first operations (the higher p…
zfzhang
Hi,When defining custom Function class, we define static forward()/backward() methods, and in forward() we usectx.save_for_backward(…)to record the input tensors for backward pass.I’m wondering, when in inference mode (training = false), will the abovectx.save_for_backward(…)call still record the tensors for the never ...
ptrblck
Based onthis responsefrom@albanDit should not save any tensors if it’s executed in a with torch.no_grad() context (and I would also assume the same for with torch.inference_mode()).
DRISS_ELALAOUI
please I have a “targets” and “outputs” tensor which have a size [batch-size,slate_length]. “targets” contains values: True or False and “outputs” contains values in [0; 1]when I execute these lines:outputs_order = torch.argsort(outputs, descending=True, dim=-1) targets_sorted_by_outputs = torch.gather(targets, dim=-1,...
ptrblck
I don’t think this is the case, as targets_sorted_by_output seems to have a single dimension and raises the IndexError as seen here: k = 5 targets_sorted_by_outputs = torch.randn(10) targets_sorted_by_outputs[:, :k] # IndexError: too many indices for tensor of dimension 1
laro
I saw code which usenn.NLLLoss()(negative log likelihood loss).I looked on the results and some loss results (result ofnn.NLLLoss()) return negative values.What is the meaning of negative values of this loss?
ptrblck
I don’t know what a negative loss would represent and guess your inputs are in the wrong range as seen in this example: criterion = nn.NLLLoss() output = F.log_softmax(torch.randn(10, 10), dim=1) target = torch.randint(0, 10, (10,)) loss = criterion(output, target) print(loss) # tensor(2.6895) # …
SuryaKiran
[Changing the contents as the question wasn’t articulated well and I didn’t produce a minimum reproducible code]As per documentation of cross_entropy (CrossEntropyLoss — PyTorch 2.1 documentation)The input is expected to contain raw, unnormalized scores for each class. input has to be a Tensor of size (minibatch,C) for...
ptrblck
I assume the discussion is targeting the original post before the edit as the current code snippet uses 8 valid classes so I refer to: This code snippet is working, as it meets the requirements. The logits have a shape of [batch_size=3, nb_classes=8] while the targets have a shape of [batch_size=…
Vedant_Roy
I’m trying to manually set the weights for ann.Conv2d. I’ve seen this post:How to set nn.conv2d weights, however I’m trying to use a numpy array as the weights. Why? Becausenp.asarray(x)allows me to easily construct my weights array using a nested Python list (xis Python list).Example code:IN = 2 OUT = 3 KERNEL_SIZE = ...
ptrblck
Transform the tensor to float and it should work: with torch.no_grad(): proof_conv.weight.copy_(torch.from_numpy(weights).float())
ADONAI_TZEVAOT
I want to move certain values outside GPU. How do I do it?The following code is not working .loss.backward() optimizer.step() scheduler.step() loss = criterion(outputs, labels) acc = binary_acc(outputs, labels) epoch_val_loss += loss.item().detach() epoch_val_acc += acc.item().detach()It is throwing t...
ptrblck
No, as it will only free the cache and thus force PyTorch to re-allocate the memory via synchronizing malloc calls, which will slow down your code. You won’t avoid out-of-memory issues, but would allow other applications to use the freed GPU memory. No, freeing the cache will not have any funct…
Afekst
Hi everyone,first of all I’d like to ask if anybody know where libtorch’s documentation has disappeared?and for my main question…when I’m trying to use the function i get an exception. Example:torch::Tensor win = torch::hann_window(512, true, torch::TensorOptions().requires_grad(false));implies the following exception:...
ptrblck
The docs can still be foundhereand I’m unaware of any removal. Could you describe which parts were removed from there? This error is quite cryptic, but I get a dtype mismatch when executing your code on Linux, which is fixed via: #include <torch/script.h> // One-stop header. #include <iostream>…
lanka
train_data=torch.utils.data.DataLoaderwhen calling thetrain_dataobject through for loop, every iteration its gives random data fromtrain_data, is it sequential or random? how can I fetch data in sequential order?data=(video,caption).
ptrblck
Thanks for the link to the code. It works for me and the data is not shuffled: def collate_fn(data): """Creates mini-batch tensors from the list of tuples (image, caption). Args: data: list of tuple (image, caption). - image: torch tensor of shape - caption…
Loki_K
# create image dataset f_ds = torchvision.datasets.ImageFolder(data_path) # transform image to tensor. to_tensor = torchvision.transforms.ToTensor() for idx, (img, label) in enumerate(f_ds): if idx == 23: # random pil image plt.imshow(img) plt.show() # image to np array ...
ptrblck
ToTensor permutes the array and returns a tensor in the shape [C, H, W]. Using reshape to swap the order of dimensions is wrong and will interleave the image as is seen in your last output: # torch tensor torch_ten = to_tensor(img) print("torch_tensor shape:", torch_ten.sha…
f_hensel
Hi, this is my first post here and I’m not very familiar with pytorch yet. My situation is as follows:I’m training a simple (sequential, dense) neural network where the loss consists of a sum of two terms, say:loss = loss1 + loss2. I would like to investigate the contributions to the gradient of the network weights of ...
ptrblck
Your code snippet should generally work (besides the typo in backward() as seen here: # setup model = nn.Linear(1, 1, bias=False) x = torch.randn(1, 1) # zero out grads out = model(x) loss1 = out.mean() loss2 = ((out - 1)**2).mean() loss1.backward(retain_graph=True) grad1 = model.weight.grad.clo…
hitbuyi
They take weights into account, bias are not included, for exact calculation, bias should be included for memory size calculation, is that right?cs231_memory1013×780 238 KB
ptrblck
Yes, for the exact calculation you could add the bias shape, but it can be skipped as it’s usually a small overhead. E.g. the first conv layer: conv = nn.Conv2d(3, 64, 3, padding=1) would create an activation shape of [batch_size, 64, 224, 224] = 3211264*batch_size elements, has a weight of [64, …
mdelas
I am training a BERT model using PyTorch and after endless research on different versions I can’t be sure which should be the correct implementation of DDP (DistributedDataParallel).I am working in aworld_size= 8. 1 node and 8 GPUs. As far as I understand, DDP spawns one process per rank and trains the same model on di...
ptrblck
TheDeepLearningExamples - BERTrepository should give you a working example using these utils.
Aarnav_Sawant
Hi,I wanted to initialize a Conv2D Kernel which returns the same image after running the image through it. This is the code I am currently usingwts = np.zeros((3,3,3,3)) nn.init.dirac_(torch.from_numpy(wts)) with torch.no_grad(): conv_layer.weight = nn.Parameter(torch.tensor(wts,dtype=torch.float)) new_img = conv_lay...
ptrblck
You would need to use a grouped convolution where the posted kernel would be repeated in dim0 (the out_channel dimension) as seen here: # setup in_channels = out_channels = 7 # init wts = torch.zeros(1, 1, 3, 3) nn.init.dirac_(wts) wts = wts.repeat(out_channels, 1, 1, 1) conv_layer = nn.Conv2d(…
KFrank
Hi Forum!I see a cuda error (in a particular situation) the first time I calleigh(),but not on subsequent calls. (This is on the current stable, 1.11.0, butI also see it on the latest nightly, 1.13.0.dev20220626.)By “first time” I mean that I start a new python session and then run thescript below – the first call fai...
ptrblck
Hi@KFrank, thanks for creating the issue and code snippet! So far I was unable to reproduce the issue using 1.13.0.dev20220626+cu113 on a P100, which is of course not the same device you are using (same architecture though). While I’m trying to grab a 1050Ti (or a more comparable GPU) could you …
gummz00
Hello,I’m running a training loop consisting of around 1700 images of 512x512 resolution. The batch size is 8. I have 15 GB of GPU memory, and yet, I cannot use a higher batch size than 8 since I will get an out of memory error.Is there something I’m doing wrong in the code or do those numbers look right?
ptrblck
The images will take a small portion of the device memory and the majority will be used by the actual model training, i.e. parameters, forward activations, gradients, etc. The general memory requirement thus depends on the actual model as well as the input shape.
Fusionastic
I’m using the Huggingfacemicrosoft/mdeberta-v3-basepretrained model to finetune on my task. I discovered that during training, if using AMP, the optimizer never gets updated. step() method of the optimizer never gets called by scaler, because the scale of the scaler keeps shrinking until this float point number itself ...
ptrblck
This could mean that the forward pass or the loss calculation would create invalid values and the GradScaler tries to decrease the scaling factor in case it’s too large. However, if the output is already invalid, decreasing the scaling factor would of course not work anymore, so you shoulde defini…
MagaMakhauri
Hi!This may be a stupid question, but if I am manually encoding string data (such as city names, airports, class of the aircraft)I later use them for ML.Does it matter what number I chose for any given ‘city’ of no?Model should calculate coefficient from a city to cityWhile I have dates, most of my input data isnt nume...
ptrblck
I don’t know what “coefficients” refer to, but the encoding and sorting depends on the use case and how the loss is calculated. E.g. if you are working on a multi-class classification use case the order wouldn’t matter as each class corresponds to an integer label without any relation to each other…
Shaojun_Ma
Hi dear community, I want to post a question about autograd.Here are my functions:def gradients(net, inputdata): inputs_res = inputdata.clone() outputs_res = net(inputs_res) gradients = autograd.grad(outputs=outputs_res, inputs=inputs_res, grad_outputs=torch.ones(outputs_res.si...
ptrblck
This error would be raised as it seems you are reusing the output as a new input in this loop: for t in range(NT): pos, vel= nn_sym4(pos, vel, dt, neth) and are thus increasing the computation graph. Is this desired? If so, then the slow down in the gradient computation would be expec…
ZahAbdel
Hi,how does 2d Convolution in expansive path in Unet from 256 to 128 feature maps work?I mean normally that happened if we want to extract more feature maps from an input.Unbenannt699×606 32.5 KB
ptrblck
Each kernel has a dimension [out_channels, in_channels, height, width] and thus does not take the average of the input activation but processes each input channel with a different set of weights (note the in_channels dimension).CS231n - Convexplains it in more details with a few vistualizations.
Oguzhan
Hi, I am trying to create several encoder blocks by using nn.ModuleList and I get NotImplementedError.class Transformer(nn.Module): def __init__(self,embed_size,num_heads,N,in_channels,batch_size,num_encoders,num_class): super().__init__() self.num_heads = num_heads self.embed_size = embed_s...
ptrblck
You cannot execute the nn.ModuleList directly but would need to iterate it (as you would do with a plain Python list). If you want to execute the internal layers sequentially you could use nn.Sequential instead.
exponential
Hi guys,Total noob here.So, I have the following codeclass MyModel(nn.Module): def __init__(self, depth, some var, some var1): super(MyModel self).__init__() def L1_block(self, x, before_trans = True): some code def L2_block(self, x, before_trans = True): some code def U1_block(self, x, bef...
ptrblck
The second approach could still hit the issue as you are reusing the same x_. If self.L1_block applies an inplace operation to x_ the next usage could be wrong. This would make sure to pass the original inputs to each module: def forward(self, x): out1 = self.layer1(x.clone()) out2 = self.…
Allenkei
Hi,I am trying to optimize a custom loss function for a Graph Neural Network. Given ann by nadjacency matrix, I first calculate two network statistics: (1) count of edge, (2) count of 2-stars. Below function returns the 2 network statistics.def network_stat(A): n = A.shape[0] holder = torch.zeros(2, dtype=torch.flo...
ptrblck
Yes, I think your description is correct as network_stat modifies holder inplace in: holder[0] += A[i,j] # first network statistics # and holder[1] +=A[i,k] * A[j,k] # second network statistics You could try to replace this operation with its out-of-place version via: holderA = holderA + A[i, j] …
songyuc
Hi, guys,I want to know how to inspect whethet there is NaN or Inf in gradients after amp?optimizer.zero_grad() with autocast(): output = model(input) loss = loss_fn(output, target) scaler.scale(loss).backward() # To Insepct Whethet There is Infs or NaNs in Gradients After AMP? if contain_inf_nan(): # Do no...
ptrblck
You can inspect the .grad attributes of each parameter (as is also done in the scaler.step() to avoid updating the parameters if invalid gradients were found e.g. due to a too large scaling factor) e.g. via: if not all([torch.isfinite(p.grad) for p in model.parameters()]): print("invalid gradie…
papoo13
When adding torchvision.transform.ToTensor() to our dataloaders transformation, ToTensor() sets the datatype of input images X to torch.float32 and labels y to torch.int64. Is there a specific reason for this?
ptrblck
The CIFAR10 dataset applies the transform only to the data samples as seenhereand uses target_transform for the targets: if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) …
scirocc19900305
int main(){ std::cout<<torch::cuda::is_available()<<std::endl; auto tensor=torch::randn({3,10},torch::kCUDA); auto p=tensor.contiguous().data_ptr<float>(); torch::Tensor te=torch::from_blob(p,{3,10}); std::cout<< te<<std::endl; return 0; }then I got “Process finished with exit code 139 (interrup...
ptrblck
It should work, if you specify the right device in from_blob: auto t = at::empty({1, 2, 3}, TensorOptions(kCUDA, 0)); auto t_ = from_blob(t.data_ptr(), {1, 2, 3}, kCUDA);
mrdbourke
Hello,I’m trying to replicate the ViT paper:[2010.11929] An Image is Worth 16x16 Words: Transformers for Image Recognition at ScaleI’ve reproduced the architecture, however, some strange things happen when increasing the size of thenn.Linear()layers.For example, when trying to run ann.Linear()layer with over3000hidden ...
ptrblck
The CUDA error: invalid device ordinal might be raised, if your system “dropped” the GPU, which could also indicate a shutdown e.g. due to a weak/faulty PSU. You could check dmesg for Xid error codes and see if some are indicating a bus error etc.
laro
I Have the following model:import torchimport torch.nn as nnimport torch.nn.functional as Fclass MyModel(nn.Module):def __init__(self, input_size, num_classes): super(MyModel, self).__init__() self.layer_1 = nn.Conv1d(1, 16, 3, bias=False, stride=2) self.activation_1 = F.relu ...
ptrblck
Remove the comma after nn.Flatten() and the error should be gone: self.flatten = nn.Flatten (), # <- note the comma
desert_ranger
I am getting the following error - RuntimeError: the derivative for ‘target’ is not implementedI did have a look at similar posts however they are different from my problem. I’m trying to code a AE from scratch. Here’s my code -import torch import torchvision import torchvision.transforms as transforms import matplotli...
ptrblck
I cannot reproduce the error using your code snippet, but would guess you could detach() the outputs passed as the target to nn.BCELoss. However, I also don’t quite understand why you would like to calculate the loss between the output and itself. Shouldn’t it be the output and the input ot a target…
John_M
How to obtain the tensor from the middle part of a CNN model (EfficientNet_b0), instead of the last layer?I saw code from some researchers that obtain the tensor from the middle part of ResNet50 in the following method:To draw ResNet50 in a simple way (there are other ways of drawing it) based on the PyTorch model:(fir...
ptrblck
You could use forward hooks as described e.g.hereor manipulate the forward method directly by creating a new module deriving from the EfficientNet_b0 implementation.
andre99amaral
Hello,I am getting this problem when using DataParallel I can not access my LSTM internal weights. The following picture exemplifies the error.image823×200 66.4 KBThanks in advance for your help!Regards,André
ptrblck
If you are using nn.DataParallel the model will be wrapped into the .module attribute so you might need to access the parameter via model.module.layer.weight.
Jimut123
We can calculate weighted loss by defining a custom loss like this:custom_loss = l_1 * loss_1 + l_2 * loss_2 + …. + l_N * loss_NSay we are usingloss_1as MAE andloss_2as MSE, etc.I wanted to know that, should the constraint for l_i’s always needs to be 1 for weighted average?l_1 + l_2 + … + l_N = 1Or it could be greater...
ptrblck
I think the weighting can sum to any value and would just scale the loss and thus the gradients. If you’ve adapted the learning rate already to the loss scale you might want to keep the sum of the weights as 1 to avoid scaling it further.
songyuc
Hi, guys,I want to know whethertorch.ampwould cause a slower convergence. I found after usingtorch.amp, my custom model seems to converge slower than training it withouttorch.amp.Your answer and guide will be appreciated!
ptrblck
No, this shouldn’t be the case as seen e.g. inthese loss curvesfor RN50.
Dizzy_Hint
Hi all,I am trying to adjust the C++ code in Aten library(pytorch/aten/src/ATen/native), but it is not practical to run CMake every time.I found this post, but the make option(build_caffe2) does not work anymore.github.com/pytorch/pytorchRebuilding Pytorch after modifying C++ code in aten libraryopened11:35AM - 08 May ...
ptrblck
I usually just use python setup.py develop which will trigger a full rebuild the first time, but will only rebuild the changed (and affected) files afterwards.
mahesh_bhosale
I want to use a custom collate function which collates data based on the arguments passed to it. I am not sure if it’s possible to pass the arguments to collate function internally from the data loader.
ptrblck
I don’t know where this argument would be coming from, but in case you want to set an additional argument in your collate_fn while creating the DataLoader, you could use a lambda approach. If you want to pass this argument from the Dataset, you could return it and use it in your custom collate_fn. …
ADONAI_TZEVAOT
I have the following outputs.shape: tensor(-0.0162, device=‘cuda:0’, grad_fn=) torch.Size([])The following is my error:ValueError: Target size (torch.Size([1])) must be the same as input size (torch.Size([]))How do I make ‘outputs’ to be of size 1?Please help!
ptrblck
You could unsqueeze the scalar (0-dim) tensor: x = torch.tensor(-0.0162) print(x) # tensor(-0.0162) print(x.size()) # torch.Size([]) y = x.unsqueeze(0) print(y) # tensor([-0.0162]) print(y.size()) # torch.Size([1]) Note that the size is shown correctly and is expected to be empty for a 0-dim tens…
Sam_Lerman
I have two networks and one of them uses 2D conv layers where one of the kernel dims is size 1, and the other just uses 1D conv, but is equivalent.So why does the latter run faster if they are mathematically the same?
ptrblck
It should not, but you would need to profile it using your setup (GPU, PyTorch version, CUDA + cuDNN + cublas version etc.) as the performance would depend on the used environment.
JohnPolo
I’m using code from thistutorial. I have my own data. It is a very small set of images, just seven with seven masks. The masks have a black background and four AOIs each with their own shade.When I get to these lines:dataset = sensor_image(root = '/home/nightjar/Documents/images', transforms = get_transform(train=True)...
ptrblck
I would add debug print statements to the __getitem__ and try to isolate which lines exactly fails and what the indexed object contains.
4158ndfkvBHJ1
Hi everybody,I am following the torchvision documentation for this function (uint8 data type for the image input, (N,4)-sized boxes tensor) and I think the following minimal example should work:from torchvision.utils import draw_bounding_boxes import torch image = torch.ones(1,1000,1000).type(torch.uint8) boxes = tor...
ptrblck
The code works fine for me and results in: [image] Based on the error message it seems a numpy array is expected as one of the input arguments and I guess the error is raised inthis line of code. Could you update torchvision and see if this would fix the issue as I currently don’t know what migh…
SouthTorch
I ran two LeNet5 training on different datasets, one is MNIST, the other is CIFAR10, the code is the same except dimensions, including the visdom related codes being the same, like:viz=Visdom() viz.line([0.], [0.], win='train_loss', opts=dict(title='Train Loss')) viz.line([0.], [0.], win='val', opts=dict(title='Validat...
ptrblck
I guess you are creating a single visdom server and might be using the same environment with the same window names, which would then write to the same plots. Try to create separate envs and select the one you want to see in visdom directly.
SouthTorch
The following CNN net works fine:class myLeNet5(torch.nn.Module): # for CIFAR10 image classification def __init__(self): super(myLeNet5, self).__init__() self.conv_unit=torch.nn.Sequential( torch.nn.Conv2d(channel_size, 6, kernel_size=5, stride=1, padding=0), torch.nn.AvgPo...
ptrblck
You can use nn.Flatten to flatten to activations before passing them to the linear layer.
SouthTorch
Many people use the following code to kfold split the dataset:from sklearn.model_selection import KFold kfold = KFold(n_splits=k_folds, shuffle=True) for fold, (train_ids, test_ids) in enumerate(kfold.split(dataset)):I just want to know other pytorch native ways. Thanks. Just feel not to import too much stuff.A follow ...
ptrblck
I;m not aware of a native PyTorch implementation of KFold and would generally recommend to use implemented and well tested modules (in this case from sklearn) instead of reimplementing the same functionality (and potentially hitting bugs) unless you have a strong reason to do so. It depends which …
SouthTorch
I am trying to implement kfold in MNIST dataset. My idea is to split the data to k_folds=5, and max_epoch=10, in the 10 epoch, the 4+1 data would be used respectively as train and val data twice. Here is my implementation:import torch import torchvision from visdom import Visdom from sklearn.model_selection import KFol...
ptrblck
The sampler will be applied through the DataLoader while you are checking the length of the original internal .dataset attribute (which will not be changed). The len of the DataLoaders should return the expected number of batches.
SouthTorch
Here is the myNet, defined as:class myMLP(torch.nn.Module): def __init__(self): super(myMLP, self).__init__() self.model=torch.nn.Sequential( torch.nn.Linear(784, 200), torch.nn.Dropout(0.3), #drop 30% torch.nn.LeakyReLU(inplace=True), torch.nn.Linea...
ptrblck
It is exactly the defined behavior. The linear layer expects inputs in the shape [batch_size, in_features]. Your input has 100 samples (batch_size=100) and you are flattening the input to [batch_size=100, in_features=784] so the layer will process this batch as specified. No broadcasting is used i…
XavierB
Hello everyone,I have been working on a project where the data and features are stored in Numpy arrays, and I found that theDataLoader was quite slowwhen thenum_workers> 0, so I decided to recreate the issue with a dummy example:import numpy as np from torch.utils.data import DataLoader class NumpyDataset: def __...
ptrblck
I don’t think this effect is necessarily depending on the usage of numpy but might be the expected overhead from using multiple processes to only index an already preloaded dataset. Multiple workers are beneficial especially if you are lazily loading and processing the data, i.e. if a single sample…
lifelonglearning
I’m trying to convert my tensorflow model into pytorch, however, I’m a bit confused about the ordering / how things such as batch_size and channels have to be passed in which sequence.I started creating my own dataset. Afterwards I defined my model however with receiving the following RuntimeError.RuntimeError: Given g...
ptrblck
The issue is raised as x = torch.flatten(x) will flatten all dimensions, while you most likely want to keep the batch dimension and flatten the others. You could use the same view operation from previous calls (x = x.view(x.size(0), -1)) or use x = torch.flatten(x, start_dim=1, end_dim=-1). Afterw…
hitbuyi
suppose that I have two models, which are created both by nn.modulemodel1 = Sequential(…)model2 = Sequential(…)model1 and modle2 looks like each otherso ,how to compare model1 and model 2 exactly? does pytorch provide API to compare them?Thanks
ptrblck
Could you explain what “compare” means in your use case? If you want to check the parameters of both models and see if they are equal, you could check both state_dicts and use e.g torch.equal for each parameter/buffer. On the other hand, if you want to verify the same forward pass logic (additiona…
L_R
Sorry I’m very new to deep learning and PyTorch. I’m looking into some codes about LSTM with pytorch.colab.research.google.comGoogle ColaboratoryWhy does he use Variable indataX = Variable(torch.Tensor(np.array(x))) dataY = Variable(torch.Tensor(np.array(y))) trainX = Variable(torch.Tensor(np.array(x[0:train_size]))) ...
ptrblck
Yes, you can directly execute the forward pass if you pass the input tensor in the expected shape to the model. By default the batch dimension would be dim0, but be careful about RNNs as they use dim1 as the default dimension for the batch size (you could use batch_first=True to change this behavior…
111414
I train a CNN based ontorch.nn.DataParalleland specify GPUs by the following code:... import os ... os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' ... device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') ... model = torch.nn.DataParallel(model).to(device) ...T...
ptrblck
Yes, and you can change the device_ids order in this case: import torch import torch.nn as nn import torchvision.models as models device = 'cuda:3' model = models.resnet18() model = nn.DataParallel(model, device_ids=[3, 0, 1, 2, 4, 5, 6, 7]).to(device) x = torch.randn(8, 3, 224, 224, device=dev…
p4x
I’ve a new machine with a low-gpu and I want to use pytorch with CUDA in practicing deep learning but it gives mefalsewhen i run torch.cuda.is_available() even after installing with this cmd :conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch". Need help in using the CUDA.Have already installed cu...
ptrblck
This would mean that you’ve installed a CPU-only binary or built from source without a properly installed CUDA toolkit. Uninstall the current PyTorch installation or create a new virtual environment and reinstall PyTorch with the desired CUDA runtime.
YoPit
Hello,Sorry if my question is too simple or naive but I’m new in jit/TorchScript.I have saved a model withtorch.jit.scriptafterthe training loop and want to load it in C++ for inference using thetorchlib. Is it enough to save the model in this way to keep the trained weights or should I do something more?Thanks!
ptrblck
It should be enough to export the model via torch.jit.save as described inthis tutorial.
AaronPonceSandoval
hi, i have a problem with the neural network optimization reproducibility with the black hole algorithm (metaheuristics). I am maximizing the accuracy by exploring the learning ratio, but at the time of reproducing the results I am not able to obtain the same. My optimal result is in iteration 20 of the black hole algo...
ptrblck
Thereproducibility docsgive you more information e.g. on how to enable deterministic algorithms etc., which might be helpful.
TinfoilHat0
I’m using some data augmentation on my training set during the training. After the training ends, I’d like to measure my train accuracy using the original, non-augmented training set.To do so, do I have to initialize dataset again without augmentation, or is there a better way to do it?
ptrblck
Re-creating a new dataset without any transformations sounds like a proper approach assuming you are lazily loading the samples (which would then be cheap). Otherwise, you could also try to set the internal .transform attribute to False assuming self.transform is used to apply the transformations o…
scientia
I’m using a pretrained network, built some layers on top of it, and then finetune. But I wonder if we can divide the gradients for the subnetwork only (the lower layers) by some factor to avoid catastrophic forgetting as soon as we start the training.
ptrblck
Yes, you could scale the gradients before the optimizer.step() method and after calling loss.backward() by accessing the .grad attributes of the desired parameters (the gradient clipping utilities might also be interesting for your use case). Alternatively, creating different optimizers with differ…
yakhyo
I used to use declaring allReLUandMaxPooling2dlayers in__init__()part of the model. However these these two functions have no learnable parameters? So Do I need to declare onlyConv2dandBatchNorm2din the__init__()part of the model? This below example is one of my code snippet of creating a Conv by stackin Convolutional,...
ptrblck
I think it depends on your use case and eventually also depends on your coding style. E.g. if you plan to replace specific layers later, using the module approach might be easier than manipulating the forward method.This postexplain the different approaches in more detail.
luofan
For example, I have a big module “BigNet”, and two gpus. Each gpu’s memory can only allow me to train one module. I know I can do thisnet1=BigNet().to(gpu1) # optimizer 1 net2=BigNet().to(gpu2) # optimizer 2 X=X.to(gpu1) y=net1(X) y=net2(y.to(gpu2)) loss=loss_fn(y, label) loss.backward() optim1.step() optim2.step()By t...
ptrblck
You could check theCPU offloadingfor your use case.
LoiseauNicolas
Hello everyone,I have probably a problem which is probably not a problem… I’m trying to implement a custom nn.Module loss function.# Here I want to compute repeatability between two sets of points def repeatability(kp1, kp2, threshold=3): if 0 in (len(kp1_), len(kp2_)): return 0 dist = torch.cdist(kp1_,...
ptrblck
Based on your code snippet I don’t think it would be a problem to re-wrap rep into a new tensor, as it shouldn’t be attached to a computation graph in the first place (so you are not detaching it at all).