instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
How to prune weights less than a threshold in PyTorch? | How to prune weights of a CNN (convolution neural network) model which is less than a threshold value (let's consider prune all weights which are <= 1).
How we can achieve that for a weight file saved in .pth format in pytorch?
| PyTorch since 1.4.0 provides model pruning out of the box, see official tutorial.
As there is no threshold method to prune in PyTorch currently, you have to implement it yourself, though it's kinda easy once you get the overall idea.
Threshold Pruning method
Below is a code performing pruning:
from torch.nn.utils i... | https://stackoverflow.com/questions/61629395/ |
Implementation of the Dense Synthesizer | I’m trying to understand the Synthesizer paper (https://arxiv.org/pdf/2005.00743.pdf 1) and there’s a description of the dense synthesizer mechanism that should replace the traditional attention model as described in the Transformer architecture.
The Dense Synthesizer is described as such:
So I tried to implement... | Is the implementation and understanding of the dense synthesizer correct?
Not exactly, linear1 = nn.Linear(d,d) according to the paper and not (d,l).
Of course this does not work if X.shape = (l,d) according to matrix multiplication rules.
This is because :
So F is applied to each Xi in X for i in [1,l]
The resultin... | https://stackoverflow.com/questions/61630765/ |
No module named 'torch.autograd' | Working with torch package:
import torch
from torch.autograd import Variable
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
w = Variable(torch.Tensor([1.0]), requires_grad = True)
def forward(x):
return x*w
def loss(x,y):
y_pred = forward(x)
return (y_pred-y)*(y_pred-y)
print("my prediction before training",4... | It seems to me that you have installed pytorch using conda.
Might be you have torch named folder in your current directory.
Try changing the directory, or try installing pytorch using pip.
This https://github.com/pytorch/pytorch/issues/1851 might help you to solve your problem.
| https://stackoverflow.com/questions/61642363/ |
Pytorch - Distributed Data Parallel Confusion | I was just looking at the DDP Tutorial:
https://pytorch.org/tutorials/intermediate/ddp_tutorial.html
According to this:
It’s common to use torch.save and torch.load to checkpoint modules
during training and recover from checkpoints. See SAVING AND LOADING
MODELS for more details. When using DDP, one optimizat... | When you're using DistributedDataParallel you have the same model across multiple devices, which are being synchronised to have the exact same parameters.
When using DDP, one optimization is to save the model in only one process and then load it to all processes, reducing write overhead.
Since they are identical,... | https://stackoverflow.com/questions/61642619/ |
Running and building Pytorch on Google Colab | I am trying to run a python package that requires pytorch-gpu. I have change the runtime type of my Colab notebook to GPU. When I run the command, I am facing the following error. Not sure if I am able to build pytorch on colab myself?
Traceback (most recent call last):
File "inference_unet.py", line 9, in <modu... | Now you can directly use pytorch-gpu on google colab, no need of installation.
Just change your runtime to gpu, import torch and torchvision and you are done.
I have attached screenshot doing just the same.
Hope the answer will find helpful.
But in case you want to install different version of pytorch or any other ... | https://stackoverflow.com/questions/61643369/ |
What is vectorised way of doing this operation in pytorch instead of two FOR loops |
Hello,
I have a tensor 'A' in Pytorch of dimesnsions Batch x Channel x Height x Width. I want to reshape it into 'B' such that dimesnions H and W are increased by 'r' and channels reduced by a factor of 'r^2'. For 'r'=2, the illustration is shown in figure attached.
In the figure if 'B' had 4 channels then first 4 ch... | Although this can be done with careful permutation and reshaping, pytorch has already implemented this with nn.PixelShuffle.
| https://stackoverflow.com/questions/61657947/ |
How to read numerical data from CSV in PyTorch? | I'm new to PyTorch; trying to implement a model I developed in TF and compare the results. The model is an Autoencoder model. The input data is a csv file including n samples each with m features (a n*m numerical matrix in a csv file). The targets (the labels) are in another csv file with the same format as the input f... | Might you be looking for something like TabularDataset?
class
torchtext.data.TabularDataset(path, format, fields, skip_header=False, csv_reader_params={}, **kwargs)
Defines a Dataset of columns stored in CSV, TSV, or JSON format.
It will take a path to a CSV file and build a dataset from it. You also need ... | https://stackoverflow.com/questions/61661943/ |
How to move axis on simple numpy array | I'm having trouble moving the 3 axis to the 1 position. I would like to move the 3 to the first 69 position. This is for a machine learning dataset and PyTorch will only accept the data if it's in a 3x69x69 format. Thanks for any help!
# To get the images and labels from file
with h5py.File(r"C:\Users\ajbur\Download... | The second and third arguments of moveaxis are source and destination. To move the last axis to the second position you could do:
a = np.empty([20000, 69, 69, 3])
np.moveaxis(a, -1, 1).shape
>>> (20000, 3, 69, 69)
| https://stackoverflow.com/questions/61664389/ |
How to sort a tensor by first dimension | I have a 2D tensor and I would like to sort by the first dimension like this example:
a = torch.FloatTensor(
[[5, 5],
[5, 3],
[3, 5],
[6, 4],
[3, 7]])
And I expected this result after sorting:
a = torch.FloatTensor(
[[3, 5],
[3, 7],
[5, 3],
[5, 5],
[6, 4]])
Is it possible to ... | Sort by first column and use the indices to then sort the whole array:
a[a[:, 0].sort()[1]]
Output:
tensor([[3., 5.],
[3., 7.],
[5., 5.],
[5., 3.],
[6., 4.]])
And if you really need it interleaved:
b = a[a[:, 1].sort()[1]]
b[b[:, 0].sort()[1]]
Output:
tensor([[3., 5.],
... | https://stackoverflow.com/questions/61665622/ |
ImportError: cannot import name 'mobilenet_v2' from 'torchvision.models' | I want to run a fastai deep learning model on my pc. Not train, just run the pre-trained model on my PC. I have the .pth file. I tried to import the fastai module that I installed and I recieved the error :
ImportError: cannot import name 'mobilenet_v2' from 'torchvision.models' (C:\file_path\__init__.py)
The Code I... | I just finished fixing this problem with my system. Uninstall any pytorch, torchvision by conda and pip. Uninstall fastai as well.
Go to https://pytorch.org/get-started/locally/ and run the conda command there base on your cuda version and etc. Then
conda install -c fastai fastai
| https://stackoverflow.com/questions/61666911/ |
Reading csv.gz file in torchtext | Pandas’s read_csv works for csv.gz as well.
Is there a way to achieve similar with PyTorch?https://torchtext.readthedocs.io/en/latest/data.html#torchtext.data.Dataset doesn’t seem to have such an option.
| TLDR: No, this is not supported by TabularDataset
torchtext.data.TabularDataset uses csv.reader.
Using csvreader against a gzipped file in Python suggests if you open the file with gzip.open, csv.reader can read it.
However, TabularDataset asks for a file path, not a file pointer, so digging into the source code, ... | https://stackoverflow.com/questions/61675018/ |
Pytorch: Loading sample of images using DataLoader | I use standard DataLoader from torch.utils.data. I create dataset class and then build DataLoader this way:
train_dataset = LandmarksDataset(os.path.join(args.data, 'train'), train_transforms, split="train")
train_dataloader = data.DataLoader(train_dataset, batch_size=args.batch_size, num_workers=2,
... | As far as I am aware there's no mechanism that does this for you. Your problem is in the LandmarksDataset class at the point where you're reading the paths of your train data folder. I assume os.listdir(train_data_folder).
Instead you could use a more efficient way os.scandir(train_data_folder) this returns a generat... | https://stackoverflow.com/questions/61675646/ |
Pytorch: Convert 2D-CNN model to tflite | I'd like to convert a model (eg Mobilenet V2) from pytorch to tflite in order to run it on a mobile device.
Has anyone managed to do so?
All I found, was a method that uses ONNX to convert the model into an inbetween state. However, this seems not to work properly, as Tensorflow expects a NHWC-channel order whereas o... | @Ahwar posted a nice solution to this using a Google Colab notebook.
It uses
torch 1.5.0+cu101
torchsummary 1.5.1
torchtext 0.3.1
torchvision 0.6.0+cu101
tensorflow 1.15.2
tensorflow-addons 0.8.3 ... | https://stackoverflow.com/questions/61679908/ |
How most efficiently compute the diagonal of a matrix product | I want to compute the following:
import numpy as np
n= 3
m = 2
x = np.random.randn(n,m)
#Method 1
y = np.zeros(m)
for i in range(m):
y[i] = x[:,i] @ x[:,i]
#Method 2
y2 = np.diag(x.T @ x)
The first method has the problem that it uses a for loop, which can't be very effecient (I need to do this in pytorch on a ... | Use a manually constructed sum-product. You want the sums of the squares of the individual columns:
y = (x * x).sum(axis=0)
As Divakar suggests, np.einsum will likely offer a less memory-intensive option, since it does not require the temporary array x * x:
y = np.einsum('ij,ij->j', x, x)
| https://stackoverflow.com/questions/61687914/ |
Bert pre-trained model giving random output each time | I was trying to add an additional layer after huggingface bert transformer, so I used BertForSequenceClassification inside my nn.Module Network. But, I see the model is giving me random outputs when compared to loading the model directly.
Model 1:
from transformers import BertForSequenceClassification
model = BertFo... | The reason is due to the random initialization of the classifier layer of Bert. If you print your model, you'll see
(pooler): BertPooler(
(dense): Linear(in_features=768, out_features=768, bias=True)
(activation): Tanh()
)
)
(dropout): Dropout(p=0.1, inplace=False)
(classifier): Linear(in_fea... | https://stackoverflow.com/questions/61690689/ |
Neural network in pytorch | I wanna create a Neural Network in PyTorch, that will have 2 inputs and 3 outputs with 1 hidden layer. The two inputs will be float numbers that represents features of an image and 3 outputs will be real numbers between 0 and 1. For example output (1, 0, 0) would mean that it is square and (0,1,0) would mean it is rect... | The network can be defined like this:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
from torch.autograd import Variable
class Net(nn.Module):
def __init__(self, num_inputs=2, num_outputs=3,hidden_dim=5):
# define your netw... | https://stackoverflow.com/questions/61694517/ |
'Net' object has no attribute 'parameters' | I am fairly new to machine learning. I learned to write this code from youtube tutorials but I keep getting this error
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in r... | You're not subclassing nn.Module. It should look like this:
class Net(nn.Module):
def __init__(self):
super().__init__()
This allows your network to inherit all the properties of the nn.Module class, such as the parameters attribute.
| https://stackoverflow.com/questions/61703398/ |
ImportError: cannot import name 'Optional' from 'torch.jit.annotations' | I have installed cpuonly pytorch and torchvision in anaconda. But when i try to import torchvision i get the following error.
ImportError: cannot import name 'Optional' from 'torch.jit.annotations'(C:\Users\MSI\Anaconda3\lib\site-packages\torch\jit\annotations.py)
How can i fix this?
| Not sure if you are installing the correct versions of the libraries. This combination seems to work:
conda create --name test5 python=3.6
conda install -c pytorch pytorch torchvision cpuonly
python
>>> import torchvision
| https://stackoverflow.com/questions/61703503/ |
how to keep pytorch model in redis cache to access model faster for video streaming? | I have this code belonging to feature_extractor.py which is a part of this folder in here:
import torch
import torchvision.transforms as transforms
import numpy as np
import cv2
from .model import Net
class Extractor(object):
def __init__(self, model_path, use_cuda=True):
self.net = Net(reid=True)
... | If you only need to keep model state on RAM, Redis is not necessary. You could instead mount RAM as a virtual disk and store model state there. Check out tmpfs.
| https://stackoverflow.com/questions/61708442/ |
Obtain torch.tensor from string of floats | We can convert 1 dimensional array of floats, stored as a space separated numbers in text file, in to a numpy array or a torch tensor as follows.
line = "1 5 3 7 4"
np_array = np.fromstring(line, dtype='int', sep=" ")
np_array
>> array([1, 5, 3, 7, 4])
And to convert above numpy array to a torch tensor, we ... | What about
x = torch.tensor(list(map(float, line.split(' '))), dtype=torch.float32)
| https://stackoverflow.com/questions/61710826/ |
volatile was removed and now had no effect use with.torch.no_grad() instread | my torch program stopped at this point
I guess i can not use volatile=True
how should I change it and what is the reason to stop?
and How should I change this code?
images = Variable(images.cuda())
targets = [Variable(ann.cuda(), volatile=True) for ann in targets]
train.py:166: UserWarning: volatile was removed... | Variable doesn't do anything and has been deprecated since pytorch 0.4.0. Its functionality was merged with the torch.Tensor class. Back then the volatile flag was used to disable the construction of the computation graph for any operation which the volatile variable was involved in. Newer pytorch has changed this beha... | https://stackoverflow.com/questions/61720460/ |
computation graph of setting weights in pytorch | I need a clarification of code written for some function in FastAI2 library.
this is the code WeightDropout written in FastAI2 library.
class WeightDropout(Module):
"A module that warps another layer in which some weights will be replaced by 0 during training."
def __init__(self, module, weight_p, l... | No, assigning a new weight is not tracked in the computational graph, because an assignment has no derivative, therefore it's impossible to get a gradient through it.
Then why does that code work? The model is not overwriting the actual parameters, but it's using a modified version for the calculations, while keeping ... | https://stackoverflow.com/questions/61722520/ |
Pytorch TypeError - eq() received an invalid combination of arguments | I'm working on a text classification problem with BERT. When training on the local machine everything works just fine, but when switching to the server, I get the following error:
<ipython-input-28-508d35ac5f5f> in flat_accuracy(preds, labels)
5 pred_flat = np.argmax(preds, axis=1).flatten()
6 ... | It could be that the eq implementation of the torch version on your server no longer lets you do elementwise comparison between a torch.Tensor and a np.ndarray. You should coerce either pred_flat to be a torch.Tensor, or coerce labels_flat to be a numpy array. Since you're using np.sum in the return statement and you a... | https://stackoverflow.com/questions/61733562/ |
Concatenating two torch tensors of different shapes in pytorch | I have two torch tensors. One with shape [64, 4, 300], and one with shape [64, 300]. How can I concatenate these two tensors to obtain the resultant tensor of shape [64, 5, 300]. I'm aware about the tensor.cat function used for this, but in order to use that function, I need to reshape the second tensor in order to mat... | You have to use torch.cat along first dimension and do unsqueeze at the first one as well, like this:
import torch
first = torch.randn(64, 4, 300)
second = torch.randn(64, 300)
torch.cat((first, second.unsqueeze(dim=1)), dim=1)
# Shape: [64, 5, 300]
It won't mess up with your data, it's only adding superficial 1 d... | https://stackoverflow.com/questions/61734347/ |
No module named 'torch.nn.functional' | I have python file with lines:
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
It generates errors:
File "C:\gdrive\python\a.py", line 5, in <module>
import torch.n... | It looks like you have an outdated version of PyTorch. Conda - pytorch-cpu was last published over a year ago and its latest version of PyTorch is 1.1.0, whereas PyTorch is currently at version 1.5.0. That packages has been abandoned.
You should install PyTorch with the official instructions given on PyTorch - Get Sta... | https://stackoverflow.com/questions/61736959/ |
Gradient clipping in pytorch has no effect (Gradient exploding still happens) | I have an exploding gradient problem when train the minibatch for 150-200 epochs with batch size = 256 and there’s about 30-60 minibatch (This depends on my specific config). But I have an exploding gradient issues even if I add the code below.
As you can see this below images, notice that in step about 40k there’s th... | Your code looks right, but try using a smaller value for the clip-value argument. Here's the documentation on the clip_grad_value_() function you're using, which shows that each individual term in the gradient is set such that its magnitude does not exceed the clip value.
You have clip value set to 100, so if you have ... | https://stackoverflow.com/questions/61756557/ |
How does the Transformer Model Compute Self Attention? | In the transformer model, https://arxiv.org/pdf/1706.03762.pdf there is self-attention which is computed using softmax on Query (Q) and Key (K) vectors:
I am trying to understand the matrix multiplications:
Q = batch_size x seq_length x embed_size
K = batch_size x seq_length x embed_size
QK^T = batch_size x seq_len... |
How is the softmax computed since there are seq_length x seq_length values per batch element?
The softmax is performed on w.r.t the last axis (torch.nn.Softmax(dim=-1)(tensor) where tensor is of shape batch_size x seq_length x seq_length) to get the probability of attending to every element for each element in the... | https://stackoverflow.com/questions/61764582/ |
How to see the adapted learning rate for Adam in pytorch? | There are many different optimizers with adaptive learning rate methods. Is it possible to see the adapted value of the initial learning rate for Adam?
Here is a similar question about Adadelta and the answer was to search for ["acc_delta"] key, but Adam has no that key.
| AFAIK there is no super easy way to do this. However, you can recalculate the current learning rate of a certain paramter using the implementation of Adam in PyTorch: https://pytorch.org/docs/stable/_modules/torch/optim/adam.html
I came up with this minimal working example:
import torch
import torch.nn as nn
import tor... | https://stackoverflow.com/questions/61773139/ |
How to get the probability of a particular token(word) in a sentence given the context | I'm trying to calculate the probability or any type of score for words in a sentence using NLP. I've tried this approach with GPT2 model using Huggingface Transformers library, but, I couldn't get satisfactory results due to the model's unidirectional nature which for me didn't seem to predict within context. So I was ... | BERT is trained as a masked language model, i.e., it is trained to predict tokens that were replaced by a [MASK] token.
from transformers import AutoTokenizer, BertForMaskedLM
tok = AutoTokenizer.from_pretrained("bert-base-cased")
bert = BertForMaskedLM.from_pretrained("bert-base-cased")
input_idx... | https://stackoverflow.com/questions/61787853/ |
Python get pytorch tensor size | I wanna know how to get the shape of this tensor in Python ? I have tried this :
> len(x)
But this prints 1, why ? I want to print the number of tuples here which is 3. Using len(x) prints only 1.
What's the problem ?
Here's the tensor :
(x=array([[[[ 0.07499999, 0. ],
[ 0.0703125 , 0. ... | It looks like your 3 tuples are located within the first (and only) index of x. In this case, len(x[0]) yields 3.
| https://stackoverflow.com/questions/61802892/ |
Pytorch RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn | This code is built up as follows: My robot takes a picture, some tf computer vision model calculates where in the picture the target object starts. This information (x1 and x2 coordinate) is passed to a pytorch model. It should learn to predict the correct motor activations, in order to get closer to the target. After ... | If you call .detach() on the prediction, that will delete the gradients. Since you are first getting indices from the model and then trying to backprop the error, I would suggest
prediction = policy_model(torch.from_numpy(indices))
motor_controls = prediction.clone().detach().numpy()
This would keep the predictions... | https://stackoverflow.com/questions/61808965/ |
How to extract position input-output indeces from huggingface transformer text tokenizator? | I want to solve stress prediction task with pretrained russian bert.
Input data looks like this:
граммов сверху|000100000001000
Zeros mean no stress. Ones represent stress position character.
I want to map it as word -> vowel number index
So it will be like
граммов -> 1
сверху -> 1
So, for each token, it shou... | Its turned out, tokenizer have return_offsets_mapping param, this solve my problem.
| https://stackoverflow.com/questions/61821515/ |
How to use map_location='cpu' due to "RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False" | I was trying to download the following model at https://pytorch.org/hub/nvidia_deeplearningexamples_tacotron2/
import torch
tacotron2 = torch.hub.load('nvidia/DeepLearningExamples:torchhub', 'nvidia_tacotron2')
I received:
>>> import torch
>>> tacotron2 = torch.hub.load('nvidia/DeepLearningExample... | torch.hub.load does not specifically support map_location, it only forwards the extra arguments to the loading of the model, so it's implementation dependent whether that would be support.
In this case it is not supported, the loading is implemented in NVIDIA/DeepLearningExamples:torchhub - hubconf.py and it does not ... | https://stackoverflow.com/questions/61826246/ |
No matching distribution found for torch==1.5.0+cpu on Heroku | I am trying to deploy my Django app which uses a machine learning model. And the machine learning model requires pytorch to execute.
When i am trying to deploy it is giving me this error
ERROR: Could not find a version that satisfies the requirement torch==1.5.0+cpu (from -r /tmp/build_4518392d43f43bc52f067241a9661c92... | PyTorch does not distribute the CPU only versions over PyPI. They are only available through their custom registry.
If you select the CPU only version on PyTorch - Get Started Locally you get the following instructions:
pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f https://download.pytorch.org/whl/torch_stab... | https://stackoverflow.com/questions/61841672/ |
Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.FloatTensor but got torch.cuda.FloatTensor | My Model:
class myNet(nn.Module):
def __init__(self):
super(myNet,self).__init__()
self.act1=Dynamic_relu_b(64)
self.conv1=nn.Conv2d(3,64,3)
self.pool=nn.AdaptiveAvgPool2d(1)
self.fc=nn.Linear(128,20)
def forward(self,x):
x=self.conv1(x)
x=self.act1(x)
... | In PyTorch two tensors need to be on the same device to perform any mathematical operation between them. But in your case one is on the CPU and the other on the GPU. The error is not as clear as it normally is, because it happened in the backwards pass. You were (un)lucky that your forward pass did not fail. That's bec... | https://stackoverflow.com/questions/61845974/ |
Why some people chain the parameters of two different networks and train them with same optimizer? | I was looking at CycleGAN's official pytorch implementation and there, author chained the parameters of both networks and used a single optimizer for both network. How does this work? Is it better than using two different optimizers for two different networks ?
all_params = chain(module_a.parameters(), module_b.param... | From chain documentation: https://docs.python.org/3/library/itertools.html#itertools.chain
itertools.chain(*iterables)
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.
As parameters() gives you an ... | https://stackoverflow.com/questions/61846505/ |
NumPyro vs Pyro: Why is former 100x faster and when should I use the latter? | From Pytorch-Pyro's website:
We’re excited to announce the release of NumPyro, a NumPy-backed Pyro using JAX for automatic differentiation and JIT compilation, with over 100x speedup for HMC and NUTS!
My questions:
Where is the performance gain (which is sometimes 340x or 2X) of NumPyro (over Pyro) coming from ... | That's a good question. I just asked the same question in Pyro's dedicated forum. Here's the answer of one of their core developers: "There are many cool stuffs in Pyro that do not appear in NumPyro, for example, see Contributed code section in Pyro docs. For me, while developing, it is much easier to debug PyTorc... | https://stackoverflow.com/questions/61846620/ |
How to use TPUs with PyTorch? | I am trying to use TPU using pytorch_xla, but it shows import error in _XLAC.
!curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py
!python pytorch-xla-env-setup.py --version $VERSION
import torch_xla
import torch_xla.core.xla_model as xm
ImportError ... | Please try this:
!pip uninstall -y torch
!pip install torch==1.8.2+cpu -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html
!pip install -q cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.8-cp37-cp37m-linux_x86_64.whl
import torch_xla
It worked for me.
Source: googlecolab/col... | https://stackoverflow.com/questions/61847448/ |
Input dimension reshape when using PyTorch model with CoreML | I have a seq2seq model in PyTorch that I want to run with CoreML. When exporting the model to ONNX the input dimensions are fixed to the shape of the tensor used during export, and again with the conversion from ONNX to CoreML.
import torch
from onnx_coreml import convert
x = torch.ones((32, 1, 1000)) # N x C x W
mo... | The dimensions of the input can be made dynamic in ONNX by specifying dynamic_axes for torch.onnx.export.
torch.onnx.export(
model,
x,
'example.onnx',
# Assigning names to the inputs to reference in dynamic_axes
# Your model only has one input: x
input_names=["input"],
# Define which dimens... | https://stackoverflow.com/questions/61850304/ |
getting unicode decode error while trying to load pre-trained model using torch.load(PATH) | Trying to load a ResNet 18 pre-trained model using the torch.load(PATH) but getting Unicode decode error please help.
Traceback (most recent call last):
File "main.py", line 312, in <module>
main()
File "main.py", line 138, in main
checkpoint = torch.load(args.resume)
File "F:\InsSoft\Anaconda\lib\... | This error hits whenever the model is pretrained on torch version < 0.4 but using torch version > 0.4 for testing / resuming.
so use checkpoint = torch.load(args.resume,encoding='latin1')
| https://stackoverflow.com/questions/61851244/ |
How to know node/feature contributions? | I'm working on GCN (Graph Convolutional Network) in PyTorch, in my application: a patient is a graph, nodes represent its genes, for each gene I have 2 features (gene structure and expression value).
The task is I'm doing a regression model to predict the risk of each patient to get a disease.
My question is,
1- ho... | I am suggesting possibly the simplest solution. However, it can work well.
According to your description of the problem, you want to learn the graph (that represents a patient) representation which can be used to predict the risk of getting a disease. As we know, GCN (graph convolution network) can provide vector rep... | https://stackoverflow.com/questions/61851325/ |
pytorch model not updating | I put my training code below. I am using torch.optim.SGD as optimizer. I thought optimizer.step() would be doing the update but the model accuracy seems to stay the same. My friend said he didn't use the optimizer.step() and his works fine.
I tried taking it out, still the same result. What can I be doing wrong?
I do... | I think this line should be under your for loop
optimizer.zero_grad(). You need to clear the parameter gradients after each loop.
try this
def train(epoch, model, optimizer, trainloader):
model.train()
for batch_idx, (data, labels) in enumerate(trainloader):
optimizer.zero_grad()
outputs = n... | https://stackoverflow.com/questions/61854692/ |
Is it mandatory in pytorch to add modules to ModuleList to access its parameters | I read some posts about ModuleList and all of them said that adding modules to ModuleList gives access to parameters of the Neural Network but in “Training a classifier” example of 60 mins blitz pytorch tutorial the modules are not added to any ModuleList and still the parameters could be accessed using
optimizer = op... | Calling module.parameters() lists all nn.Parameter of the module. Concretely, every attribute on the module that is an instance of nn.Parameter will be in that list. Additionally to listing all the parameters of that module, it will also list all parameters of the submodules (unless module.parameters(recurse=False) is ... | https://stackoverflow.com/questions/61855285/ |
BERT encoding layer produces same output for all inputs during evaluation (PyTorch) | I don't understand why my BERT model returns the same output during evaluation. The output of my model during training seems correct, as the values were different, but is totally the same during evaluation.
Here is my BERT model class
class BERTBaseUncased(nn.Module):
def __init__(self):
super(BERTBaseU... | In case anybody else has the problem, perhaps you forgot to use one of the recommended learning rates from the official paper: 5e-5, 3e-5, 2e-5
Gradients seem to polarize if the learning rate is too high, such as 0.01, causing repeatedly the same logits for the val set.
| https://stackoverflow.com/questions/61855486/ |
Difficulty in Implementing a simple single-layer RNN using Pytorch's base class “nn.Linear” class | While working on making a simple RNN using Pytorch nn.linear function. So firstly I initialized my weights as
self.W_x = nn.Linear(self.input_dim, self.hidden_dim, bias=True)
self.W_h = nn.Linear(self.hidden_dim, self.hidden_dim, bias=True)
Now in the main step where I am getting the result of the current state by u... | Your W_x and W_h are not weights, but linear layers, which use a weight and bias (since bias=True). They need to be called as a function.
Furthermore, you cannot use NumPy operations with PyTorch tensors, but if you convert your tensors to NumPy arrays you can't back propagate through them, since only PyTorch operatio... | https://stackoverflow.com/questions/61858053/ |
How to handle class imbalance in multi-label classification using pytorch | We are attempting to implement multi-label classification using CNN in pytorch. We have 8 labels and around 260 images using a 90/10 split for train/validation sets.
The classes are highly imbalanced with the most frequent class occurring in over 140 images. On the other hand, the least frequent class occurs in less ... | There's basically three ways of dealing with this.
Discard data from the more common class
Weight minority class loss values more heavily
Oversample the minority class
Option 1 is implemented by selecting the files you include in your Dataset.
Option 2 is implemented with the pos_weight parameter for BCEWithLogits... | https://stackoverflow.com/questions/61879612/ |
Weird behavior when calling cuda() on different tensors in pytorch | I am trying to train a pytorch neural network on a GPU device. In order to do so, I load my inputs and network onto the default cuda enabled GPU decive. However, when I load my inputs, the model's weights do not stay cuda tensors. Here is my train function
def train(network: nn.Module, name: str, learning_cycles: dict... | Given that a device mismatch crops up regardless of the device the inputs are on, it's likely that some of your model's parameters are not being moved over to the GPU when you call network = network.cuda(). You have model parameters on both the CPU and the GPU.
Post your model code. It's likely you have a Pytorch modu... | https://stackoverflow.com/questions/61880544/ |
Training models interactively in Pytorch | I need to train two models in parallel. Each model has a different activation function with trainable parameters. I want to train model one and model two in the way that the parameters of the activation function from model one (e.g., alpha1) is separated from the parameters in model two (e.g., alpha2) by a gap of 2; i.... | Example module definition
I will use torch.nn.PReLU as parametric activation you talk about.
get_weight created for convenience.
import torch
class Module(torch.nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.input = torch.nn.Linear(in_features, 2 * in_features... | https://stackoverflow.com/questions/61888716/ |
trouble importing Pytorch in Jupyter notebook | Iam new to deep learning and Iam trying to import Pytorch on Jupyter Notebook.
I installed Pytorch with the following lines of code in Anaconda Prompt.
conda create -n pytorch_p37 python=3.7
conda activate pytorch_p37
conda install pytorch torchvision -c pytorch
conda install jupyter
conda list
it all executed well.... | !pip install torch
It worked for me in a Anaconda's Jupyter notebook.
| https://stackoverflow.com/questions/61897853/ |
How to solve UserWarning: Using a target size (torch.Size([])) that is different to the input size (torch.Size([1]))? | I am trying to run code from a book I purchased about reinforcement learning in Pytorch.
The code should work according to the book, but for me the model doesn't converge and the reward remains negative. It also get the following user warning:
/home/user/.local/lib/python3.6/site-packages/ipykernel_launcher.py:30: Us... | size([]) is valid, but it represents a single value, not an array, whereas size([1]) is a 1 dimensional array containing only one item item. It is like comparing 5 to [5]. One solution to this is
returns = returns[::-1]
returns_amount = len(returns)
returns = torch.tensor(returns)
... | https://stackoverflow.com/questions/61912681/ |
How to build a model to predict a graph (not a image) in time series? | There is an adjacent matrix dataset that is based on time series. I would like to know if it is possible to build a neural network model to predict tn time point's matrix by using the previous time-series data. In my opinion, traditional models such as CNN may not fit for the sparse matrix graph.
| Maybe you should give a look at Graph Neural Networks (specialy Spatial-Temporal Graph Networks). They use temporal information about graphs and its adjacency matrix to predict future nodes states, such values in the next-step.
You can read this survey paper as a start point and follow its cited works therefore.
| https://stackoverflow.com/questions/61925599/ |
Autoencoder to encode features/categories of data | My question is regarding the use of autoencoders (in PyTorch). I have a tabular dataset with a categorical feature that has 10 different categories. Names of these categories are quite different - some names consist of one word, some of two or three words. But all in all I have 10 unique category names. What I'm trying... | First you will need to set up a train_loader depending on your data that will iterate over your data points.
Then you need to figure out what kind of loss you are going to use and optimizer:
# mean-squared error loss
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=.001) #learning rate depend on... | https://stackoverflow.com/questions/61940062/ |
Pytorch runtime error: Cuda Out of memory. Works fine with jupyter notebook but doesn't as a script | I have a special kind of problem. I am able to run the code in jupyter notebook perfectly fine with no OOM error. However when i run the same code as a script in linux it gives me the OOM error. Has anyone have the same issue. I tried gc.collect() and torch.cuda.empty_cache() inside the code and nothing helps.
It alwa... | I had a similar thing happen to me recently.
I would run my model in a Jupyter notebook, on a AWS EC2 p2.xlarge instance, and the model would run correctly. Then, I would ssh into the same instance, and re-run a .py script of the same model, and receive the OOM errors that you described.
All I had to do was reset the ... | https://stackoverflow.com/questions/61944703/ |
Kernel size can't be greater than actual input size | I have a data with depth = 3 and I want to pass it through 3 convolution layers with 3x3x3 kernels each.
My current code is below. The first input is
[batch_size=10, in_channels=1, depth=3, height=128, width=256]
and I notice after the first conv3d layer the output is [10,8,1,126,254]. Obviously it has now depth 1 an... | You need to use padding. If you only want to pad the input for the convolutions after the first one and only in the depth dimensions to get the minimum dimension of 3, you would use padding=(1, 0, 0) (it's 1 because the same padding is applied to both sides, i.e. (padding, input, padding) along that dimension).
self.c... | https://stackoverflow.com/questions/61945404/ |
Unable to import torch (ImportError: libcudart.so.10.0) | I'm currently working on a Nvidia Jetson Nano and I'm not very familiar with Linux. I am trying to run a python file which imports a package called torch. I have installed it alongside with torchvision while following the instructions from NVIDIA here.
When I run pip list on my terminal, I am able to see torch liste... | I meet the exact same problem. The problem seems to be cuda 10.2. Downgrading to 10.0 does not help either. Probably the solution is to manually install everything from Jetpack and making sure that the cuda version to be installed is 10.0.
| https://stackoverflow.com/questions/61948074/ |
How to fine tune BERT on unlabeled data? | I want to fine tune BERT on a specific domain. I have texts of that domain in text files. How can I use these to fine tune BERT?
I am looking here currently.
My main objective is to get sentence embeddings using BERT.
| The important distinction to make here is whether you want to fine-tune your model, or whether you want to expose it to additional pretraining.
The former is simply a way to train BERT to adapt to a specific supervised task, for which you generally need in the order of 1000 or more samples including labels.
Pretraining... | https://stackoverflow.com/questions/61962710/ |
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first | The following is from a project that I'm doing in Udacity on Deep Learning. The project is on Generating TV scripts. The error that i encountered is the one below.
The following function is the one after model training.
def generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100):
"""
Gene... | np.roll(current_seq, -1, 1) requires the input to be a NumPy array, but current_seq is a tensor, so it tries to convert it to a NumPy array, which fails, because the tensor is on the GPU. In order to convert it to a NumPy array, you need to have the tensor on the CPU.
current_seq = np.roll(current_seq.cpu(), -1, 1)
| https://stackoverflow.com/questions/61964863/ |
Convert np array of arrays to torch tensor when inner arrays are of different sizes | I have several videos, which I have loaded frame by frame into a numpy array of arrays. For example if I have 8 videos, they are converted into an 8 dimensional numpy array of arrays where each inner array has a different dimension depending on the number of frames of the individual video. When I print
array.shape
... | You can use rnn util function pad_sequence to make them same size.
ary
array([list([1, 2, 3]), list([1, 2]), list([1, 2, 3, 4])], dtype=object)
from torch.nn.utils.rnn import pad_sequence
t = pad_sequence([torch.tensor(x) for x in ary], batch_first=True)
t
tensor([[1, 2, 3, 0],
[1, 2, 0, 0],
[1, 2, 3... | https://stackoverflow.com/questions/61970047/ |
Can I use a PyTorch or Tensorflow project on a machine without GPU? | I'm a noob when it comes to Python and machine learning. I'm trying to run two different projects that have to do with something called Deep Image Matting:
https://github.com/Joker316701882/Deep-Image-Matting with Tensorflow
https://github.com/huochaitiantang/pytorch-deep-image-matting with Pytorch
I'm just trying ... | For the PyTorch one, there were two problems and it looks like you've solved the first one on your own with map_location. The second problem is that the weights in your checkpoint and the weights in your model don't have the same shape! A quick detour to the github repo; let's visit net.py in core. Take a look at lines... | https://stackoverflow.com/questions/61974153/ |
Install torch on python 3.8.1 windows 10 | I have been reading this post How to install pytorch in windows? but no one answer work for me on the versio 3.8.1 of python. Anything else I can do?
| Maybe this can help you.
pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
Please ensure that you have met the prerequisites, depending on your package manager. You can also use Anaconda as a package manager since it installs all dependencies.
| https://stackoverflow.com/questions/61981438/ |
PyTorch C++ FrontEnd returning multiple Tensors in forward | I was wonder how can I return a std::vector<torch::Tensor> in my forward pass of a Module Class,
I read about the Macro of FORWARD_HAS_DEFAULT_ARGS in the docs, but didn’t really
understand how to use it, and also how to use it for making it possible to return a vector in return.
Thank you in advance.
| FORWARD_HAS_DEFAULT_ARGS is a C++ macro and according to documentation:
This macro enables a module with default arguments in its forward
method to be used in a Sequential module.
So it's not what you are after.
I assume you are returning multiple torch::Tensor values contained in std::vector. You could just ... | https://stackoverflow.com/questions/61988134/ |
PyTorch error - 'numpy.ndarray' object has no attribute 'relu' | I am testing my CNN model, but keep on getting error "AttributeError: 'numpy.ndarray' object has no attribute 'relu'".
my dataset is extracted by below code:
import torch
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import tor... | Where is F defined? F seems to be the numpy array.
Did you maybe mean to do:
import torch.nn.functional as F? Otherwise, the relu function isn't defined anywhere.
| https://stackoverflow.com/questions/61990429/ |
Pytorch : GPU Memory Leak | I speculated that I was facing a GPU memory leak in the training of Conv nets using PyTorch framework. Below image
To resolve it, I added -
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
which resolved the memory problem, as shown below -
but as I was using torch.nn.DataParallel, so I expect my code to utilise all t... | So the way I resolved some of my CUDA out of memory issue is by making sure to delete useless tensors and trim tensors that may stay referenced for some hidden reason. The problem may arise from either requesting for more memory than you have the capacity for or an accumulation of garbage data that you don't need, but ... | https://stackoverflow.com/questions/61991467/ |
pythorch-lightning train_dataloader runs out of data | I started to use pytorch-lightning and faced a problem of my custom data loaders:
Im using an own dataset and a common torch.utils.data.DataLoader. Basically the dataset takes a path and loads the data corresponding to an given index the dataloader loads its.
def train_dataloader(self):
train_set = TextKeypointsD... | The solution was:
I used source_tensor = source_tensor.view(-1, self.batch_size, self.input_size) which lead to some errors later on, now Im using source_tensor = source_tensor.permute(1, 0, 2), which fixed the problem.
| https://stackoverflow.com/questions/62006977/ |
Confusion regarding batch size while using DataLoader in pytorch | I am new to pytorch.
I am training an ANN for classification on the MNIST dataset.
train_loader = DataLoader(train_data,batch_size=200,shuffle=True)
I am confused. The dataset is of 60,000 images and I have set batch size of 6000 and my model has 30 epochs.
Will every epoch see only 6000 images or will every epoch se... | Every call to the dataset iterator will return batch of images of size batch_size. Hence you will have 10 batches until you exhaust all the 60000 images.
| https://stackoverflow.com/questions/62012673/ |
Pytorch: How to know if GPU memory being utilised is actually needed or is there a memory leak | I have 3 Tesla V100(16 GB). I am doing transfer learning using efficeint net (63 Million parameters) on images of (512,512) with a batch size of 20.
My GPU memory utilisation is below -
As you can see, it has almost filled up all the 3 GPUs(almost 80%).
My question is is there any theoretical way of calculating that t... | I'm not sure that is what you asked for but have you tried doing something like:
memory_usage = number_of_variables * memory_usage_per_variable.
So if you use torch.float32 tensors, and you have 125 000 variables sent to the GPU with .cuda(). Then you are using 4Gbytes of memory on your GPU. You can compare with how ... | https://stackoverflow.com/questions/62013841/ |
Pytorch could not find module | I have installed pytorch with command:
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch -y
Python complains regarding line import torch with message:
Could not find module 'C:\ProgramData\Anaconda3\envs\edx\lib\site-packages\torch\lib\caffe2_nvrtc.dll' (or one of its dependencies). Try using the full p... | I faced the same problem. If your OS is Windows then I would recommend using Anaconda and installing pytorch in separate conda environment. Quick solution is to search for nvcuda.dll file on google and download this file. If you are running the code on Jupyter notebook the output will give you the complete path of the ... | https://stackoverflow.com/questions/62021601/ |
pip install torch killed at 99% -- Excessive memory usage | This is while I was installing torch on my laptop. It was getting killed continuously so I thought I will check the memory usage. It hanged my laptop, I had to take a picture with my phone.
If you can't see the image below, it shows pip using 5.8 GiB memory out of 7.8 GiB available. That was a sudden spike at 99%.
Sy... | If you are running low on memory you could try with pip install package --no-cache-dir
| https://stackoverflow.com/questions/62030345/ |
Is torch.as_tensor() the same as torch.from_numpy() for a numpy array on a CPU? | On a CPU, is torch.as_tensor(a) the same as torch.from_numpy(a) for a numpy array, a? If not, then why not?
From the docs for torch.as_tensor
if the data is an ndarray of the corresponding dtype and
the device is the cpu, no copy will be performed.
From the docs for torch.from_numpy:
The returned tens... | They are basically the same, except than as_tensor is more generic:
Contrary to from_numpy, it supports a wide range of datatype, including list, tuple, and native Python scalars.
as_tensor supports changing dtype and device directly, which is very convenient in practice since the default dtype of Torch tensor is floa... | https://stackoverflow.com/questions/62033283/ |
How embedding_bag exactly works in PyTorch | in PyTorch, torch.nn.functional.embedding_bag seems to be the main function responsible for doing the real job of embedding lookup. On PyTorch's documentation, it has been mentioned that embedding_bag does its job > without instantiating the intermediate embeddings. What does that exactly mean? Does this mean for examp... | In the simplest case, torch.nn.functional.embedding_bag is conceptually a two step process. The first step is to create an embedding and the second step is to reduce (sum/mean/max, according to the "mode" argument) the embedding output across dimension 0. So you can get the same result that embedding_bag give... | https://stackoverflow.com/questions/62052734/ |
PyTorch Model Training: RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR | After training a PyTorch model on a GPU for several hours, the program fails with the error
RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR
Training Conditions
Neural Network: PyTorch 4-layer nn.LSTM with nn.Linear output
Deep Q Network Agent (Vanilla DQN with Replay Memory)
state passed into forward() h... | The error RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR is notoriously difficult to debug, but surprisingly often it's an out of memory problem. Usually, you would get the out of memory error, but depending on where it occurs, PyTorch cannot intercept the error and therefore not provide a meaningful error mess... | https://stackoverflow.com/questions/62067849/ |
Pytorch: IndexError: index out of range in self. How to solve? | This training code is based on the run_glue.py script found here:
# Set the seed value all over the place to make this reproducible.
seed_val = 42
random.seed(seed_val)
np.random.seed(seed_val)
torch.manual_seed(seed_val)
torch.cuda.manual_seed_all(seed_val)
# Store the average loss after each epoch so we can plot th... | I think you have messed up with input dimension declared torch.nn.Embedding and with your input. torch.nn.Embedding is a simple lookup table that stores embeddings of a fixed dictionary and size.
Any input less than zero or more than declared input dimension raise this error.
Compare your input and the dimension mentio... | https://stackoverflow.com/questions/62081155/ |
forward() takes 1 positional argument but 2 were given | I'm trying to build a Model using EfficientNet-B0.
The details of the Model are shown in the code below.
I got the following error when I tried to learn.
TypeError Traceback (most recent call last)
'''
<ipython-input-17-fb3850894108> in forward(self, *x)
24 #x: bs*N x... | Now you can easily get the network without the last layers by using the include_top parameter:
m = EfficientNet.from_pretrained('efficientnet-b0', include_top=False)
What it does, as can be easily seen in the code, is not calling forward method for the last layers (AveragePool, Dropout, FC).
Other alternative approach... | https://stackoverflow.com/questions/62084245/ |
Is this the right way to compute gradients of two losses from two different NN's in pytorch? | I have a NN defined in pytorch and I have created two instances of that net as self.actor_critic_r1 and self.actor_critic_r2. I calculate the losses of each net i.e. loss1 and loss2 and I sum it up and calculate the grads in the following way,
loss_r1 = value_loss_r1 + action_loss_r1 - dist_entropy_r1 * args.entropy_c... | It should be the sum approach. If there is no interplay then the gradient of the 'wrong' loss will be zero for the 'wrong' optimizer anyway, and if there is interplay you likely want to optimize for that interplay.
Only if you know that there is interplay but you do not want to optimize for it should you use approach ... | https://stackoverflow.com/questions/62102840/ |
PyTorch paste values into tensor by row index with increasing column index | I have a tensor output into which I want to put some values. I know the row that each value should go in, but I don't have an index tensor describing the columns. Instead, if there are k values that belong to one row, they should go in columns 0, 1, ..., k-1. This is perhaps better explained with an example:
import to... | I think your solution has linear time complexity. So, I am not sure if it can be further improved. However, I think the solution you provided is not correct. Let me give an example.
For the following input:
row_idx = torch.tensor([0, 0, 1, 0, 0, 1, 2, 2, 2, 3])
Your solution outputs the following.
tensor([[4., 1.,... | https://stackoverflow.com/questions/62105292/ |
Calculate the standard deviation of a moving windows using 2d convolution | I am doing a image processing project.
I want to calculate the standard deviation of a silding window using 2d convolution. I can now calculate the mean, but I cannot find a way to calculate the standard deviation. Here is my code:
import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
device = tor... | I think it can be somehow like this:
mean (img) using convolution.
Subtract from the original image of p. 1
Calculate the square of each element.
By convolution we find the average, p. 3
Calculates the square root of the elements of p. 4
| https://stackoverflow.com/questions/62110234/ |
Multiple threads accessing same model on GPU for inference | I have a cnn model that is loaded onto the GPU and for every image, a new thread has to be created and detached to run the model on this image. Is this possible and if so, Is it safe?
| Yes, you definitely can. There are two aspects to it. If you want to run each model in parallel, then you have to load the same model in multiple GPUs. If you don't need that (just want the threading part), then you can load the model and use concurrent.futures.ThreadPoolExecutor(). In each call, you can pass an image.... | https://stackoverflow.com/questions/62111922/ |
fp16 inference on cpu Pytorch | I have a pretrained pytorch model I want to inference on fp16 instead of fp32, I have already tried this while using the gpu but when I try it on cpu I get:
"sum_cpu" not implemented for 'Half' torch.
any fixes?
| As I know, a lot of CPU-based operations in Pytorch are not implemented to support FP16; instead, it's NVIDIA GPUs that have hardware support for FP16(e.g. tensor cores in Turing arch GPU) and PyTorch followed up since CUDA 7.0(ish). To accelerate inference on CPU by quantization to FP16, you may wanna try torch.bfloat... | https://stackoverflow.com/questions/62112534/ |
pytorch got None after backward() | I am learning pytorch and write a simple code as below.
import torch
x = torch.randn(3,requires_grad=True).cuda()
print(x)
y = x * x
print(y)
y.backward(torch.tensor([1,1.0,1]).cuda())
print(x.grad)
tensor([ 0.5934, -1.8813, -0.7817], device='cuda:0', grad_fn=<CopyBackwards>)
tensor([0.3521, 3.5392, 0.6111], d... | I got it.
x = torch.randn(3,requires_grad=True).cuda()
x is create by cuda(). So x is not a leaf tensor.
Change the code as below will be ok.
x = torch.randn(3,requires_grad=True,device=0)
| https://stackoverflow.com/questions/62114631/ |
Training 1D CNN in Pytorch | I want to train the model given below. I am developing 1D CNN model in PyTorch. Usually we use dataloaders in PyTorch. But I am not using dataloaders for my implementation. I need guidance on how i can train my model in pytorch.
import torch
import torch.nn as nn
import torch.nn.functional as F
class CharCNN(nn.Modu... | The forward method of your model only takes one argument, but you are calling it with two arguments:
output = model(inputs, batch_size)
It should be:
output = model(inputs)
| https://stackoverflow.com/questions/62120826/ |
is there any similar function with clamp_ in tensorflow > 2.0 | I'm converting torch code to tensorflow 2.0
prior_boxes = torch.FloatTensor(prior_boxes).to(device) # (8732, 4)
prior_boxes.clamp_(0, 1) # (8732, 4)
is there any replacement of clamp_(0,1) in tensorflow > 2.0?
| Try tf.clip_by_value, though unlike clamp_, it is not in-place:
t = tf.constant([[-10., -1., 0.], [0., 2., 10.]])
t2 = tf.clip_by_value(t, clip_value_min=-1, clip_value_max=1)
t2.numpy()
# gives [[-1., -1., 0.], [0., 1., 1.]]
| https://stackoverflow.com/questions/62143092/ |
No performance improvement using quantization model in pytorch | I have trained a model in pytorch with float data type. I want to improve my inference time by converting this model to quantized model. I have used torch.quantization.convert api to convert my model's weight to uint8 data type. However, when I use this model for inference, I do not get any performance improvement. Am ... | PyTorch documentation suggests three ways to perform quantization. You are doing post-training dynamic quantization (the simplest quantization method available) which only supports torch.nn.Linear and torch.nn.LSTM layers as listed here. To quantize CNN layers, you would want to check out the other two techniques (thes... | https://stackoverflow.com/questions/62143162/ |
Difference between src_mask and src_key_padding_mask | I am having a difficult time in understanding transformers. Everything is getting clear bit by bit but one thing that makes my head scratch is
what is the difference between src_mask and src_key_padding_mask which is passed as an argument in forward function in both encoder layer and decoder layer.
https://pytorch.org... | Difference between src_mask and src_key_padding_mask
The general thing is to notice the difference between the use of the tensors _mask vs _key_padding_mask.
Inside the transformer when attention is done we usually get an squared intermediate tensor with all the comparisons
of size [Tx, Tx] (for the input to the encode... | https://stackoverflow.com/questions/62170439/ |
Convolution in PyTorch with non-trainable pre-defined kernel | I would like to introduce a custom layer to my neural network. The mathematical operation should be a discrete 2D cross correlation (or convolution) with a non-trainable kernel. The values in the kernel depend on three things: kernel shape, strides and padding. I intend to multiply the output element-wise with a weight... | If I understand correctly,you want a Conv2d layer with defined kernel and you don't want it to be learnable.
In that case,you can use the conv2d function like this:
import torch.nn.functional as F
output_tensor = F.conv2d(input_tensor, your_kernel, ...)
the parameter your_kernel is your weight matrix,also you need ... | https://stackoverflow.com/questions/62189366/ |
Pytorch: accessing a subtensor using lists of indices | I have a pair of tensors S and T of dimensions (s1,...,sm) and (t1,...,tn) with si < ti. I want to specify a list of indices in each dimensions of T to "embed" S in T. If I1 is a list of s1 indices in (0,1,...,t1) and likewise for I2 up to In, I would like to do something like
T.select(I1,...,In)=S
that will have t... | If you're flexible with using NumPy only for the indices part, then here's one approach by constructing an open mesh using numpy.ix_() and using this mesh to fill-in the values from the tensor S. If this is not acceptable, then you can use torch.meshgrid()
Below is an illustration of both approaches with descriptions... | https://stackoverflow.com/questions/62200105/ |
How to solve this question "RuntimeError: CUDA out of memory."? | I'm going to extract a feature from pictures.I first define a tensor data_feature_map, and then use torch.cat to stack the features of one picture.
My code is :
data_feature_map = torch.ones(1,2048)
for i, data in enumerate(train_loader, 0):
img, _ = data
img.requires_grad_=False
if torch.cuda.is_availab... | Since your GPU is running out of memory, you can try few things:
1.) Reduce your batch size
2.) Reduce your network size
| https://stackoverflow.com/questions/62210030/ |
Differential Privacy decreases the model performance significantly | Background Information
I trained a classifier to predict three labels: COVID/Pneumonia/Healthy based on chest X-Ray images. It's a PyTorch implementation of COVID-Net. I use a training set to train on, validation set to save the best performing model, and then a test set to measure the "real" performance of the model.... | It seems the PyTorch Differential Privacy library from Facebook Research is built on the concept of Renyi differential privacy guarantee that is well-suited for expressing guarantees of privacy-preserving algorithms and for composition of heterogeneous mechanisms. We need to have a good estimation of the heterogenity i... | https://stackoverflow.com/questions/62246851/ |
How to get the imagenet dataset on which pytorch models are trained on | Can anyone please tell me how to download the complete imagenet dataset on which the pytorch torchvision models are trained on and their Top-1 error is reported on?
I have downloaded Tiny-Imagenet from Imagenet website and used pretrained resnet-101 model which provides only 18% Top-1 accuracy.
| Download the ImageNet dataset from http://www.image-net.org/ (you have to sign in)
Then, you should move validation images to labeled subfolders, which could be done automatically using the following shell script:
https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh
| https://stackoverflow.com/questions/62248037/ |
Passing variable to nn.Conv2d arguments within a class init definition python | So I want to pass some new variables such as kernel_size when I initiate a new object. Let's say net=Net10(5,2,4,3,1,1). so that I get an object of this class with the parameters I want not something always constant, cos otherwise I will have to define lots of classes. Now, I want to pass kernel_size within the self.Co... | Try:
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=self.kernel, padding=2, stride=1)
In more details: python functions (e.g., __init__ of the conv layer) can have input arguments is two "flavors": positional arguments: that is associating an input argument to a function variable according to its... | https://stackoverflow.com/questions/62248832/ |
How to load dataset from pickle files into PyTorch? | I have X_train(inputs) and Y_train(labels) in separate pickle files in form of integer matrices. Now, I need to load them and train using PyTorch. I tried torch.utils.data.DataLoader and torchvision.datasets.DatasetFolder but nothing worked or I might be getting wrong somewhere. Please suggest a proper way for the same... | You should really give a clear description of your problem with some examples. Anyway, as far as I understand you are looking for something like this.
import pickle
from torch.utils.data import Dataset
from torchvision import transforms
from torch.utils.data import DataLoader
class YourDataset(Dataset):
def __i... | https://stackoverflow.com/questions/62260217/ |
Downloading transformers models to use offline | I have a trained transformers NER model that I want to use on a machine not connected to the internet. When loading such a model, currently it downloads cache files to the .cache folder.
To load and run the model offline, you need to copy the files in the .cache folder to the offline machine. However, these files hav... | One relatively easy way to deal with this issue is to simply "rename" the pretrained models, as is detailed in this thread.
Essentially, all you have to do is something like this for whatever model you're trying to work with:
from transformers import BertModel
model = BertModel.from_pretrained("bert-bas... | https://stackoverflow.com/questions/62261602/ |
what is torch's unsqueeze equivalence with tensorflow? | what is torch's unsqueeze equivalence with tensorflow?
#tensorflow auto-broadcasts singleton dimensions
lower_bounds = tf.argmax(set_1[:, :2].unsqueeze(1), set_2[:, :2].unsqueeze(0)) # (n1, n2, 2)
upper_bounds = tf.argmin(set_1[:, 2:].unsqueeze(1), set_2[:, 2:].unsqueeze(0)) # (n1, n2, 2)
| Maybe you wanna try this:
tf.expand_dims(x, axis)
| https://stackoverflow.com/questions/62273504/ |
PyTorch LSTM dropout vs Keras LSTM dropout | I'm trying to port my sequential Keras network to PyTorch. But I'm having trouble with the LSTM units:
LSTM(512,
stateful = False,
return_sequences = True,
dropout = 0.5),
LSTM(512,
stateful = False,
return_sequences = True,
dropout = 0.5),
How should I formulate this in PyTorch? Especi... | The following should work for you.
lstm = nn.LSTM(
input_size = ?,
hidden_size = 512,
num_layers = 1,
batch_first = True,
dropout = 0.5
)
You need to set the input_size. Check out the documentation on LSTM.
Update
In a 1-layer LSTM, there is no point in assigning dropout since dropout is a... | https://stackoverflow.com/questions/62274014/ |
Where is the numpy data stored? | In python, If only import torch (but not import numpy), "torch.numpy()" can still work. Is that means the numpy data can be stored and displayed without numpy package? Where is the numpy data stored and how does it display (without numpy package)?
example codes:
import torch
a = torch.tensor([[1,2,3],[4,5,6]])
a = a.... | PyTorch uses NumPy internally. You don't need to manually import everything a package uses, that is one of the core principles of modules. It's still an object of the same NumPy class and you need to have NumPy installed for it to work, otherwise you would get an import error, just that the import happens in one of PyT... | https://stackoverflow.com/questions/62274612/ |
what is the torch's torch.cat equivalence with tensorflow? | def cxcy_to_xy(cxcy):
"""
Convert bounding boxes from center-size coordinates (c_x, c_y, w, h) to boundary coordinates (x_min, y_min, x_max, y_max).
:param cxcy: bounding boxes in center-size coordinates, a tensor of size (n_boxes, 4)
:return: bounding boxes in boundary coordinates, a tensor of size (n... | Few options depending on the API in TF you're using:
tf.concat - most similar to torch.cat:
tf.concat(values, axis, name='concat')
tf.keras.layers.concatenate - if you're using Keras sequential API:
tf.keras.layers.concatenate(values, axis=-1, **kwargs)
tf.keras.layers.Concatenate - if you're using Keras function... | https://stackoverflow.com/questions/62274656/ |
what does clamp_ does in pytorch and how to change it to the tensorflow 2.0? | prior_boxes = torch.FloatTensor(prior_boxes).to(device) # (8732, 4)
prior_boxes.clamp_(0, 1) # (8732, 4)
what dooes clamp_ do in pytorch and how to change it to the tensorflow 2.0?
I'm not sure what clamp_ do exactly?
| clamp_(0, 1) Clamp all elements in prior_boxes into the range [ 0, 1].
Tensorflow:
tf.clip_by_value
https://www.tensorflow.org/api_docs/python/tf/clip_by_value
| https://stackoverflow.com/questions/62275778/ |
Array Slicing with step 2 | Have array like
arr = [1,2,3,4,5,6,7,8,9,10].
How I can get array like this:
[1,2,5,6,9,10]
take 2 elements with step 2(::2)
I try something like arr[:2::2].it's not work
| [:2::2] is not valid Python syntax. A slice only takes 3 values - start, stop, step. You are trying to provide 4.
Here's what you need to do:
In [233]: arr = np.arange(1,11)
In [234]: arr ... | https://stackoverflow.com/questions/62275877/ |
Pytorch loss does't change in vgg 19 model | In pytorch I made a model vgg19 for classification tiny imagenet:
model = nn.Sequential(
nn.BatchNorm2d(3),
nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(3,3), padding=1),
nn.ReLU(),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3,3), padding=1),
nn.ReLU(),
nn.MaxPool2d((2,2)... | nn.CrossEntropyLoss applies log-softmax, but you also apply softmax in the model:
nn.Linear(1000, 200),
nn.Softmax(),
nn.Dropout2d(),
The output of your model must be the raw logits, without the nn.Softmax().
Additionally, dropout should not be used just before the output of the model, since that effectively wipes ... | https://stackoverflow.com/questions/62284832/ |
Why torch.dot(a,b) makes requires_grad=False | I have some losses in a loop storing them in a tensor loss. Now I want to multiply a weight tensor to the loss tensor to have final loss, but after torch.dot(), the result scalar, ll_new, has requires_grad=False. The following is my code.
loss_vector = torch.FloatTensor(total_loss_q)
w_norm = F.softmax(loss_vector, di... | I think the issue is in the line: loss_vector = torch.FloatTensor(total_loss_q) as requires_grad for loss_vector is False (default value). So, you should do:
loss_vector = torch.FloatTensor(total_loss_q, requires_grad=True)
| https://stackoverflow.com/questions/62294833/ |
Whenever I try to install torch, it displays killed | I just want to install pytorch, I ran this in the terminal:
pip install torch
And it displays:
Collecting torch
Killed
What is the problem?
| It says your your free ram is not enough to install the package, but there is a method that you can still use it.
pip install torch --no-cache-dir
| https://stackoverflow.com/questions/62301268/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.