user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
tominator
I trained a semantic segmentation model (FCN). Now I am writing an API where I can call the model and get back the segmentation result as an array. The inference of the model on the GPU is really fast (0,02 seconds). The problem is when I want to bring the output back to the CPU: it takes 3,8 seconds. My image resolut...
ptrblck
I get a transfer time of approx. 700ms for an output of [1, 64, 2048, 1536] on my laptop, which shouldn’t have the fastest GPU connection compared to a server or workstation using: x = torch.randn(1, 64, 2048, 1536, device='cuda') nb_iters = 100 # warmup for _ in range(10): y = x.cpu() torch.…
Niamul_Quader
Hello,I am trying to implement a dataloader with the following sampling characteristics:Essentially, given that there are N (e.g. N=10) data points in a dataset, I am trying to build a dataloader where the data points sampled in the second half of a batch will depend on the data points sampled in the first half of a ba...
ptrblck
One simple approach would be to use batch_size=2 in the DataLoader and add the sampling logic to Dataset.__getitem__. This method would get the two indices as its index argument, and you could use this index to sample the desired paired sample. If you want or need, you could also use a BatchSampler,…
henry_Kang
Hello. Happy New year!!!I am trying to calculate my suggested network speed and comparison network. Both are semantic segmentation network.My network name is A.The other name is B.The input size of image is same. There is no resize or crop.From Titan RTX, the network A has 25 FPS. The B has 20 FPS.In the google colab I...
ptrblck
If you are using cudnn, then different kernels might be picked due to the difference in workload (models) and GPU architectures. You could use torch.backend.cudnn.benchmark = True to let cudnn profile the kernels and pick the fastest one. Note that the first iteration for each new input shape will …
phaedrus
I’m trying to fine-tune Resnet18, but replaced BatchNorm with GroupNorm. It works on CPU, it works when I don’t unfreeze the GroupNorm, it works with BatchNorm… but with GroupNorm unfrozen, it always fails withRuntimeError: CUDA error: an illegal memory access was encountered.Here is a minimal code that reproduces the ...
ptrblck
Could you update to the latest PyTorch release and also try the CUDA10.2 or 11.0 binaries? If you are still hitting the illegal memory access, could you run the script via: CUDA_LAUNCH_BLOCKING=1 python script.py args and post the stack trace here?
amitoz
Is this the right way to time profile the model prediction on a test sample?import torch.autograd.profiler as profiler x.to("cuda:0") # test sample model.eval() with profiler.profile(use_cuda=True) as prof: with torch.no_grad(): pred = model(x) print(prof)
ptrblck
I would recommend to add some warum iterations and also calculate the actual runtime as a mean over iterations. This should be automatically done for you by using torch.utils.benchmark from the current master branch or nightly binary.
zeyuyun1
Hi,I think this question is very similar to thispost(which explains how to access an 4-D tensor through 3-D index), but I still can’t figure it out.I want to access an 4-D tensor through 2-D index like following:dim1 = 3 dim2 = 4 dim3 = 5 dim4 = 10 source = torch.randn((dim1,dim2,dim3,dim4)) index = torch.randint(dim3,...
ptrblck
I assume ret should be initialized with the shapes [dim1, dim2, dim4], otherwise you’ll get a shape mismatch error in the posted loop. If that’s the case, this code should work: dim1 = 3 dim2 = 4 dim3 = 5 dim4 = 10 source = torch.randn((dim1,dim2,dim3,dim4)) index = torch.randint(dim3, (dim1, dim2…
Gor_Matevosyan
Hey everyone.I’m trying to train this exmaple:device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) class TwoLayerNet(torch.nn.Module): def __init__(self, D_in, H, D_out): super(TwoLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 ...
ptrblck
I can reproduce the issue, which is raised by disabling the gradient calculation globally by the silero-models creation inthis line of code. I don’t know, why it’s disabling the gradient calculation, but you can enable it again via: torch.set_grad_enabled(True) after loading the model.
coincheung
I was reading the code of mask-rcnn to see how they fix their bn parameters. I notice that they useself.register_bufferto create theweightandbias, while, in the pytorch BN definition,self.register_parameteris used whenaffine=True. Could I simply think thatbufferandparameterhave everything in common except thatbufferwil...
ptrblck
Yes, you are correct in your assumption. If you have parameters in your model, which should be saved and restored in the state_dict, but not trained by the optimizer, you should register them as buffers. Buffers won’t be returned in model.parameters(), so that the optimizer won’t have a change to u…
Anno
I defined a simple custom data set like in the officialexampleand named the class “Dataset”. Then in my training method I split the data set into training and validation like this:dataset = Dataset(opt) train_size = int(0.8*len(dataset)) val_size = len(dataset) - train_size lengths = [train_size, val_size]...
ptrblck
Instead of using dataset.random_split I would create indices for both splits, create two separate datasets with the custom transformations etc. applied to the training and validation dataset, and wrap both datasets in Subsets using the indices. This would allow you to pass the different arguments o…
justanhduc
Hi. Is there any official way to convert directly an array of native CUDA containers likefloat3to atorch::Tensor? If not, is there any efficient way to to it? Thanks!
ptrblck
You should be able to create a tensor via torch::from_blob with kCUDA as the optional argument.
cdahms
I’m attempting to use the PyTorch built-in ResNet 50 model fromhttps://pytorch.org/docs/stable/torchvision/models.htmlwith single-channel (grayscale) images.I figured out from various posts on this forum that I needed to change my model setup like so:# MyResNet50 import torchvision import torch.nn as nn def buildResN...
ptrblck
You could calculate the stats from your current training dataset, as was done for the ImageNet data for the posted values (or just use the 0.5 “defaults”).
Y_shin
Say I have a top-k indexing matrixP (B*N*k), a weight matrixW(B*N*N)and a target matrixA (B*N*N), I want to get a adjacent matrix that operates as the following loops:for i in range(B): for ii in range(N): for j in range(k): if weighted: A[i][ii][P[i][ii][j]] ...
ptrblck
You could use a scatter_/gather approach as seen here: B, N, k = 2, 3, 4 P = torch.randint(0, N, (B, N, k)) W = torch.randn(B, N, N) A = torch.zeros(B, N, N) A_ = A.clone() # loop for i in range(B): for ii in range(N): for j in range(k): A[i][ii][P[i][ii][j]] = W[i][ii][P[…
Hacking_Pirate
Hi,I am trying to create a dataset class for a problem, In that all the targets are in the form of a string like “Airplane”, “tree” etc. When I am trying to convert it into a tensor is says thatTypeError: must be real number, not string, also when I am trying to convert image to tensor it saysTypeError: must be real nu...
ptrblck
You would have to map the words to indices as e.g. described inthis tutorialfirst and could then create the tensors containing the numerical values. The second error is raised, if the JPEG file descriptor instead of an already loaded image array is passed to the tensor creation. Make sure img is …
Sutharsan_Mahendren
class Self_Attn(nn.Module): """ Self attention Layer""" def __init__(self, in_dim): super().__init__() # Construct the conv layers self.query_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//2 , kernel_size= 1) self.key_conv = nn.Conv2d(in_channels = in_dim...
ptrblck
Your approach could work theoretically, but I would be careful about the overall workflow in your training script. Usually you would setup the model and pass all parameters to an optimizer before the first forward pass. This won’t work properly in your approach, since not all modules are initializ…
Shawn0
Hi all,I’m working on a model for multi-task learning which has, say, 1000 tasks. nn.ModuleList() was used to wrap those tasks (heads) as shown in the below model. Assuming the batch size is 32, the output is a list of 1000 sublists each has 32 predicted values. One issue here is the label matrix is actually very spar...
ptrblck
You could pass the target tensor into the forward method and use it to skip the actual calculation of head in the last for loop, if this output is not needed (i.e. if no target is available for it). During validation, you would have to make sure that the target tensor is ignored and I assume you wa…
Super_Pie_Camel
I am currently implementing my own train.py for yolov3 object detection.However, I met some problem about the labels.For yolov3 object detection, it is allowed to detect multiple object in an image.In this case, different image may have different number of detected object. It means that different image may have differe...
ptrblck
You could return the targets as e.g. a dict as is also done inthis tutorial.
spadel
I have a tensor with shape[bn, k, 2]. The last dimension are coordinates and I want each batch to be sorted independently depending on the y coordinate ([:, :, 0]). My approach looks something like this:import torch a = torch.randn(2, 5, 2) indices = a[:, :, 0].sort()[1] a_sorted = a[:, indices] print(a) print(a_sorte...
ptrblck
This should work: a = torch.randn(2, 5, 2) indices = a[:, :, 0].sort()[1] a_sorted = a[torch.arange(a.size(0)).unsqueeze(1), indices] print(a) print(a_sorted)
maze09
Hi everyone,I got 4D logit value matrices with the shape (batchsize, classes (e.g. 9 logit values if number of classes ==9), height, width) and the assigned class matrices (label matrices) which are 3D and has the shape (batchsize, 1 (which are the indices of the true class), height, width). How can the logits values c...
ptrblck
You could use the gather operation and filter out the specific values afterwards: logits = torch.randn(2, 3, 4, 4) target = torch.randint(0, 3, (2, 4, 4)) res = logits.gather(1, target.unsqueeze(1))
marcocarobene
Hi all,I’m encountering an unexpected difference in the value of two tensors before and after addition.I have received the following tensor from a Linear layer:x = torch.tensor([ 0.2163, -0.1675, -0.0950, -0.1593, -0.0628, -0.3286, 0.0187, -0.2372, -0.1530, 0.2945, 0.0602, 0.1602, -0.0701, 0.0301, -0.0220,...
ptrblck
This small error is expected due to the limited floating point precision. As explained inthis Wikipedia article for single precision floats, the precision limitations of decimal values are defined as: Decimals between 2**n and 2**(n+1): fixed interval 2**(n-23) For your output n would be 19, sin…
neuralpat
Hi,I’ve seen a lot of threads about similar issues, but unfortunately none of them helped me resolve mine.I’m trying to generate news headlines, with a character-level RNN.I have the following model:class HeadlineModel(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(HeadlineModel...
ptrblck
nn.CrossEntropyLoss for a mutli-class classification on a temporal sequence expects the model output in the shape [batch_size, nb_classes, seq_len] containing logits, while the target should be passed as [batch_size, seq_len] containing the class indices in the range [0, nb_classes-1].
krliczki
Hi,I tried to utilize the following topic:Best way to convolve on different channels with a single kernel?autogradYou could repeat the single kernel and use the functional API: x = Variable(torch.randn(1, in_channels, 100)) # Gaussian kernel kernel = Variable(torch.FloatTensor([[[0.06136, 0.24477, 0.38774, 0.24477, 0...
ptrblck
You could permute the result tensor as seen here: conv_out = (F.conv1d(data_reshaped, torch_kernel, padding=padding_value, bias=None) / torch_kernel.shape[2]) ret = conv_out.view(torch_data.shape).permute(0, 2, 1) print(ret) > tensor([[[1.0000, 1.0000], [2.0000, 2.0000], [3.00…
normster
Hi,I’m trying to run some code which requires an older version of pytorch (v1.1.0) on an RTX 3090 card and sending anything to the gpu hang for a really long time. I know this is to be expected since the GPU and software compute capability differ in the major version (7.5 vs 8.6) but is there anything I can do about th...
ptrblck
The “hang” you are seeing is most likely the JIT compilation for the (new) GPU architecture. In PyTorch 1.1.0 CUDA>=11.0 wasn’t released yet, so you would need to cherry-pick all CUDA11 commits to this branch and recompile it. I think the easier way would be to update the PyTorch code base and use…
ryunosuke0723
I am converting y (shape [1,6]) and output and x ([1,64]) to float type respectively, but I get an error.Is the conversion method wrong?error messageTraceback (most recent call last): File "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet-master/bindsnet/nextrsnn.py", line 95, in <module> optimizer.zero_grad(); ou...
ptrblck
I’m not sure where this error is coming from as your model definition isn’t posted. Check the complete stack trace and see, if you can spot the line of code which raises the error. Based on the posted error message e.g. a matrix multiplication might fail with the shape mismatch e.g. in a linear la…
ryunosuke0723
I implemented this cord. But error occurred about the size of tensor .Where should I fix it and what does it mean this error ?Could someone teach me? pleaseerror messageTraceback (most recent call last): File "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet-master/bindsnet/nextrsnn.py", line 88, in <module> netw...
ptrblck
Since you are using nn.CRossEntropyLoss or nn.NLLLoss (based on the stack trace), I assume you are working with a multi-class classification. Based on the output shape of the model, the current batch contains a single sample with logits for 6 classes. If that’s the case, the target should have the …
ryunosuke0723
I created a neural network using the logistic regression implemented by pytorch as a model, but the accuracy is low.I want to know the cause. So Where should I check ?import torch import torch.nn as nn import numpy as np from bindsnet.network import Network from bindsnet.network.nodes import Input, LIFNodes from bindsn...
ptrblck
No, if your current model and training routine cannot overfit the small dataset, then there might be some other issues in the code or the model is not suitable for this use case and you would need to modify its architecture.
oat
May I ask why PyTorch’s autograd willaccumulate gradients, ifoptimizer.zero_grad()is not called?What is an example of the use case of cumulated gradients?Thanks.
ptrblck
You could simulate a larger batch size by accumulating the gradients of smaller batches and scaling them with the number of accumulations. This can be useful e.g. if the larger batch size would be beneficial for training but doesn’t fit onto your GPU. Accumulating the gradients gives you the abilit…
Hacking_Pirate
Hi,I am creating a model for image classification but getting this error:Given groups=1, weight of size [40, 3, 3, 3], expected input[16, 32, 33, 5] to have 3 channels, but got 32 channels insteadI am using an efficientnet_b3 model.Here is my dataset class:class HolidayDataset(Dataset): def __init__(self, train_pat...
ptrblck
The error is raised by an nn.Conv2d layer, which expects an input with 3 channels, while it seems you are trying to pass an input tensor with 5 channels (in a wrong memory layout) to this layer. Assuming my assumption is correct and your input contains 5 channels, you would have to first permute it…
Hacking_Pirate
Hi,I was trying to create a denoising AE, but as I was training it I got some size error eventhough both clear and pixelated images have same size.Here is model Arch:############### MODEL ################ class AutoEncoder(nn.Module): def __init__(self): super(AutoEncoder, self).__init__() self.encoder = nn.S...
ptrblck
Your model works fine with an input of [batch_size, 3, 128, 128]: model = AutoEncoder() x = torch.randn(2, 3, 128, 128) out = model(x) print(out.shape) > torch.Size([2, 3, 130, 130]) so I guess the shape of your model output doesn’t match the target shape. If that’s the case, you would have to ch…
Johannes_L
Hello everyone,I have a short question regarding RNN and CrossEntropyLoss:I want to classify every time step of a sequence. For this I want to use a many-to-many classification with RNN. So I forward my data (batch x seq_len x classes) through my RNN and take every output. My target is already in the form of (batch x s...
ptrblck
This would be the expected shapes for the “standard” multi-class classification use case, but as described inthe docsthe expected tensor can have additional dimensions (d1, d2, ... , dk). For your use case you could thus use the model output as [batch_size, nb_classes, seq_len] and the target as…
Preetham_R_Patlolla
I’ve been trying to develop an Autoencoder model for the task of knowledge representation where my input is a sequence of images. Loss of this model (both training and testing) doesn’t decrease. It is instead fluctuating and of course, my image reconstruction is very poor. I’ve tried the following:Changing the learning...
ptrblck
You could start by overfitting a small dataset (e.g. just 10 samples) by playing around with the hyperparameters (optimizer, learning rate etc.). If that doesn’t help, I would suggest to simplify the model. Once your can come up with a model and hyperparameters, which overfit this small dataset, y…
mohit117
Hello,I created a fresh conda environment and ran the following code,conda install pytorch torchvision torchaudio cudatoolkit=10.0 -c pytorchon ubuntu 16.04 LTS. Why did this install pytorch version 1.4.0 and not the latest pytorch 1.7.1?I want to install the latest version.
ptrblck
The CUDA drivers are needed to run the CUDA runtime, which ships with the PyTorch binaries. For the latest PyTorch version you can install the CUDA runtime in version 9.2, 10.1, 10.2, and 11.0 as@InnovAruldescribed.
MalviyaR
In the first run, the code ran well, but from the second run the system has started throwing error in the following:for i, (inputs, labels) in enumerate(datasets[‘test’]):print(labels)datasets[‘test’] has multiple objects mainlydata which is a tensor of size [20000, 32, 32, 3]labels which is an ndarray of size [20000]I...
ptrblck
Thanks for posting the stack trace. It seems normalize raises the shape mismatch error. Could you check how many values you’ve passed to transform.Normalize and the number of channels for each input image? It seems that you might have used two values for the mean and std in Normalize while your i…
wheresmadog
Hi, I’m trying to train a binary classifier where 64x64x3 images are as inputs. But the model only outputs close to 0. I also, found that the parameters before and after training differ, that is, gradient updates anyway.Is there anything else I should try?def fn_fit(self, optimizer, loss_fn, batch_size=16, epochs=10, l...
ptrblck
Try to overfit a small dataset, e.g. just 10 samples, by playing around with the hyperparameters. Once your model is able to do so scale up the use case again.
steve_moody
If I understand it correctly, the Tensor size for an RNN is:(batch_size x sequence_length x n_features)batch_size: total segments to handlesequence_length: number of time steps to unrolln_features: dimension of a one-hot-encoded vector of the vocab size.I’ve got a dataset with 73461 total chars and a vocab size of 52. ...
ptrblck
This line of code increases the batch size, which would be wrong: out = out.reshape(-1, self.hidden_dim) Depending on your use case, you might want to pass the last time step to the linear layer via: out = self.fc(out[:, -1, :]) instead or reduce the temporal dimension in any other way.
Mendel123
I have a tensor with shape [2,3] and I want to expand it to [4,3].If I usetorch.expanddirectly, a error occurs.>>>x tensor([[4., 5., 6.], [1., 2., 3.]]) >>>x.size() torch.Size([2, 3]) >>>x.expand(4,3) RuntimeError: The expanded size of the tensor (4) must match the existing size (2) at non-singleton dimension 0...
ptrblck
Yes, from thedocs: Returns a new view of the self tensor with singleton dimensions expanded to a larger size. […] Any dimension of size 1 can be expanded to an arbitrary value without allocating new memory. You could use x.repeat(2, 1) for your use case. Note that this operation would alloca…
SHAW1213
I’m using the fashion_mnist to practice. I built a network with 2 conv layers and 2 fc layers, it works, but when i added the number of conv layers to 5, it doesn’t work. The error message is the same as the title…The code is above, I really hope for your help :transformer = transforms.Compose([transforms.ToTensor()]) ...
ptrblck
Replace x = x.reshape(-1, 1600) with x = x.view(x.size(0), -1) to keep the batch size constant and you would most likely get a shape mismatch error in the following linear layer (and should adapt the in_features of it).
Giuseppe
Hy all, when i run project in linux it works, when i run in windows it doesn’t work. (now i am unable to use linux at the moment)When i run i have this error:Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\GIUSEPPEPUGLISI\anaconda3\lib\multiprocessing\spawn.py", line 116, in ...
ptrblck
Ha, I thought you might have overlooked the suggested fix.Have a look at theWindows FAQ, where the if-clause protection is given as a code snippet: import torch def main() for i, data in enumerate(dataloader): # do something here if __name__ == '__main__': main()
PLarsen79
Say I want to run a forward pass through the network, using a batch-size of 256, and before backprop I would want to weight the losses across the batch input/target sequences, is that possible and what would be the best practise?It’s not a solution for me to do preproccessing and collect input/target sequences that wil...
ptrblck
You could use an unreduced loss via reduction='none' in the creation of the criterion and multiply the weight matrix with the loss tensor before reducing it and calling backward.
Hoodythree
I’m trying to reimplement a paper about bilinear pooling(Link hereHierarchical Bilinear Pooling). So I need to get the intermediate output of some convolutional layers. But when I tried this with DenseNet121, I found that it’s difficult to do that as the forward pass of DenseNet is quite different with VGG or ResNet. F...
ptrblck
Wrapping the child modules into nn.Sequential containers might not work for a lot of modules, as they might use functional calls in their original forward method, which would be lost. You could derive a new model and manipulate the forward method instead (unsure, what kind of errors you were gettin…
maikefer
Since it is misisng in the docu (https://pytorch.org/docs/stable/backends.html) I’m wondering what is the default value of torch.backends.cudnn.enabled or does it depend on special things like PyTorch version, hardware etc?
ptrblck
If cudnn is available (which is the case for the binaries shipping with CUDA+cudnn), it’s enabled by default and you can check it via print(torch.backends.cudnn.enabled).
UCDuan
Hi all,I’m using Captum to do the integrated gradient for an LSTM model. If I just load the model and the weights, it showscudnn RNN backward can only be called in training mode. I tried to remove model.eval() but it doesn’t give the correct result.I also tried to put all the data and model to CPU and it works fine, bu...
ptrblck
It’s a limitation from the cudnn implementation. From thecudnn docs: fwdMode Input. Specifies inference or training mode (CUDNN_FWD_MODE_INFERENCE and CUDNN_FWD_MODE_TRAINING). In the training mode, additional data is stored in the reserve space buffer. This information is used in the backward p…
Hassan_Imani
I converted my code from keras to pytorch. It is a regression task with 3D CNNs.I used just one thread in keras, but in pytorch I am using 16 threads.Can this issue be the reason for the increase of my loss?I am using SGD optimizer and MSE loss function.
ptrblck
If the initialization adaption didn’t help, you could try to load the Keras parameters into the PyTorch model and make sure the same (random) input creates the same outputs. If that’s the case, the difference should come from the preprocessing.
PLarsen79
I am looking for an efficient way of manual editing embedding weights, in between forwards-backprop-iterations.Say I have three embeddings, example:self.tok_embA = nn.Embedding(config.vocab_size, config.n_embd) self.tok_embB = nn.Embedding(config.vocab_size, config.n_embd) self.tok_embC = nn.Embedding(config.vocab_size...
ptrblck
The easiest way would be to apply the loop and manipulate the parameter using all conditions. It’s hard to tell if and how these operations might avoid the loop without seeing the condition, but you might be able to use e.g. a mask.
zhaizhaizhai
here’s the code:x_real.requires_grad_()out = nets.discriminator(x_real, y_org)loss_reg = r1_reg(out, x_real)def r1_reg(d_out, x_in):# zero-centered gradient penalty for real imagesbatch_size = x_in.size(0)out =d_ out.sum().requires_grad_()grad_dout = torch.autograd.grad(outputs=out, inputs=x_in,create_graph=True, retai...
ptrblck
I cannot find any obvious issues by skimming through the models. Try to add print statements into the forward methods of all models and check, if the activations have a valid .grad_fn via print(x.grad_fn). At one point in a model the statement should return None and the previous operation would de…
RobinMaaas
Hello all,I have built the following CNN and was able to train it successfully (Validation Loss and Acc: 0.0081/0.9991).However, I have sometimes (about 50 percent, but once it occurs always x times in a row) the problem that the CNN does not learn at all, it then remains at a loss of around 3.8 and an accuracy of abou...
ptrblck
Your training seems to be instable and thus sensitive to the random seed. Sometimes using other parameter initializations might help stabilizing the training overall.
Siddhesh_Mhatre
Hi,I have compiled pytorch on a machine that has an Nvidia GPU with cuda capability (cc) 7.5. I tried using the same compiled libraries on machine that has an Nvidia GPU with cc of 6.1 and it worked, but I got the following errorCUDA error: no kernel image is available for execution on the devicewhen I tried to use th...
ptrblck
I guess you haven’t used PTX and only built PyTorch for sm_75. You could use TORCH_CUDA_ARCH_LIST="6.1 7.5" python setup.py install to build for both architectures. You can also add +PTX after each architecture to ship with PTX.
Rajan_Lagah
reward = 3 def custom_loss(outputs,target): outputs = F.softmax(outputs,dim=1) outputs, reservation = outputs[:,:-1], outputs[:,-1] gain = torch.gather(outputs, dim=1, index=target.unsqueeze(1)).squeeze() return lossI am trying to implement custom loss but it was giving runtime cuda err...
ptrblck
The stack trace might point to an invalid index and you could rerun the code via: CUDA_LAUNCH_BLOCKING=1 python script.py args to see if this is indeed the line of code raising the error. Also, if you run the code on the CPU you might get a better error message.
HDB
Hi, a question confused me for a long time. When I use batch gradient descend in pytorch, the allocated memory of gpu accumulates with the number of training within on batch. I failed to find where the mistake is, someone can help? Thank you very much. Some information below is the output of my code.No.0*allocated mem...
ptrblck
This increase in memory usage is often due to (accidentally) storing some tensors, which are attached to the computation graph, and thus the complete graph with it. Could you check, if you are adding the model output, loss, or any other tensor with a valid .grad_fn to a list or any other container …
bayes_and_blues
I’m currently working on porting code from Keras to PyTorch. I’m working with many GPUs and CPUs so it’s important to have batch generation happening in parallel. My problem is that I’m trying to use the num_workers argument on the DataLoader class, but am meeting with errors. Current relevant toy code:import torch t...
ptrblck
Based on the first post I assume that your code runs fine with num_workers=0 for the full epoch and doesn’t yield any error? If that’s the case, could you check if you have enough shared memory available?
ptrmcl
So I have this tensortof size a x b x cI have another tensoruof size a. Each element ofuis an index of the element I want fromt’s second dimension. So I want to apply the mask and get something that’s a x c.How can I do this? Please let me know if I can provide any clarifications.
ptrblck
This code should work: a, b, c = 2, 3, 4 t = torch.arange(a*b*c).view(a, b, c) print(t) > tensor([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) u = torch.tensor([0, 2]) res = …
Wesley_Neill
This is counter-intuitive but there is a reason. I know parallel processing through batches is what makes DataLoaders great.I designed a general purpose (I thought) method that accepts an autoencoder and aDataLoaderand trains it.Now I’m working on a new model that exclusively usesLSTMCells, which it looks like don’t ac...
ptrblck
I’m not sure I understand the use case completely, but you could set batch_size=1 to get single samples in each batch (and remove the batch dimension if needed). Would this work for you? If not, could you explain what “removing batching” would mean?
wasabi
Hi guys. I’m trying to create multiple dataloaders using a for loop, and each of them uses a different transform. However, I notice that they always pick the transform of the last iteration.train_loader = np.empty((2), dtype=np.object) for i in range(2): train_loader[i]= torch.utils.data.DataLoader( torchvisi...
ptrblck
This issue is created by the wrong usage of i inside the lambda definition, you would need to bind i for each created function. This should solve the issue: train_loader = np.empty((2), dtype=np.object) for i in range(2): train_loader[i] = torch.utils.data.DataLoader( torchvision.dataset…
Silvester98
I have a list like[x1, x2, ..., xn], andxiis a Tensor with sizetorch.Size([2, 3]), how to convert this list a Tensor with sizetorch.Size([n, 2, 3]). I am looking for an elegant method. Thanks for your reply.
ptrblck
You could use torch.stack: n = 10 l = [torch.randn(2, 3) for _ in range(n)] t = torch.stack(l) print(t.shape) > torch.Size([10, 2, 3])
ydcjeff
As of today, we can use long, byte or bool tensor as indices. but indexing with byte tensor is deprecated.But indexing with longtensor doesn’t give same answer as indexing with booltensor.x = torch.rand(3, 3) >>> x tensor([[0.0857, 0.9867, 0.0330], [0.9295, 0.9787, 0.4835], [0.9376, 0.3851, 0.8934]]) y ...
ptrblck
Yes, this is expected behavior and e.g. explained innumpy - integer array indexingandnumpy - boolean array indexing.
Toby
When I run my program and notice that it’s so slow. I try to compare the processing time in train and eval mode by this simple scriptimport time for (image, target) in dataloader: image, target = image.to(device), target.to(device) b_size = image.size()[0] model.train() t1 = time.time()...
ptrblck
If you are using a GPU, you would have to synchronize the code before starting and stopping the timer via torch.cuda.synchronize() as the timings would be wrong otherwise.
ljh
Hi! I was constructing a multilayer LSTM by stacking a bunch of LSTM in an list.I found out that when I’m using the python list, the loss is weird.But when I’m using the nn.ModuleList(), it’s just normal.So why can’t I use the python list? Do I have to use nn.Modulelist()?Here’s the code and loss when using nn.Moduleli...
ptrblck
Plain Python lists won’t register the module properly, so that e.g. model.parameters() will not return the internal parameters of the submodules in this list (and thus your optimizer won’t get them). You shoud use nn.ModuleList instead as described in thedocs.
111439
Hi, I have a neural network the last last layer of which is Sigmoid, but the output of my model(input) contains values that are out from [0…1] range. Sorry, I am new in pytorch so I am not familiar with all pipelines. Could you please tell me, should I apply the sigmoid separately? If so, why it is shown in the neural ...
ptrblck
Thanks for the update. Have you set the self.testing argument to True, as the last activation wouldn’t be used otherwise as seenhere?
seyeeet
i seefrom torch.modules.utils import _single, _pair, _triplewhat does_pair,_single, and_triple, do?
ptrblck
These are internal methods (marked via the underscore at the beginning), which repeat some arguments if necessary. E.g. for nn.Conv2d you can pass the kernel_size as a single integer or as a tuple. In the former case, the tuple will be created via _pair inthis line of code. So it’s used for conv…
LanceVance
I am working on semantic segmentation of electric motors. My masks contain 7 classes (including background) encoded as RGB colors.I use the following code which is based onthispost:import torch import numpy as np import cv2 import matplotlib.pyplot as plt h=256 w=256 #Loading mask mask_img = cv2.imread('input/labe...
ptrblck
The mask tensor is initialized via torch.empty, which uses uninitialized memory and thus random values. Based on the output of torch.unique(mask) it seems you haven’t set all values in the mask and thus the last value is coming from the uninitialized memory. Could you check where this index is use…
Vivek_Reddy
Hello everyone,I encountered an error when trying to define a custom dataset for the PyTorch dataloader.I want to read in an image from the image path, generate the label from the image path, and return the image and label. Below is my code for the dataset.class Non_ImageFolder_Dataset(Dataset): def __init__(sel...
ptrblck
Since the error is raised by tiffile, it seems that the TIF image is indeed somehow “broken”. Could you check which index is used in the dataset by iterating it and check the file manually?
ptrblck
No, I was thinking about e.g.:nb_classes = 10 batch_size = 64 target = torch.arange(0, nb_classes) random_targets = torch.randint(0, nb_classes, (batch_size - nb_classes, )) target = torch.cat((target, random_targets))assuming the batch size is larger than the number of classes. Otherwise you won’t be able to sample e...
ptrblck
torch.cat will return a tensor, so it seems you haven’t used it to create all_classes, have you? Could you post an executable code snippet showing your use case and explain what results are expected?
Niu
For example:Feature is [B,C,H,W], I have weights of [B,C], I want to rearrange feature in Channel dimension with descending weights for per image. My code is as follow:I want to know that there is a more elegant way to operate all channels at the same time?Earnestly hope !import torch feature = torch.rand(4,6,3,3) weig...
ptrblck
You could directly index the tensor as seen here: feature = torch.rand(4,6,3,3) weight = torch.rand(4,6) _, indices = torch.sort(weight, dim=1, descending = True) z1 = feature[0,indices[0],:,:] z2 = feature[1,indices[1],:,:] z3 = feature[2,indices[2],:,:] z4 = feature[3,indices[3],:,:] z = torch.st…
tomcc
Hello I am currently constructing ensembled methods and is wondering how i should save them.For this example, taken fromhereclass MyEnsemble(nn.Module): def __init__(self, modelA, modelB, nb_classes=10): super(MyEnsemble, self).__init__() self.modelA = modelA self.modelB = modelB # R...
ptrblck
It depends how you would like to reload and use these models afterwards. E.g. if you only care about the two submodules and would like to use them afterwards, the first approach would work. Note that you would lose the self.classifier as it’s a module in MyEnsemble. In the latter case, all paramet…
JamesDickens
If I have an iterable dataset (loading tf records of images and bounding boxes), and I wish to repeat the dataset epoch after epoch, my code before realizing a problem was:for epoch_num in range(epochs):data_iterator = iter(data_func(*data_args))for batch in data_iterator:/// training stuffThe issue with this approach ...
ptrblck
You could use persistent_workers=True in the DataLoader creation and iterate it directly via: for batch in loader: ... which will make sure to keep the workers alive.
Tomash
Hi,I got an error like in the tittle and it sounds easy (I wonder that I just need to change type of loaded data) but I have a problem with that… I changed types but error still appears.In my main function:inputs = load_images(glob.glob(args.input)) outputs = predict(model, inputs)def load_images(image_files): load...
ptrblck
This error might be raised, if your model parameters are in float32 while the input is in float64. Based on your code snippet you are indeed passing the input as DoubleTensors (float64) so you would need to make sure the model parameter have the same dtype via model.double(). Alternatively, you co…
sunfishcc
Background:I’m working on an adversarial detector method which requires to access the outputs from each hidden layer (Local Intrinsic Dimensionality Detector - a.k.a.: LID).I loaded a pretrained VGG16 fromtorchvision.models.To access the output from each hidden layer, I put it into a sequential model:vgg16 = models.vgg...
ptrblck
VGG16 uses dropout layers, which will be disabled when model.eval() is used and which explains the difference during the model.train() comparison.
JamesDickens
I just updated from pytorch 1.7.0 to 1.7.1 using anaconda and I seem to no longer be able to seetorchvision.models.detectionor torchvision.opsHow do I access these modules? Maybe my install was bad?How can I revert back to Pytorch 1.7.0
ptrblck
Based on the output it seems your torchvision version was downgraded to 0.2.2: torchvision {0.8.1 (pytorch/win-64) -> 0.2.2 (pytorch/noarch)} and I’m unsure why this would happen. Could you create a new virtual environment and reinstall the latest lib versions? I would generally recommend to upd…
hadaev8
So, batch.flip(2) works fine, but how to flip only half of it?
ptrblck
Yes, your code looks good and seems to work fine: batch = torch.cat((torch.zeros(4, 2, 4, 2), torch.ones(4, 2, 4, 2)), dim=3) print(batch) perm = torch.randperm(batch.size(0)) idx = perm[:batch.size(0)//2] batch[idx] = batch[idx].flip(3) print(batch)
L-Reichardt
Hello,For a Project I am using the Sparsity-Invariant Convolution which is implemented in a class. The dilation rate is an input into this class, so would have to be set when initialized.Within a Model-Block, I want to use this convolution 3 times in parallel, with differing dilation rates. Is it possible to lock the w...
ptrblck
Yes, weight sharing is possible and a simple approach would be to use the functional API by defining the filters and bias as nn.Parameters and apply them via F.conv2d using the different dilation rates.
Alpha
Is there a table which shows the supported cuda version for every pytorch version?Thanks.
ptrblck
If these 3rd party packages are shipping with CUDA kernels, then you would need to install a local CUDA toolkit, yes.
seankala
Hi everyone. I’m trying to implement the elastic averaging stochastic gradient descent (EASGD) algorithm from the paperDeep Learning with Elastic Averaging SGDand was running into some trouble.I’m using PyTorch’storch.optim.Optimizerclass and referencing theofficial implementation of SGDand theofficial implementation o...
ptrblck
This line of code: p = p - self.alpha * (x_normal - x_tilde) would create a non-leaf tensor, so that the following p.grad call would raise this warning. Based on your code I think you should new a new variable name for this assignment and keep p pointing to the parameters in the optimizer. Also,…
dmdmello
Hi. I’m using pytorch 1.7 and getting a very slow training speed with my new rtx 3070 whenever I enable torch.cuda.amp.autocast (2x slower).From what I’ve read, this problem should be solved in 1.7.1, because it incorporates the newer cudnn versions, right? Are there any hopes for it’s stable version being available un...
ptrblck
cudnn8.0.5 ships with the updated heuristics for the 3090 and cudnn8.1.x will cover the complete 30xx series. You could try out the nightly PyTorch build, which already uses cudnn8.0.5 and check, if the performance is improved.
Wesley_Neill
I’m coding a timeseries autoencoder that reconstructs the elements of the input reverse order, one at a time. I’m using thetorch.catoperation to concatenate each element back into sequence form.# reconstruct remaining elements for i in range(1, self.seq_len): hs_i, cs_i = self.cell(x_i, (hs_i, cs_i)...
ptrblck
Yes and by default the torch.cat operation is tracked, so based on your description you would append the outputs of the model with the complete computation graph and would then backpropagate through all these outputs and the model.
Lau
Hi!I am trying to combine two pre-trained models. Unfortunately, I get the error message specified in the title, and I do not understand. it Could you please help me figure out what am I doing wrong?Thank you very much!class Net(nn.Module): def __init__(self): super(Net,self).__init__() sel...
ptrblck
I would not recommend to wrap random models into an nn.Sequential container, since you would lose all operations from the functional API in the forward method. While your approach might work for the resnet, the densenet would missthese ops. The better way would be to either derive your custom mod…
matthias.l
Hi, looking at the exampleextension-cpp.I am wondering why you allocate memory for the output tensors each time you call forward or backward.Sure, for the forward case you could provide an output tensor.But for the backward case this is not possible without bad hacks.Does PyTorch internally take care that old output te...
ptrblck
PyTorch uses a caching allocator and reused already allocated memory. I think the code tries to focus on readability of the code and as you said, these small perf. gains are sometimes not possible without bad hacks.
dkoslov
Hi there, I tried to export a small pretrained (fashion MNIST) model to ONNX for test cases and evaluated the results. The outputs were completely differnt and I already tried different solutions which did not help to solve the problem.I spent weeks on finding a solution to this error - may you please help me?Here are ...
ptrblck
Could you test the PyTorch and ONNX model with a constant input, e.g. torch.ones, and check if the result still differs? If not, I guess the preprocessing of the input data might be different, which would also change the model outputs.
ooyamatakehisa
pytorch.orgtorch.nn.functional — PyTorch 1.7.0 documentationThere is no note in the description of avg_pool1d on this page that says "may choose a non-deterministic algorithm, so this function is deterministic?The function conv1d, which is similar to avg_pool1d, has its Note, so please tell me what avg_pool1d is doing....
ptrblck
As described in the note for F.conv1d cudnn might non-deterministically pick a kernel or the kernel itself might yield non-deterministic results, which is not the case for the pooling layer.
oat
Assuming the following forward pass: x → y → z, in whichx is a scalary = x * xz = 2 * yI want to track the following derivatives/gradients, including the gradient for the intermediate function y:dz/dy, gradient of z with respect to y, which should be “2”dy/dx, gradient of y with respect to x, which should be “2x”dz/dx,...
ptrblck
Your code should raise a warning and explain the reason and workaround for it: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .ret…
Mona_Jalal
Do you know how I can fix this error? I am following all the instructions as shown in this git repo:github.comyinyunie/Total3DUnderstandingImplementation of CVPR'20 Oral: Total3DUnderstanding: Joint Layout, Object Pose and Mesh Reconstruction for Indoor Scenes from a Single Imagefull log accessible herehttps://pastebin...
ptrblck
Double post fromhere.
AleTL
Hello,I’m working with an autoencoder and I want to visualize the output and the original image. I already did it but my problem is that everytime the images are plotted, are different images, so I cannot make a visual comparison of the improvement.My code is next:# training and so on for batch_features, _ in train_loa...
ptrblck
I guess you might be shuffling the data in your training DataLoader, which would thus yield random samples in all batches. If you want to use the same image, you could directly get it by indexing the dataset via: data, target = train_loader.dataset[index].
dav_n
Hi everyone,I’m trying to understand what .backward() does when called, in terms of types of involved tensors (during computation). I am running the following code:—Before training code:net.to(‘cuda’)net.half() # 16 bit net—Training code (first part):outputs = net(inputs) # 16 bitloss = criterion(outputs, tar...
ptrblck
Yes, the dtype would be recorded by Autograd and the backward computation would be executed in the same precision as its forward part, if you don’t change it. This would also mean that your FP16 gradient updates might easily underflow, which is why we recommend to use the mixed-precision training u…
egundogdu
Most people struggling nans at the output know that when you feed nan or zero input to the model which has layers such as batchnorm, then the model may become broken. During the training, if you do not do backward pass, the model does not break down. However, since you already did a forward pass with these undesired i...
ptrblck
I’m not aware of any other approaches that to make sure these invalid values are filtered out (e.g. via torch.isfinite(input)).
yoad.tewel
HeySo I saw this post:Rtx 3070 slower with mixed precision autocast in pytorch 1.7, where@ptrblcksaid:Rtx 3070 slower with mixed precision autocast in pytorch 1.7cudnn8.0.5 ships with the updated heuristics for the 3090 and cudnn8.1.x will cover the complete 30xx series. You could try out the nightly PyTorch build, whi...
ptrblck
The nightly release is tagged with the date e.g. as: 1.8.0.dev20201109 You might see more issues, as the nightly will be rebuild every day from the current master branch. That being said, I don’t have the feeling that the nightly is terribly unstable. Yes You can use the install command from thew…
sunshichen
I’m using DDP(one process per GPU) to training a 3D UNet. I transfered all batchnorm layer inside network to syncbatchnorm withnn.SyncBatchNorm.convert_sync_batchnorm.When doing validation at the end of every training epoch on rank 0, it always freeze at same validation steps. I think it is because of the syncbatchnorm...
ptrblck
Could you update to the latest stable release or the nightly binary and check, if you are still facing the error? 1.1.0 is quite old by now and this issue might have been already fixed.
eric_2_hamel
I want to do a binary boundary losses inspired fromhttps://github.com/JunMa11/SegLoss/blob/master/losses_pytorch/boundary_loss.pyandhttps://arxiv.org/abs/1812.07032. I have seen the use ofwith torch.no_gradin forward method in loss. I am not sure how torch.no_grad is recommended in the forward method. Since it is done...
ptrblck
If you need to call a numpy method e.g. since there is no corresponding method in PyTorch, your workflow is correct. The no_grad() wrapper wouldn’t change anything, which was the initial question, since Autograd won’t track any numpy operations. You can still use the processing in the forward metho…
L-Reichardt
Hello,i have made modifications to a model, expanding it with multiple attention mechanisms. 80% of the model is the same as the previous version. Is it possible, to take the pretrained weights of the previous version, and insert them where applicable?Ive trained the new model for 1 epoch, saving the weights (checkpoin...
ptrblck
Manipulating the state_dict sounds like a valid approach, if you’ve changed some parameters (e.g. in their shape). On the other hand, if you’ve added or removed parameters, you could try to use load_state_dict(sd, strict=False) to ignore missing or unexpected keys.
vishak_bharadwaj
Any general guidelines both space and time wise as to which frameworks are best suited in the various stages of MLAre there any guidelines as to why transforms, for example, shouldn’t happen on the GPU but on Pytorch CPU. If Pytorch CPU is slower than Numpy, then why not code the transforms up in Numpy.
ptrblck
I would claim it all depends on your use case and there is no silver bullet. By default you would want to use the GPU to train the model and the CPU to load and process the data. Using multiple workers in the DataLoader the data loading and processing will be applied in the background, while the GP…
pgp
Tan of shear factors is taken inget_shear_matrix2dfunction. It changes the shear factor from what is expected. What is the reason behind using tan in shear?
ptrblck
I assume it’s the general formula for the shear matrix as described inthis simple example.
grizzlycoder
In my model, I take two tracks (track1, track2) and I have an interaction label (1 or 0). In the training epoch, when I print my target I get something like torch.tensor([1,0]) or torch.tensor([0,0]) etc.How does it convert my single number into a 2d vector of different values? I’d imagine label 1 becomes [1,1] and lab...
ptrblck
I’m not sure how to understand the question as you are defining the model architecture and are responsible for the interpretation of the model output. Based on your description I guess you are using two output neurons, apply a sigmoid on them, and are dealing with a multi-label classification use ca…
Bakri
Hello,I’m trying to implement neural networks pruning strategies, the code was working fine until I converted it from numpy to pytorch (only the pruning part) to leverage GPU speed.The code isThe function that does the sparsification:def magnitude_pruning(A, drop=0.2): if drop<0: drop=0 shape_a = A.shape n_el...
ptrblck
Thanks for the follow up! This is indeed a bug and should be fixed. I’ll create an issue later to track it.
Karan_Chhabra
Hi,I was trying to use the cosineAnnealing Learning rate but I was confused about what should be theT_maxparameter be.Whether it should benumber of epochs,length of train_loaderor multiple of the two?torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max,eta_min=0,last_epoch=-1,verbose=False)
ptrblck
Thedocsgive you the applied formula and show how T_max is used. In particular it’s used to divide the current epoch by its value, which would thus anneal the change in the learning rate and end with the max. learning rate. CyclicLR cycles the learning rate between two boundaries with a constant f…
krishnab
Hey Folks, I was just trying to understand the PytorchEmbeddinglayers. I am creating an time-series prediction model using an LSTM, but I also have some categorical information that I want to include in the model. I have some time series variables, such as the year, month, week number, and day, as well as some spatial ...
ptrblck
You could feed the data as a single tensor to the nn.Embedding layer. However, I would use separate embeddings, as your input data would have completely different ranges. nn.Embedding layers accept inputs containing values in [0, nb_embeddings-1]. If your year data contains values in e.g. [1988,…
pyxiea
A similar problem on stackoverflowis here, but no answer is useful.Asthis tutorialshown, the output of multi-gpus will be concatenated on the dimension 0, but I don’t know why does it not work in my code.model = T2T(......) # T2T is a sub class of nn.Module if torch.cuda.device_count() > 1: print("Using", ...
ptrblck
This tensor won’t be split, as dim0 has only a single sample and thus only a single GPU will execute this tensor. If you want to make sure each GPU gets a chunk of the input tensor, make sure dim0 has at least a size of num_gpus.
Muhammad4hmed
Hi, I am trying to run following network:class CustomVGG16(torch.nn.Module): def __init__(self): super(CustomVGG16, self).__init__() self.vgg = torchvision.models.vgg16_bn(pretrained = True) self.vgg.classifier[-1] = torch.nn.Linear(4096,25) self.softmax = torch.nn.Softmax() ...
ptrblck
Remove the softmax and the torch.argmax. Also, if your target is one-hot encoded, I assume you are dealing with a multi-class classification, so replace nn.BCEWithLogitsLoss with nn.CrossEntropyLoss.
kaas
class text_CNN(nn.Module): def __init__(self): super(text_CNN, self).__init__() self.conv1 = nn.Conv1d(in_channels=1, out_channels=10, kernel_size=2) def forward(self, x): print(x.type()) x = F.max_pool1d(F.relu(self.conv1(x)), 2) return x model = text_CNN() x = torch.randint(2, (16, 1, 22)) m...
ptrblck
The error message might be confusing as the data type mismatch points to one of the used tensors. Based on the error it seems that the first tensor (input in this case) is used as the expected type.
turian
I have read this post and understand about root nodes:Grad is None even when requires_grad=TrueI have followed its advice but I still get gradient of NoneHere is the code I run:import os import torch import torch.tensor as T from fairseq.models.wav2vec import Wav2VecModel MODEL = "wav2vec_small.pt" fname = MODEL os.sy...
ptrblck
You are rewrapping the input in a new tensor, which will break the computation graph and thus your input won’t get any gradients in this line of code: model.feature_extractor(torch.tensor(x.view(1, -1))) Use this instead and it should work: model.feature_extractor((x.view(1, -1)) You should also…
Muhammad4hmed
I’m trying to make a custom vgg16 and the architecture is as follows:class CustomVGG16(torch.nn.Module): def __init__(self): super(CustomVGG16, self).__init__() self.vgg = torchvision.models.vgg16_bn(pretrained = True) self.vgg.classifier[-1].out_features = 25 self.softmax = torch.nn...
ptrblck
Unfortunately that’s not the case, since changing the out_features alone won’t reinitialize the internal parameters. You would have to reassign a new nn.Linear layer to self.vgg.classifier[-1] instead.
GustavoVargasHakim
Hi everyone,I am working on a Neuroevolution project. I am building a model which is composed by several DenseBlocks, however, the skip connections of each of the denseblocks may vary. I tell you all of this to put into context, that the forward pass is built dynamically.My code is the following:'''Networks class''' cl...
ptrblck
Could you check, if all passed arguments are nn.Module objects, i.e. denseBlocks, links, and classifier? It’s unclear from the error message which module is raising this issue and the code looks generally alright. Wrapping the modules in nn.Sequential inside the forward is unusual, but shouldn’t c…
leoentersthevoid
Hi,I trained and saved a model that has two embedding layers.One had a vocab V of ~ 22k items, that were encoded using a latent dimension D of 8.If this is my trained embedding matrix (V x D)tensor([[ 0.6163, 0.9769, 0.3950, ..., 1.2966, 0.3279, 1.4990], [-0.4985, -0.6366, 0.6025, ..., 0.1584, -0.9755,...
ptrblck
The input index is directly used to index the weight matrix as seen here: emb = nn.Embedding(4, 2) x = torch.arange(4) print(emb.weight) > Parameter containing: tensor([[-0.5812, 0.8916], [ 1.9390, -0.6156], [ 0.2126, 0.0578], [-1.1099, 0.0964]], requires_grad=True) out …
AndreaRossi
Hi everyone, I am a bit of a newbie in PyTorch and I have a very basic issue that I am having trouble with.I have two matrices A and B, with different number of rows, but same number of columns.Basically, A and B are different collections of same-sized vectors.What I am trying to do is to subtract each vector in B from...
ptrblck
Broadcasting should work, but would trade memory for a potential speedup: c = a.unsqueeze(0) - b.unsqueeze(1)