instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
TypeError: img should be PIL Image. Got
import torch import torch.nn as nn import torchvision.transforms.functional as TF class DoubleConv(nn.Module): def __init__(self, in_channels, out_channels): super(DoubleConv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1, bias=False), ...
As stated in the error you recievced, Tf.resize expects an input of type PIL.Image Pil is a python library found here, it's used for dealing and processing images. https://python-pillow.org/ Docs for the function in pytorch: https://pytorch.org/vision/0.8/_modules/torchvision/transforms/functional.html#resize
https://stackoverflow.com/questions/66309024/
kmeans clustering python
There are coordinates that I want to cluster. The result of clustering using the kmeans [[0, 107], [0, 108], [0, 109], [0, 115], [0, 116], [0, 117], [0, 118], [0, 125], [0, 126], [0, 127], [0, 128], [0, 135], [0, 136], [0, 194], [0, 195], [1, 107], [1, 108], [1, 109], [1, 110], [1, 114], [1, 115], [1, 116], [1, 117], [...
I assume you want the coordinates affected to the 7th cluster. You can do so by storing you result in a dictionary : from sklearn.cluster import KMeans km = KMeans(n_clusters=9) km_fit = km.fit(nonzero_pred_sub) d = dict() # dictionary linking cluster id to coordinates for i in range(len(km_fit)): cluster_id = km_fi...
https://stackoverflow.com/questions/66312861/
pytorch KAIR example on Android
I stuck trying to trace/scipt ffdnet KAIR's model to android. Model's forward looks like: def forward(self, x): #, paddingBottom, paddingRight): #, sigma): noise_level_model = 15 sigma = torch.full((1, 1, 1, 1), noise_level_model / 255.).type_as(x) h, w = x.size()[-2:] paddingBottom = int(np.ceil(h/2)...
I encountered a similar issue. It was due to my model using numpy math operations (which are numpy.ufunc). I fixed the issue by replacing all of numpy ufuncs (i.e. np.add, np.ceil, and +, - etc on ndarrays) with corresponding torch versions (i.e. torch.add, torch.sub etc).
https://stackoverflow.com/questions/66314426/
How to find r2score of my PyTorch model for regression
I have a UNet model. I'm trying for a regression model since, in my output, I have different floating values for each pixel. In order to check the r2score, I tried to put the below code in the model class, training_step, validation_step, and test_step. from pytorch_lightning.metrics.functional import r2score r2 = r2sco...
The issue is that the function accepts 1D or 2D tensors, but your tensor is 4D (B x C x H x W). So to use the function you should reshape it: r2 = r2score(pred.view(pred.shape[1], -1), y.view(y.shape[1], -1))
https://stackoverflow.com/questions/66317323/
How to create a tensor by accessing specific values at given indices of a 2 X 2 tensor in pytorch?
Suppose mat = torch.rand((5,7)) and I want to get values from 1st dimension (here, 7) by passing the indices, say idxs=[0,4,2,3,6]. The way I am able to do it now is by doing mat[[0,1,2,3,4],idxs]. I expected mat[:,idxs] to work, but it didn't. Is the first option the only way or is there a better way?
torch.gather is what you are looking for: torch.gather(mat, 1, torch.tensor(idxs)[:, None])
https://stackoverflow.com/questions/66329802/
Pytorch N - Beats model throwing error: 'str' object has no attribute '__name__'
I'm trying to replicate pytorch's N - Beats model in colab. I copied the same code from https://pytorch-forecasting.readthedocs.io/en/stable/tutorials/ar.html to a colab notebook. There is an error showing up at training cell. import os import warnings warnings.filterwarnings("ignore") os.chdir("../../....
downgrading pytorch-lightning from 1.2.1 to 1.1.8 solved it for me.
https://stackoverflow.com/questions/66342637/
creating a progress bar for a validation test Python
The following code is used to find p-values for a significant test on Cifar-10 database. Because we need a min of 1000 permutations, it is a very slow process, and I want to inlude a progress bar to show how time for each permutation. I was thinking of using the tqdm library and sleep function, but am stuck on where to...
from tqdm import tqdm def validate_significance(val_loader, model, criterion, args): model.eval() vec_acc1 = [] vec_acc1_chance = [] vec_acc5 = [] vec_acc5_chance = [] for ss in tqdm(range(0, args.num_permutations)): ....
https://stackoverflow.com/questions/66351236/
Pytorch C++ API : CMake Issue
I want to include the pytorch C++ API to the large C++ software I am working on. For legacy reasons, I must use find_package and the associated find_path and find_library functions, instead of the proposed target_link_libraries. Here's my FindTORCH.cmake : include( FindPackageHandleStandardArgs ) find_path( TORCH_INC...
Torch exposes its own targets. To use them effectively, simply remove FindTORCH.cmake from your project, and add /path/to/libtorch/ to your prefix path: cmake_minimum_required(VERSION 3.19) # or whatever version you use project(your-project CXX) list(APPEND CMAKE_PREFIX_PATH "/path/to/libtorch/") find_packag...
https://stackoverflow.com/questions/66356955/
Why does Python's cProfile report a different elapsed time than using time.time() deltas when using PyTorch?
I am profiling some code using PyTorch. I am aware the CUDA normally has some asynchronous execution (see PyTorch docs), but I believe that transferring from GPU to CPU will generally force synchronization. For this reason, I decided to naively profile using cProfile, but I notice that the time reported by Profile.enab...
Empirically, it seems like cProfile will not "hook" into the code if you don't "flush" all of the outputs, or if you're code isn't fully wrapped in a function. See more detail in the comments here: https://github.com/EricCousineau-TRI/repro/blob/bdef8a14b5/python/cprofile_with_torch/repro.py#L75-L9...
https://stackoverflow.com/questions/66361942/
CUDA initialization: Unexpected error from cudaGetDeviceCount()
I was running a deep learning program on my Linux server and I suddenly got this error. UserWarning: CUDA initialization: Unexpected error from cudaGetDeviceCount(). Did you run some cuda functions before calling NumCudaDevices() that might have already set an error? Error 804: forward compatibility was attempted on no...
I just tried rebooting. Problem solved. Turned out that it was caused by NVIDIA NVML Driver/library version mismatch.
https://stackoverflow.com/questions/66371130/
from ._nnls import nnls ImportError: DLL load failed: The specified module could not be found
While running a UNet traning code I found DLL load failed error. Here is the code: ''' import torch import scipy import albumentations as A from ._nnls import nnls from albumentations.pytorch import ToTensorV2 from tqdm import tqdm import torch.nn as nn import torch.optim as optim from unet_model...
The below solution worked for me. conda remove --force numpy, scipy pip install -U numpy, scipy Successfully installed numpy-1.19.5 scipy-1.5.4 Reference: https://github.com/conda/conda/issues/6396#issuecomment-350254762
https://stackoverflow.com/questions/66378763/
sqrt_vml_cpu not implemented for 'Long'
a = torch.full([2, 2], 9) b = a.sqrt() print(b) b = a.rsqrt() print(b) RuntimeError: sqrt_vml_cpu not implemented for 'Long' a is torch.LongTensor, but sqrt and rsqrt do not suppor Long, what should I do?
I couldn't reproduce your code because, when I run it, I get the following error (PyTorch 1.6): RuntimeError: Providing a bool or integral fill value without setting the optional `dtype` or `out` arguments is currently unsupported. In PyTorch 1.7, when `dtype` and `out` are not set a bool fill value will return a tenso...
https://stackoverflow.com/questions/66382240/
Why is my parameter not changing and its gradient 0?
I am building a really simple model to learn the parameter in a Poisson model and I am not sure where I am going wrong. I am using pytorch.nn and doing the following. I made some really simple fake data # This is the value I am trying to estimate x = torch.tensor(2.0) # This is a value drawn from the Poisson(x) dist...
Your model doesn't have any trainable parameters. See this link torch.nn.parameter.Parameter A kind of Tensor that is to be considered a module parameter.
https://stackoverflow.com/questions/66386878/
Floating point operations results are different in Android, TensorFlow and Pytorch
I am trying to compare the floating point numbers on Android, Tensorflow and Pytorch. What I have observed is I am getting same result for Tensorflow and Android but different on Pytorch as Android and Tensorflow are performing round-down operation. Please see the following result: TensorFlow import tensorflow as tf a=...
You are not using the same level of precision when printing, hence why you get different results. Internally, those results are identical, it's just an artifact that you see due do the default of python to print only 7 digits after the comma. If we set the same level of precision in numpy as the one you set in PyTorch,...
https://stackoverflow.com/questions/66388745/
Why embed dimemsion must be divisible by num of heads in MultiheadAttention?
I am learning the Transformer. Here is the pytorch document for MultiheadAttention. In their implementation, I saw there is a constraint: assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" Why require the constraint: embed_dim must be divisible by num_heads? If w...
When you have a sequence of seq_len x emb_dim (ie. 20 x 8) and you want to use num_heads=2, the sequence will be split along the emb_dim dimension. Therefore you get two 20 x 4 sequences. You want every head to have the same shape and if emb_dim isn't divisible by num_heads this wont work. Take for example a sequence 2...
https://stackoverflow.com/questions/66389707/
torch.nn.fucntional.interpolate(): Parameters Settings
I'm using torch.nn.functional.interpolate() to resize an image. Firstly I use transforms.ToTensor() to transform an image into a tensor, which have size of (3, 252, 252), (252, 252) is the size of the imported image. What I want to do is to create a tensor with size (3, 504, 504) with interpolate() function. I set the ...
If you're using scale_factor you need to give batch of images not single image. So you need to add one batch by using unsqueeze(0) then give it to interpolate function as follows: import torch import torch.nn.functional as F img = torch.randn(3, 252, 252) # torch.Size([3, 252, 252]) img = img.unsqueeze(0) # torch.Si...
https://stackoverflow.com/questions/66407004/
pytorch int32 to int64 conversion
I'm trying to convert a simple image mask to int64 image = np.array([[1, 2], [3, 4]], dtype='int32') transform = Compose([ torch.from_numpy, ConvertImageDtype(torch.int64) ]) However, transform(image) yields tensor([[ 4294967296, 8589934592], [12884901888, 17179869184]]) Is there something wrong, o...
If you skip torch's conversion, the image is transformed correctly. image = np.array([[1, 2], [3, 4]], dtype='int64') transform = Compose([ torch.from_numpy ]) transform(image) # tensor([[1, 2], # [3, 4]])
https://stackoverflow.com/questions/66420588/
Importing MNIST dataset from local directory in a closed system
I am trying to run a tutorial based on MNIST data in a cluster and the node where training script runs don't have internet access so I am manually placing the MNIST dataset in the desired directory but I am getting Dataset not found error. I am trying to run this tutorial on the cluster. I have tried this answer but th...
You have to specify a root folder, not a full path to the processed file: root (string): Root directory of dataset where MNIST/processed/training.pt and MNIST/processed/test.pt exist. In your case: root is /scratch/netra Thus, train_dataset = \ datasets.MNIST('/scratch/netra-%d' % hvd.rank(), train=True, download=Tr...
https://stackoverflow.com/questions/66430702/
how can i reshape these images as a 2d images tensors?
I am currently working with rgb images loaded as tensors and i would like to reshape them to be 2d tensors to implement deep neural networks on them the shape which I am currently working on is : images.shape torch.Size([32, 3, 244, 244]) I dont know how to deal with the last two fields and also how to flatten the 3 ...
Your requirement is too hazy and it's unclear what you want to achieve with these images. Do they come with labels? If not, do you want to use an unsupervised method such as an autoencoder? Looking at the shape of your images tensor: torch.Size([32, 3, 244, 244]) This means that there are 32 color (RGB) images in this...
https://stackoverflow.com/questions/66448486/
Loss of Conv-neural-network not decreasing, instead obsoleting
I have a convolutional neural network in vgg architecture "style" (down below) to classify images if there is a cat on the picture, or a dog. My training set contains 25000 images cropped to 256px each side. I tried different learning rates, different loss functions and much more but my loss keeps fluctuating...
have you tried adding momentum to your SGD optimizer? optimizer = optim.SGD(model.parameters(), lr=0.1, weight_decay=0.0016, momentum=0.9) Or, a different optimizer such as Adam or AdaDelta, which will use adaptive learning rate? Also, it does not look like your training data is shuffled - can it happen than some batc...
https://stackoverflow.com/questions/66453419/
RuntimeError: CUDA error: device-side assert triggered on loss function
/pytorch/aten/src/ATen/native/cuda/Loss.cu:102: operator(): block: [18,0,0], thread: [54,0,0] Assertion input_val >= zero && input_val <= one failed. /pytorch/aten/src/ATen/native/cuda/Loss.cu:102: operator(): block: [18,0,0], thread: [55,0,0] Assertion input_val >= zero && input_val <= one ...
There might be two reasons of the error: As the log says input_val is not between the range [0; 1]. So you should ensure that model outputs are in that range. You can use torch.clamp() of pytorch. Before calculating the loss add the following line: out = out.clamp(0, 1) Maybe you are sure that model outputs are...
https://stackoverflow.com/questions/66456541/
In training mode, targets should be passed
I am new to deep learning and have the project on detecting traffic lights in university where we can use open-source code. So, I tried to run the code on kaggle https://www.kaggle.com/endoruk1234/trafficlightdetection-fasterrcnn-pytorch/log However on the stage of testing the saved model on a video, I got this mistake...
In your example you don't explain how you load your model, but I think you have forgotten model.eval(). This function is a kind of switch for some specific layers/parts of the model that behave differently during training and inference (evaluating) time. To make inferences, you can load your model like this : model.lo...
https://stackoverflow.com/questions/66475189/
Why does it take so long print the value of a GPU tensor in Pytorch?
I wrote this pytorch program to compute a 5000*5000 matrix multiplication on GPU, 100 iterations. import torch import numpy as np import time N = 5000 x1 = np.random.rand(N, N) ######## a 5000*5000 matrix multiplication on GPU, 100 iterations ####### x2 = torch.tensor(x1, dtype=torch.float32).to("cuda:0") ...
Pytorch CUDA operations are asynchronous. Most operations on GPU tensors are actually non blocking until a derived result is requested. This means that until you ask for a CPU version of a tensor, commands like matrix multiply are basically being processed in parallel to your code. When you stop the timer there's no gu...
https://stackoverflow.com/questions/66477371/
'LSTM' object has no attribute '_flat_weights_names'
While executing iNltk library, I am getting an error. I have latest versions of pytorch and torchvision. 'LSTM' object has no attribute '_flat_weights_names' After re-searching on some blogs some people suggested to downgrade the version to 1.2 So i tried below installation from https://pytorch.org/get-started/previou...
I tried using pip, but that did not work for me. conda fixed the issue. Setup a conda environment first and activate it. Install iNLTK using pip in conda as follows: pip install inltk Remove the version of PyTorch installed as a dependency for iNLTK. pip uninstall torch Install the desired version of PyTorch. conda i...
https://stackoverflow.com/questions/66478043/
How to solve dist.init_process_group from hanging (or deadlocks)?
I was to set up DDP (distributed data parallel) on a DGX A100 but it doesn't work. Whenever I try to run it simply hangs. My code is super simple just spawning 4 processes for 4 gpus (for the sake of debugging I simply destroy the group immediately but it doesn't even reach there): def find_free_port(): "&quot...
The following fixes are based on Writing Distributed Applications with PyTorch, Initialization Methods. Issue 1: It will hang unless you pass in nprocs=world_size to mp.spawn(). In other words, it's waiting for the "whole world" to show up, process-wise. Issue 2: The MASTER_ADDR and MASTER_PORT need to be t...
https://stackoverflow.com/questions/66498045/
unable to import pytorch-lightning
I installed pytorch-lightning using pip, and I'm running on Mac. I tried: ! pip install pytorch-lightning --upgrade ! pip install pytorch-lightning-bolts (finished successfully) and then: import pytorch_lightning as pl and what I get is: -- ------------------------------------------------------------------------- Imp...
I guess this is an outdated issue as we have cut out TorchMetrics to a standalone package. Please, check out the latest PytorchLightning.
https://stackoverflow.com/questions/66505335/
pytorch deep learning loading data sequentially and efficiently
I have been doing neural network analysis on 20 thousand "images", each image represented in the form of the intensity of 100 * 100 * 100 neurons. x = np.loadtxt('imgfile') x = x.reshape(-1, img_channels, 100, 100, 100) //similarly for target variable 'y' Above, the first dimension of x will be the number of...
Digging a while after posting the question, found out there is, of course, a way using torch.utils.data.Dataset. Each image-data can be saved in a separate file and all the filenames are listed in 'filelistdata'. Only the batch_size number of images will be loaded into memory when called using DataLoader (in the backgr...
https://stackoverflow.com/questions/66522854/
How to do elementwise comparison sum without for loop
The for loop makes my program very slow. I would've used np.sum(target==output) but I need the argmax value for each row in the output. How can I speed this up? The output is a tensor data type for i, x in enumerate(target): if target[i] == torch.argmax(output[i]): correct_class += 1
You could vectorize the above using np.argmax's axis argument, to obtain the indices of the maximum value across the rows: (target==np.argmax(output, axis=1)).sum() For instance: output = np.random.choice([0,1],(4,2)) print(output) array([[1, 1], [0, 1], [0, 1], [0, 1]]) target = np.array([[0,1,0,...
https://stackoverflow.com/questions/66532614/
MMDetection loading from own training checkpoint for inference produces garbage detections
I've trained up a very simple model using the MMDetection colab tutorial and then verifying the result using: img = mmcv.imread('/content/mmdetection/20210301_145246_123456.jpg') img = cv2.resize(img, (0,0), fx=0.25, fy=0.25) model.cfg = cfg result = inference_detector(model, img) show_result_pyplot(model, img, result...
One of the mistakes in your code is that you have not updated num_classes for mask_head. Our aim here should be to replicate the same config file that was used for training should also be used for testing/validation. If you have trained the model using 1 num_classes for bbox_head and mask_head in the config file but fo...
https://stackoverflow.com/questions/66537288/
Unable to import pytorch_lightning on google colab
I have done the following: !pip install pytorch_lightning -qqq import pytorch_lightning But get the following error: ImportError Traceback (most recent call last) <ipython-input-7-d883b15aac58> in <module>() ----> 1 import pytorch_lightning --------------------------------...
As said in Issue #6415 on Github, try installing from the GitHub. It worked for me. !pip install git+https://github.com/PyTorchLightning/pytorch-lightning import pytorch_lightning as pl print(pl.__version__) Output: 1.3.0dev It seems that the error is coming from Issue #6210 and they say it was fixed. I guess it wasn...
https://stackoverflow.com/questions/66538407/
One hot encoding in pytorch
I am really new to coding, right now I am trying to turn my label to one hot encoding. I have already done transferring the np.array to tensor as shown below tensor([4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 3., 3., 3., 3., 3., 3....
You will have to convert it in long type. Can't do it with float. F.one_hot only takes LongTensor. F.one_hot(t.long())
https://stackoverflow.com/questions/66543659/
How to run a pytorch model server inside docker?
I am trying to create a docker image to make it run as a server for serving a model in pytorch. I converted the .pt model file to .MAR file in my local machine and i copied the .MAR file inside the docker image. I created a dockerfile: FROM ubuntu:18.04 ENV TZ=Asia/Shanghai ENV DEBIAN_FRONTEND noninteractive RUN apt-g...
I hope I understand the problem. When you do docker run torchserve:local ...., by default it runs the CMD which is torchserve --start --model-store model_store --models densenet161=densenet161.mar but since the command runs in the background, your newly created docker container will immediately exit. Due to this same p...
https://stackoverflow.com/questions/66551874/
how to import a torch 1.7.1 when torch 1.4.0 is also installed
how to import a torch 1.7.1 when torch 1.4.0 is also installed When I run the command: ! pip list It lists all libraries with : torch 1.7.1 Now when I run: >>>import torch >>>torch.__version__ '1.4.0' How Do I import torch==1.7.1 in the python program? I am using python 3.8.3 and windows 10
Slightly different way to answer your question, but if you want to have two versions of torch installed simultaneously for different purposes (e.g. running different programs), my recommendation would be to use torch 1.7.1 and torch 1.4.1 in separate virtual environments. Please see the links below for guides on getti...
https://stackoverflow.com/questions/66552454/
Understanding Jacobian tensor gradients in pytorch
I was going through official pytorch tut, where it explains tensor gradients and Jacobian products as follows: Instead of computing the Jacobian matrix itself, PyTorch allows you to compute Jacobian Product for a given input vector v=(v1…vm). This is achieved by calling backward with v as an argument: inp = torch.ey...
We will go through the entire process: from computing the Jacobian to applying it to get the resulting gradient for this input. We're looking at the operation f(x) = (x + 1)², in the simple scalar setting, we get df/dx = 2(x + 1) as complete derivative. In the multi-dimensional setting, we have an input x_ij, and an ou...
https://stackoverflow.com/questions/66569022/
HTTP Error when trying to download MNIST data
I am using Google Colab for training a LeNet-300-100 fully-connected neural network on MNIST using Python3 and PyTorch 1.8. To apply the transformations and download the MNIST dataset, the following code is being used: # MNIST dataset statistics: # mean = tensor([0.1307]) & std dev = tensor([0.3081]) mean = np.arra...
I was having the same 503 error and this worked for me !wget www.di.ens.fr/~lelarge/MNIST.tar.gz !tar -zxvf MNIST.tar.gz from torchvision.datasets import MNIST from torchvision import transforms train_set = MNIST('./', download=True, transform=transforms.Compose([ transforms.ToTensor(), ]), train=True) test_set = M...
https://stackoverflow.com/questions/66577151/
Bound optimization using pytorch
How to include bounds when using optimization method in pytorch. I have a tensor of variables, each variable has different bound. upper_bound = torch.tensor([1,5,10], requires_grad=False) lower_bound = torch.tensor([-1,-5,-10], requires_grad=False) X = torch.tensor([10, -60, 105], require_grad=True) for _ in ...
Gradient descent is not the best method to achieve constrained optimization, but here you can enforce your constraints with : x = ((X-lower_bound).clamp(min=0)+lower_bound-upper_bound).clamp(max=0)+upper_bound Requires two clamp instead of one but I could not find any native way to achieve this.
https://stackoverflow.com/questions/66584157/
RuntimeError: mean is not implemented for type torch.ByteTensor
I am getting this error after running my code: "RuntimeError: mean is not implemented for type torch.ByteTensor"? Do anyone know what I am doing wrong here? accuracy = torch.mean(output)
Got it, basically torch.mean() isn't implemented on torch.ByteTensor so we can convert it to FloatTensor which is supported by torch.mean(). So the code will change to: accuracy = torch.mean(output.type(torch.FloatTensor))
https://stackoverflow.com/questions/66586141/
RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED using pytorch
I am trying to run a simple pytorch sample code. It's works fine using CPU. But when using GPU, i get this error message: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 889, in _cal...
There is some discussion regarding this here. I had the same issue but using cuda 11.1 resolved it for me. This is the exact pip command pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/torch_stable.html
https://stackoverflow.com/questions/66588715/
How to shift columns (or rows) in a tensor with different offsets in PyTorch?
In PyTorch, the build-in torch.roll function is only able to shift columns (or rows) with same offsets. But I want to shift columns with different offsets. Suppose the input tensor is [[1,2,3], [4,5,6], [7,8,9]] Let's say, I want to shift with offset i for the i-th column. Thus, the expected output is [[1,8,6], [4,...
I was sceptical about the performance of torch.gather so I searched for similar questions with numpy and found this post. Similar solution from NumPy to Pytorch I took the solution from @Andy L and translated it into pytorch. However, take it with a grain of salt, because I don't know how the strides work: from numpy....
https://stackoverflow.com/questions/66596699/
GPU in docker container for deep learning task
Recently, I have started working on using docker images. I want to deploy PyTorch based text classification model which requires GPU to run on. When the docker image is called upon, then it's not able to detect GPU in the VM. Hence, my code is failing by throwing no Cuda device found error. This is my base image FROM g...
Installing Nvidia drivers into the container doesn't help since the GPU device isn't exposed to the container. Running with nvidia-docker instead does.
https://stackoverflow.com/questions/66603536/
Pytorch showing the error: 'NoneType' object has no attribute 'zero_'
I am using Python 3.8 and VSCode. I tried to create a basic Neural Network without activations and biases but because of the error, I'm not able to update the gradients of the weights. Matrix Details: Layer Shape: (1, No. of Neurons) Weight Layer Shape: (No. of Neurons in the previous layer, No. of Neurons in the next ...
Your model doesn't have any trainable parameters for the grad to be calculated. Use torch's Parameter. See this link for creating a module with learnable parameters. torch.nn.parameter.Parameter A kind of Tensor that is to be considered a module parameter.
https://stackoverflow.com/questions/66610575/
Why does my pytorch NN return a tensor of nan?
I have a quite simple neural network which takes a flattened 6x6 grid as input and should output the values of four actions to take on that grid, so a 1x4 tensor of values. Sometimes after a few runs though for some reason I am getting a 1x4 tensor of nan tensor([[nan, nan, nan, nan]], grad_fn=<ReluBackward0>) M...
nan values as outputs just mean that the training is instable which can have about every possible cause including all kinds of bugs in the code. If you think your code is correct you can try addressing the instability by lowering the learning rate or use gradient clipping.
https://stackoverflow.com/questions/66625645/
tuple unpacking in X_test
i am following a simple tutorial in PyTorch. The tutorial is using the diabetes dataset and built a simple two-layer network. In some part of the tutorial there exist the following part of the code where there exists an iteration on the X_test using enumerate. predictions=[] with torch.no_grad(): for i, data ...
enumerate simply enumerates iterable items. e.g. my_list = ['cat', 'dog', 'elephant'] print(list(enumerate(my_list))) >> [(0, 'cat'), (1, 'dog'), (2, 'elephant')] In your case i is an index of data variable in some loop state (it is not used tho) and data is a feature tensor of one row in your dataset.
https://stackoverflow.com/questions/66628243/
GPU underutilized in Actor Critic (A2C) Stable Baselines3 implementation
I am trying to use A2C of StablesBaselines3 for training an agent on my custom environment. My problem is that my GPU Utilization is very less (around 10 % only) while my CPU utilization has hit the ceiling. Because of this the training is very very slow. I have tried the following things as per this discussion thread ...
Stable baselines is using your gpu ... if you look task manager on second tab click on your gpu and instead of 3D select cuda and you will see the usage of cuda I had some troubles with my env because my env uses pandas .. and pandas use cpu .. on windows is not possible easly to use cudf so my cpu was using 100% I use...
https://stackoverflow.com/questions/66628280/
how to solve this (Pytorch RuntimeError: 1D target tensor expected, multi-target not supported)
i am newbie in pytorch and deep learning my data set 53502 x 58, i have problem this my code model = nn.Sequential( nn.Linear(58,64), nn.ReLU(), nn.Linear(64,32), nn.ReLU(), nn.Linear(32,16), nn.ReLU(), nn.Linear(16,2), nn.LogSoftmax(1) ) criterion = nn.NLLLoss() optimizer = optim.AdamW...
When using NLLLoss the target tensor must contain the index representation of the labels and not one-hot. So for example: I guess this is what your target looks like: target = [0, 0, 1, 0] Just convert it to just the number which is the index of the 1: [0, 0, 1, 0] -> [2] [1, 0, 0, 0] -> [0] [0, 0, 0, 1] -> [...
https://stackoverflow.com/questions/66635987/
Difference between Xavier weights pytorch implementation
What is the difference between nn.init.xavier_uniform and nn.init.xavier_uniform_ when initialising weights?
The _ convention in nn.init.xavier_uniform_ is PyTorch's way of doing an operation in place. This convention applies to many of its functions.
https://stackoverflow.com/questions/66640099/
Pass an arbitrary image size to cnn in pytorch
I'm trying to train a lenet model in pytorch, The ideia is to put images of any size in it, so I started doing with nn.AdaptiveAvgPool2d but the error comes as mat1 dim 1 must match mat2 dim 0 Here is my code class LeNet5(nn.Module): def __init__(self, num_classes=10): super(LeNet5, self).__init__() self.c...
if you read the theory on AdaptiveAvgPool2d, this is what it says " we specify the output size And the stride and kernel-size are automatically selected to adapt to the needs" More info available here Hence Your spatial dimension is reduced by AdaptiveAvgPool2d and not the depth of feature maps. So, the spati...
https://stackoverflow.com/questions/66640116/
Performance in reading dicom files with SimpleITK and PyTorch
I want to directly load image from memory to python in pytorch tensor format. I modified GetArrayViewFromImage() function by replacing those lines: image_memory_view = _GetMemoryViewFromImage(image) array_view = numpy.asarray(image_memory_view).view(dtype = dtype) by: image_memory_view = _GetMemoryViewFromImage(image)...
While this does not directly answer your question, I strongly recommend using the torchio package, instead of dealing with these IO issues yourself (torchio uses SimpleITK under the hood).
https://stackoverflow.com/questions/66653808/
How to vectorize loss for a LSTM doing sequential Language modelling
So I have an assignment involving Language Modelling and I passed all the unit tests but my code is too slow to run. I think it's because of the way I compute my loss. The formula we're given is the following: My naive implementation is the following: losses_batch_list = [] batch_size = log_probas.size(0) for b in ran...
B = batch_size T = sequence_length (padded) N = vocab_size if type(mask_b) == torch.bool: mask = mask.view(-1) # (B, T) -> (B*T,) else: mask = mask.bool().view(-1) # (B, T) -> (B*T,) log_probas = log_probas.view(-1, N) # (B, T, N) -> (B*T, N) targets = target.view(-1, 1) # (B, T) -> (B*T, 1) loss =...
https://stackoverflow.com/questions/66665589/
Pytorch MNIST autoencoder to learn 10-digit classification
I'm trying to build a simple autoencoder for MNIST, where the middle layer is just 10 neurons. My hope is that it will learn to classify the 10 digits, and I assume that would lead to the lowest error in the end (wrt reproducing the original image). I have the following code, which I've already played around with a fai...
Autoencoder is technically not used as a classifier in general. They learn how to encode a given image into a short vector and reconstruct the same image from the encoded vector. It is a way of compressing image into a short vector: Since you want to train autoencoder with classification capabilities, we need to make ...
https://stackoverflow.com/questions/66667949/
pytorch collections.OrderedDict' object has no attribute 'to'
this is my main code,but I don't know how to fix the problem? device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = torch.load('./checkpoints/fcn_model_5.pth') # 加载模型 model = model.to(device)
You are loading the checkpoint as a state dict, it is not a nn.module object. checkpoint = './checkpoints/fcn_model_5.pth' model = your_model() # a torch.nn.Module object model.load_state_dict(torch.load(checkpoint )) model = model.to(device)
https://stackoverflow.com/questions/66670326/
How to calculate the mean and the std of cifar10 data
Pytorch is using the following values as the mean and std for the cifar10 data: transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) I need to understand the concept behind calculating it because this data is 3 channel image and I do not understand what is summed and divided over what and so on. Also if someone can s...
The 0.5 values are just approximates for cifar10 mean and std values over the three channels (r,g,b). The precise values for cifar10 train set are mean: 0.49139968, 0.48215827 ,0.44653124 std: 0.24703233 0.24348505 0.26158768 You may calculate these using the following script: import torch import numpy import torchvi...
https://stackoverflow.com/questions/66678052/
How to incoporate mask into negative likelihood loss (torch.nn.functional.nll_loss)
Hello I am implementing a lstm for language modelling for homework and I am at the loss implementation phase. Our instructor told us to use F.nll_loss but the sequences are padded and we have to take into account a mask that is given which tells us when the sequences stop. input: log_probas (batch_size, sequence_lengt...
you could reshape the tensors and use mask to select non-padded tokens, and compute the loss vocab_size = log_probas.size(-1) log_probas = log_probas.view(-1, vocab_size) target = target.view(-1) mask = mask.view(-1).bool() loss = F.nll_loss(log_probas[mask], targets[mask])
https://stackoverflow.com/questions/66678314/
PyTorch can't find the name?? (NameError: name 'device' is not defined)
sorry - I'm a complete beginner! I am trying to build a 'mini-system' using the Torchreid libraries from https://kaiyangzhou.github.io/deep-person-reid/index.html# In their version they use CUDA but my Mac is not compatible with CUDA and it doesn't have a CUDA enabled GPU so I installed the CPU-only version of PyTorch ...
Define device variable before the usage: import torch ... model = torchreid.models.build_model( name='resnet50', num_classes=datamanager.num_train_pids, loss='softmax', pretrained=True ) # Just right before the actual usage device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = m...
https://stackoverflow.com/questions/66679163/
Why is pytorch softmax function not working?
so this is my code import torch.nn.functional as F import torch inputs = [1,2,3] input = torch.tensor(inputs) output = F.softmax(input, dim=1) print(output) is the reason why the code not working because of the dim? the error here: File "c:\Users\user\Desktop\AI\pytorch_jovian\linear_reg.py", line 19, in ...
Apart from dim=0, there is another issue in your code. Softmax doesn't work on a long tensor, so it should be converted to a float or double tensor first >>> input = torch.tensor([1, 2, 3]) >>> input tensor([1, 2, 3]) >>> F.softmax(input.float(), dim=0) tensor([0.0900, 0.2447, 0.6652])
https://stackoverflow.com/questions/66690233/
Mapping tensor in pytorch
I have the following two tensors: img is a RGB image of shape (224,224,3) uvs is a tensor with same spacial size e.g. (224, 224, 2) that maps to coordinates (x,y). In other words it provides (x,y) coordinates for every pixel of the input image. I want to create now a new output image tensor that contains on index (x,...
Try with: out = img[idx[...,0], idx[...,1]]
https://stackoverflow.com/questions/66693083/
Define manually sorted MNIST dataset with batch size = 1 in PyTorch
[] : this indicates a batch. For example, if the batch size is 5, then the batch will look something like this [1,4,7,4,2]. The length of [] indicates the batch size. What I want to make a training set something looks like this: [1] -> [1] -> [1] -> [1] -> [1] -> [7] -> [7] -> [7] -> [7] -> [...
If you want a DataLoader where you just want to define the class label for each sample then you can make use of the torch.data.utils.Subset class. Despite its name it doesn't necessarily need to define a subset of dataset. For example import torch import torchvision import torchvision.transforms as T from itertools imp...
https://stackoverflow.com/questions/66695251/
How to find partial derivative in pytorch
I have a model u(x,t) with layers 2X50, then 50X50, and 50X1. I train the model with input x,t of size [100,2]. In the final layer I get u and now I want to differentiate it w.r.t to x and t and double differentiate w.r.t to x. How do I do this in PyTorch?
You can use PyTorch's autograd engine like so: import torch x = torch.randn(100, requires_grad=True) t = torch.randn(2, requires_grad=True) u = u(x,t) # 1st derivatives dt = torch.autograd.grad(u, t)[0] dx = torch.autograd.grad(u, x, create_graph=True)[0] # 2nd derivatives (higher orders require `create_graph=True`)...
https://stackoverflow.com/questions/66708568/
How can i use pytorch model in C#?
I have a pytorch model in NLP and a script for use it in python. Now i want to use this script in C#. I tried run python script from C# and it worked. I get user sentence in C#, pass it to python and its outputs use in C#. The problem is that i want to do this work in a loop until user select exit but every time it goe...
you can export the model in ONNX format and then use the OpenCV DNN module or tensorrt for inference purposes. It will give you a significant boost in speed and your whole code will be in C#.
https://stackoverflow.com/questions/66710421/
PyTorch How to code Multi Head Self Attention in parallel?
I want to encode the word (embedding) sequence with 16-Head Self-Attention. Currently I use a nn.ModuleList together with a for loop to generate the output of each head then concatenate all of them. This approach is extremely slow and I wonder if there's way to code MHA in parallel? To generalize, I would like to know ...
I figured it out. Since nn.Linear is acctually an affine transformation with a weights matrix and a bias matrix, one can easily wrap such matrices in nn.Parameter and take advantage of broadcast semantics to achieve the goal. Edit: I also find a nn.Linear(d_model, n_heads*d_key) functions identically.
https://stackoverflow.com/questions/66711170/
PyTorch using LR-Scheduler with param groups of different LR's
I have defined the following optimizer with different learning rates for each parameter group: optimizer = optim.SGD([ {'params': param_groups[0], 'lr': CFG.lr, 'weight_decay': CFG.weight_decay}, {'params': param_groups[1], 'lr': 2*CFG.lr, 'weight_decay': 0}, {'params': param_groups[2], ...
You are right, learning rate scheduler should update each group's learning rate one by one. After a bit of testing, it looks like, this problem only occurs with CosineAnnealingWarmRestarts scheduler. I've tested CosineAnnealingLR and couple of other schedulers, they updated each group's learning rate: scheduler = torc...
https://stackoverflow.com/questions/66711210/
How to join two tensors
I have two tensors of dimension [3,1]. I need to join them as a [3,2] tensor. t = torch.tensor([[3.],[1],[2]], requires_grad=True) x = torch.tensor([[1.],[4],[5]], requires_grad=True) I tried torch.cat and torch.stack but neither work for me.
With cat you need to specify the dimension the tensors are concatenated along. By default this is 0, but you wish to use 1: import torch res = torch.cat([t,x], axis=1)
https://stackoverflow.com/questions/66713761/
RuntimeError: 1D target tensor expected, multi-target not supported Python: NumPy
I am dealing with a CNN and I get the following error on the line loss = criterion(outputs, data_y): Here is the relevant code snippet: def run(model, X_train, Y_train, X_test, Y_test, learning_rate=0.01, num_epochs=100, minibatch_size=8, print_cost=True): seed = 0 ...
This error usually appears when you pass a one-hot-encoded target to CrossEntropy or NLLLoss (instead of a single class index), but your problem is simpler - you just have a typo here: data_y = torch.LongTensor(batch_x) # <- should be `batch_y`
https://stackoverflow.com/questions/66720209/
Average Pooling layer in Deep Learning and gradient artifacts
I know that in Convolution layers the kernel size needs to be a multiplication of stride or else it will produce artefacts in gradient calculations like the checkerboard problem. Now does it also work like that in Pooling layers? I read somewhere that max pooling can also cause problems like that. Take this line in the...
This doesn't look like a checkerboard artifact honestly. Also I don't think discriminator would be the problem, it's usually about image restoration (generator or decoder). Took a quick look at the MUNIT and what they use in Decoder is torch.nn.Upsample with nearest neighbor upsampling (exact code line here). You may t...
https://stackoverflow.com/questions/66720639/
Pytorch RNN with no nonlinearity
Is it possible to implement an RNN layer with no nonlinearity in Pytorch like in Keras where one can set the activation to linear? By removing the nonlinearlity, I want to implement a first-order infinite-impulse-response (IIR) filter with a differentiable parameter and integrate it into my model for end-to-end learnin...
Removing non-linearity from RNN turns it into a linear dense layer without any activation. If that is what you want, then simply use nn.linear and set activation to None Explanation Here is why this happens. Fundamentally, an RNN for timesteps works as below - h(t) = tanh(U.x(t) + W.h(t−1) + b) h(0) = tanh(U0.x(0) + ...
https://stackoverflow.com/questions/66726974/
Cannot perform reduction function min on tensor with no elements because the operation does not have an identity at THCTensorMathReduce.cu:64
I am configuring a GitHub repo in which the author stated that you have to install pytorch=0.4 and python=3.7. Now, I have CUDA 11.0 and the Pytorch version is conflicting with CUDA. After installing the Pytorch it gives the below error. Any hint? My Conda List # Name Version Build ...
As the error message suggests, the argument for min function is empty. The behavior of torch.min([]) is undefined. Check that dist[i][mask[i] == 0] is not empty, before taking min of it.
https://stackoverflow.com/questions/66729277/
Is torch.float32 different from numpy's float32?
Setting precision as 30 in PyTorch shows: >>> torch.set_printoptions(precision=30) >>> y tensor([[-0.388252139091491699218750000000, -0.610148549079895019531250000000, -1.333969473838806152343750000000, -1.027917861938476562500000000000, -0.498563587665557861328125000000, -0.09679349...
By default, if it takes less digits than the configured value of precision to distinguish a floating-point value from other values of the same dtype, NumPy will only print as many digits as necessary for that. You have to set the floatmode option to 'fixed' to get the behavior you were expecting: numpy.set_printoptions...
https://stackoverflow.com/questions/66730777/
Split a torch tensor using a same-sized tensor of indices
Let's say that I have tensor t = torch.tensor([1,2,3,4,5]) I want to split it using a same-sized tensor of indices that tells me for each element, in which split it should go. indices = torch.tensor([0,1,1,0,2]) So that the final result is splits [tensor([1,4]), tensor([2,3]), tensor([5])] Is there a neat way to do ...
One could do it using argsort for general case: def mask_split(tensor, indices): sorter = torch.argsort(indices) _, counts = torch.unique(indices, return_counts=True) return torch.split(t[sorter], counts.tolist()) mask_split(t, indices) Though it might be better to use @flawr answer if this is your real ...
https://stackoverflow.com/questions/66736492/
Installing PyTorch with CUDA in setup.py
I'm trying to specify PyTorch with CUDA in install_requires. The command to install with pip is pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio===0.8.0 -f https://download.pytorch.org/whl/torch_stable.html How do I do that in the setup.py install_requires?
I also faced same problem later I fixed it but using this in setup.py files and it worked, just add these lines as in your setup.py file. "torch@https://download.pytorch.org/whl/cu111/torch-1.8.0%2Bcu111-cp37-cp37m-linux_x86_64.whl", "torchvision@https://download.pytorch.org/whl/cu111/torchvision-0.9.0%2...
https://stackoverflow.com/questions/66738473/
with torch.no_grad: AttributeError: __enter__
with torch.no_grad:AttributeError: __enter__ I got this error while running pytorch code. I have torch==0.4.1 torchvision==0.3.0, I run the code in google colab.
torch.no_grad is a contextmanager it really has __enter__ and __exit__. You should use it with with statement, like this with context_manager(): pass Thus, simply replace with torch.no_grad: (accessing the attribute) with with torch.no_grad(): (calling a method) to use contextmanager properly.
https://stackoverflow.com/questions/66744675/
Same weights, implementation but different results n Keras and Pytorch
I have an encoder and a decoder model (monodepth2). I try convert them from Pytorch to Keras using Onnx2Keras, but : Encoder(ResNet-18) succeeds I build the decoder myself in Keras (with TF2.3), and copy the weights (numpy array, including weight and bias) for each layer from Pytorch to Keras, without any modification...
Solved! It turns out there's indeed no problem with implementation (at least not significant ones). It's the problem with weights copying. The original weights has (H, W, 3, 3), but TF-model requires dim of (3, 3, W, H), so I permuted it by [3,2,1,0], overlooking the (3, 3) also have their own sequence. So it should b...
https://stackoverflow.com/questions/66744761/
Torch JIT Trace = TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect
I am following this tutorial: https://huggingface.co/transformers/torchscript.html to create a trace of my custom BERT model, however when running the exact same dummy_input I receive an error: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We cant record the data flow of...
What this error means This warning occurs, when one tries to torch.jit.trace models which have data dependent control flow. This simple example should make it clearer: import torch class Foo(torch.nn.Module): def forward(self, tensor): # It is data dependent # Trace will only work with one path ...
https://stackoverflow.com/questions/66746307/
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces)
I am using Pytorch. I got this RuntimeError while evaluating a model. Any idea how to solve this?
SOLUTION: Just replace the view() function with reshape() function as suggested in the error and it works. I guess this has to do with how the tensor is stored in memory.
https://stackoverflow.com/questions/66750391/
Pytorch linear regression loss increase
I tried to implement a simple demo that gets a polynomial regression, but the linear model's loss fails to decrease. I am confused about where I went wrong. If I trained the model one sample(batch size = 1) each time, it works fine. but when I feed the model with many samples a time, the loss increase and get inf. impo...
You need to use loss_func = torch.nn.MSELoss(reduction='mean') to solve the NaN problem. A batch of one or two seems to work because the loss was small enough. By adding more epochs, you should see that your loss tend exponentially to infinity.
https://stackoverflow.com/questions/66778368/
CNN Classifier only guesses one thing - PyTorch
I'm trying to make a model predict the race of a 75x75 image's ethnicity, but when ever I train the model, the accuracy always stays completely still at 53.2%. I didn't realize why until I actually ran it on some of photos. It turned out, that no matter what the photo was, it would always predict 'other'. I'm not entir...
The number of layers and the dataset size don't explain this behavior for this example. Your CNN is behaving as a constant function, so far I don't know why, but these might be some clues: Since you have separated your data by label into folders, if you are training your model using only one of those folders you will ...
https://stackoverflow.com/questions/66783997/
How to create a graph neural network dataset? (pytorch geometric)
How can I convert my own dataset to be usable by pytorch geometric for a graph neural network? All the tutorials use existing dataset already converted to be usable by pytorch. For example if I have my own pointcloud dataset how can i use it to train for classification with graph neural network? What about my own image...
How you need to transform your data depends on what format your model expects. Graph neural networks typically expect (a subset of): node features edges edge attributes node targets depending on the problem. You can create an object with tensors of these values (and extend the attributes as you need) in PyTorch Geome...
https://stackoverflow.com/questions/66788555/
Why putting value on GPU slow the calculation?
I'm a new one in GPU parallezation. I found putting values on GPU in advance slows the calculations and indexing. My code is as follows: import torch A = torch.rand(600, 600, device='cuda:0') row0 = torch.tensor(100, device='cuda:0') col0 = torch.tensor(100, device='cuda:0') row1 = torch.tensor(356, device='cuda:0') c...
Your code is slow because there is nothing to parallelize, and you're just taking unnecessary GPU overheads. GPU parallelism works by launching a large number of threads, and simultaneously computing chunks of some operation. Things like matrix multiplication and convolution are very GPU-friendly, because you can break...
https://stackoverflow.com/questions/66801874/
How to install the module pytorch_lightning.metrics in Raspberry pi3
I am trying to execute a python file which has pytorch with lightning and torchvision modules. But after I downloaded and successfully installed whl file of pytorch in pi3 I am getting same error again and again. The error is ModuleNotFoundError: No module named 'pytorch_lightning.metrics' Help would be highly apprec...
Use instead: from torchmetrics.functional import accuracy
https://stackoverflow.com/questions/66807032/
How to solve the famous `unhandled cuda error, NCCL version 2.7.8` error?
I've seen multiple issue about the: RuntimeError: NCCL error in: /opt/conda/conda-bld/pytorch_1614378083779/work/torch/lib/c10d/ProcessGroupNCCL.cpp:825, unhandled cuda error, NCCL version 2.7.8 ncclUnhandledCudaError: Call to CUDA function failed. but none seem to fix it for me: https://github.com/pytorch/pytorch/is...
This is not a very satisfactory answer but this seems to be what ended up working for me. I simply used pytorch 1.7.1 and it's cuda version 10.2. As long as cuda 11.0 is loaded it seems to be working. To install that version do: conda install -y pytorch==1.7.1 torchvision torchaudio cudatoolkit=10.2 -c pytorch -c conda...
https://stackoverflow.com/questions/66807131/
Slow execution time for CUDA initialization in Azure Batch VM
I have an issue of slow initialization time for running some CUDA program in one of the VM for Azure Batch. After some troubleshooting, I made a simple test running this call as shown in the below code. #include <stdio.h> #include <cuda.h> #include <cuda_runtime_api.h> #include <time.h> clock_t...
Azure Batch in VirtualMachineConfiguration mode allocates Virtual Machine Scale Sets internally. There is no difference in the underlying hardware Azure Batch allocates from. For further investigation: How big is your sample set? Is your start time reproducible between different VMs within different Batch pools? Perha...
https://stackoverflow.com/questions/66809823/
Why do we need to pass the gradient parameter to the backward function in PyTorch?
According to the docs, when we call the backward function to the tensor if the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifying gradient. import torch a = torch.tensor([10.,10.],requires_grad=True) b = torch.tensor([20.,20.],requires_gra...
It's because PyTorch is calculating the jacobian product. In case of scalar value, .backward() w/o parameters is equivalent to .backward(torch.tensor(1.0)). That's why you need to provide the tensor with which you want to calculate the product. Read more about automatic differentiation.
https://stackoverflow.com/questions/66811113/
Logging training metrics to a csv file
I want to log all training metrics to a csv file while it is training on YOLOV5 which is written with pytorch but the problem is that I don't want to use tensorboard. To achieve this goal I tried some techniques like below: -First log it into tensorboard and then try to convert it to a csv file (failed) -Extract log fi...
You might try using the Weights and Biases YOLOv5 integration. Here is the link: https://docs.wandb.ai/guides/integrations/yolov5 The link has more details, but here are some quotes that convey the basic idea: Simply by installing wandb, you'll activate the built-in W&B logging features: system metrics, model metr...
https://stackoverflow.com/questions/66816695/
PyTorch CPU memory leak but only when running on a specific machine
I'm running a model and I've noticed that the RAM usage slowly increases during the training of the model. It's around 200mb-400mb per epoch, but over time it fills up all the RAM on my machine which eventually leads the OS to kill the job. However, the strange thing about this is it's only when running on a specific m...
Try incorporating this in your process: import gc # add this after computing one complete operation gc.collect()
https://stackoverflow.com/questions/66817006/
how to save a Pytorch model?
I am new to Deep learning and I want to know, how can I save the final model in Pytorch? I tried some things that were mentioned but I got confused with, how to save the model and how to load it back?
to save: # save the weights of the model to a .pt file torch.save(model.state_dict(), "your_model_path.pt") to load: # load your model architecture/module model = YourModel() # fill your architecture with the trained weights model.load_state_dict(torch.load("your_model_path.pt"))
https://stackoverflow.com/questions/66821329/
Memory leak with en_core_web_trf model, Spacy
there is a Memory leak when using pipe of en_core_web_trf model, I run the model using GPU with 16GB RAM, here is a sample of the code. !python -m spacy download en_core_web_trf import en_core_web_trf nlp = en_core_web_trf.load() #it's just an array of 100K sentences. data = dataload() for index, review in enumerat...
Lucky you with GPU - I am still trying to get thru the (torch GPU) DLL Hell on Windows :-). But it looks like Spacy 3 uses more GPU memory than Spacy 2 did - my 6GB GPU may have become useless. That said, have you tried running your case without the GPU (and watching memory usage)? Spacy 2 'leak' on large datasets is (...
https://stackoverflow.com/questions/66832669/
Huggingface error during training: AttributeError: 'str' object has no attribute 'size'
While trying to finetune a Huggingface GPT2LMHeadModel model for casual language modeling (given a sequence of words, predict the next word) using Pytorch Lightning, I am getting an error during training: AttributeError: 'str' object has no attribute 'size' What went wrong with our training code? Is this due to the i...
Here transformer recent version may occur this pip install transformers==2.11.0 In my case it's work!! then restart your kernel
https://stackoverflow.com/questions/66834205/
When using torch.backward() for a GANs generator, why doesn't discriminator losses change in Pytorch?
My understanding of GANs is: When training your generator, you need to back-propagate through the discriminator first so you can follow the chain rule. As a result, we can't use a .detach() when working on our generators loss calculation. When updating discriminator, since your generator weight update doesn't affect...
backward doesn't update the weights, it updates the gradients of the weights. Updating weights is the responsibility of the optimizer(s). There are different ways to implement GANs, but often you would have two optimizers, one that is responsible for updating the weights (and resetting the gradients) of the generator a...
https://stackoverflow.com/questions/66841054/
I can't figure out why the size of the tensors doesn't match in Pytorch
Some context: I have been studying AI and ML for the last couple of month now and finally I am studying neural nets. Great! The problem is that when I follow a tutorial everything seems to be OK, but when I try to implement a NN by my self I always face issues related to the size of the tensors. I have seem the answer ...
Input : 16 x 1 x 50 x 50 After conv1/maxpool1 : 16 x 32 x 25 x 25 After conv2/maxpool2 : 16 x 64 x 12 x 12 (no padding so taking floor) After conv3/maxpool3 : 16 x 128 x 6 x 6 (=73 728 neurons here is your error) Flattening : you specified a view like -1 x 32 * 4 * 8 * 8 = 9 x 8192 The correct flattening is -1 x 32 * 4...
https://stackoverflow.com/questions/66842842/
The input tensor should have dimensions 1 x height x width x 3. Got 1 x 3 x 224 x 224
I want to convert the Pytorch-trained model to the tensorflow model and use the model on mobile devices. For this, I follow these steps; First I convert the pytorch trained model to onnx format. Then I convert the onnx format to the tensorflow model. Firstly pytorch trained model to onnx; import torch import torch.onnx...
Maybe you could try einops for tensor transformations. It's elegant and powerful. In your case, the code should be import einops input_tensor = einops.rearrange(input_tensor,'b c w h -> b w h c')
https://stackoverflow.com/questions/66843633/
TypeError: linear(): argument 'input' (position 1) must be Tensor, not str
so ive been trying to work on some example of bert that i found on github as its the first time im trying to use bert and see how it works. The respiratory im working with is the following: https://github.com/prateekjoshi565/Fine-Tuning-BERT/blob/master/Fine_Tuning_BERT_for_Spam_Classification.ipynb im using a differen...
I've been working on this repo too. Motivated by the answer provided on this link. There is a class probably named Bert_Arch that inherits the nn.Module and this class has a overriden method named forward. Inside forward method just add the parameter 'return_dict=False' to the self.bert() method call. Like so: _, cls_h...
https://stackoverflow.com/questions/66846030/
model.eval for class with field of network - pytorch
I have a class model with field of pre-trained resnet something like: class A(nn.Module): def __init__(self, **kwargs): super(A, self).__init__() self.resnet = get_resnet() def forward(self, x): return self.resnet(x) ... now Im doing model = A() ... model.eval() Is it ok or shuld I o...
Short answer It's OK. Long answer As the nn.Module.train() runs recursively like this. self.training = mode for module in self.children(): module.train(mode) return self And the nn.Module.eval() is just calling self.train(False) So as long as self.resnet is an nn.Module subclass. You don't need to bother about it ...
https://stackoverflow.com/questions/66853955/
Proper way to log things when using Pytorch Lightning DDP
I was wondering what is the proper way of logging metrics when using DDP. I noticed that if I want to print something inside validation_epoch_end it will be printed twice when using 2 GPUs. I was expecting validation_epoch_end to be called only on rank 0 and to receive the outputs from all GPUs, but I am not sure this ...
Questions validation_epoch_end(self, outputs) - When using DDP does every subprocess receive the data processed from the current GPU or data processed from all GPUs, i.e. does the input parameter outputs contains the outputs of the entire validation set, from all GPUs? Data processed from the current GPU only, output...
https://stackoverflow.com/questions/66854148/
CUDA initialization: CUDA unknown error - this may be due to an incorrectly set up environment
I am trying to install torch with CUDA support. Here is the result of my collect_env.py script: PyTorch version: 1.7.1+cu101 Is debug build: False CUDA used to build PyTorch: 10.1 ROCM used to build PyTorch: N/A OS: Ubuntu 20.04.1 LTS (x86_64) GCC version: (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 Clang version: Could not ...
Had the same issue and in my case solution was very easy, however it wasn't easy to find it. I had to remove and insert nvidia_uvm module. So: > sudo rmmod nvidia_uvm > sudo modprobe nvidia_uvm That's all. Just before these command collect_env.py reported "Is CUDA available: False". After: "Is CUD...
https://stackoverflow.com/questions/66857471/
Could not find a version that satisfies the requirement torch==1.7.0+cpu
I want to install torch==1.7.0+cpu from requirements.txt I have an error Could not find a version that satisfies the requirement torch==1.7.0+cpu (from -r requirements.txt (line 42)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2, 0.3.1, 0.4.0, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0, 1.2.0, 1.3.0, 1.3.1, 1.4.0, 1.5....
If you have this issue while installing your modules from requirements.txt then you could simply add the following line to the top of your requirements.txt file -f https://download.pytorch.org/whl/torch_stable.html
https://stackoverflow.com/questions/66858277/
Get Pytorch - tensor values as a integer in python
I have my output of my torch tensor which looks like below (coordinate of a bounding box in object detection) [tensor(299., device='cuda:0'), tensor(272., device='cuda:0'), tensor(327., device='cuda:0'), tensor(350., device='cuda:0')] I wanted to extract each of the tensor value as an int in the form of minx,miny,maxx...
minx, miny, maxx, maxy = [int(t.item()) for t in tensors] where tensors is the list of tensors.
https://stackoverflow.com/questions/66874669/
Dead Kernel after running torchvision.utils.make_grid(images)
To make it simple, I am following this tutorial provided by PyTorch to create a CNN. However, it appears that when I'm running this particular code block with this respective line: # show images imshow(torchvision.utils.make_grid(images)) It somehow kills the kernel. Which confuses me because it is only a simple funct...
The same thing happened to me. Running these commands in the python interpreter, I got an error that lead me to this: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized when I added the following, it worked: import os os.environ['KMP_DUPLICATE_LIB_OK']='True'
https://stackoverflow.com/questions/66875621/
Federated reinforcement learning
I am implementing federated deep Q-learning by PyTorch, using multiple agents, each running DQN. My problem is that when I use multiple replay buffers for agents, each appending experiences at the corresponding agent, two elements of experiences in each agent replay buffer, i. e., "current_state" and "ne...
I just found what is causing the problem. I should have used copy.deepcopy() for experiences: experience = copy.deepcopy((current_state, action, np.array([reward]), next_state, done)) self.buffer.append(experience)
https://stackoverflow.com/questions/66875831/
Finding the Hessian matrix of this function
Hi I have the following function: sum from 1 to 5000 -log(1−(xi)^2) -log(1-(a_i)^t*x), where a_i is a random vector and we are trying to minimize this function's value via Netwon's method. I need a way to calculate the Hessian matrix with respect to (x1, x2, x3, ...). I tried auto-gradient but it took too much time. He...
PyTorch has a GPU optimised hessian operation: import torch torch.autograd.functional.hessian(func, inputs)
https://stackoverflow.com/questions/66881349/
What does the 1 in torch.Size([64, 1, 28, 28]) mean when I check a tensor shape?
I'm following this tutorial on towardsdatascience.com because I wanted to try the MNIST dataset using Pytorch since I've already done it using keras. So in Step 2, knowing the dataset better, they print the trainloader's shape and it returns torch.Size([64, 1, 28, 28]). I understand that 64 is the number of images in ...
It simply defines an image of size 28x28 has 1 channel, which means it's a grayscale image. If it was a colored image then instead of 1 there would be 3 as the colored image has 3 channels such as RGB.
https://stackoverflow.com/questions/66885978/
Output evaluation loss after every n-batches instead of epochs with pytorch
Instead of printing the evaluation loss every epoch I would like to output it after every n-batches. I have around 150'000 batches per epoch. I would like to output the evaluation loss every 50'000 batches. Is this even possible? I am using pytorch and a pretrained bert model from huggingface. My train loop: best_valid...
If you want to skip n elements of, for example, some list, you can do this using enumerate: n = 50000 for i,epoch in enumerate(some_list): if i%n == 0: print('\n Epoch {:} / {:}'.format(epoch + 1, params['epochs'])) ... But in your case, you can use only an additional condition: n...
https://stackoverflow.com/questions/66889503/