instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
import matplotlib failed while deploying my model in AWS sagemaker
I have deployed my AWS model successfully. but while testing i am getting runtime Error: "import matplotlib.pyplot as plt" . I think it is due to pytorch framework version i used(framework_version=1.2.0). I am facing the same issue when i use higher versions as well. PyTorchModel(model_data=model_artifact, ...
It sounds like you want to inject some additional code libraries into the SageMaker PyTorch serving container. You might have to dig into the source code for how the PyTorch serving container is built to further customize it: https://github.com/aws/sagemaker-pytorch-inference-toolkit, or build your own image. Digging i...
https://stackoverflow.com/questions/62912156/
How does one save torch.nn.Sequential models in pytorch properly?
I am very well aware of loading the dictionary and then having a instance of be loaded with the old dictionary of parameters (e.g. this great question & answer). Unfortunately, when I have a torch.nn.Sequential I of course do not have a class definition for it. So I wanted to double check, what is the proper way to...
As can be seen in the code torch.nn.Sequential is based on torch.nn.Module: https://pytorch.org/docs/stable/_modules/torch/nn/modules/container.html#Sequential So you can use f = torch.nn.Sequential(...) torch.save(f.state_dict(), path) just like with any other torch.nn.Module.
https://stackoverflow.com/questions/62923052/
What should __len__ be for PyTorch when generating unlimited data?
Say I am trying to use PyTorch to learn the equation y = 2x and I want to generate an unlimited amount of data to train my model with. I am supposed to provide a __len__ function. Here's an example below. What should it be in this case? How do I specify the number of mini-batch iterations per epoch? Do I just set a num...
You should use torch.utils.data.IterableDataset instead of torch.utils.data.Dataset. In your case it would be: import torch class Dataset(torch.utils.data.IterableDataset): def __init__(self, batch_size): super().__init__() self.batch_size = batch_size def __iter__(self): while True: ...
https://stackoverflow.com/questions/62925418/
How to add new sample to CIFAR10 torchvision?
Hi I want to add my own images to the CIFAR10 dataset in torchvision, how can I do that? train_data = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform) train_data.add # or a workaround! thanks
You can either create a custom dataset for CIFAR10, using the raw cifar10 images here or you can still use the CIFAR10 dataset inside your new custom dataset and then add your logic in the __getitem__() method. This is a simple example to get you going : class CIFAR10_2(torch.utils.data.Dataset): def __init__(self,...
https://stackoverflow.com/questions/62931963/
Best way to save many tensors of different shapes?
I would like to store thousands to millions of tensors with different shapes to disk. The goal is to use them as a time series dataset. The dataset will probably not fit into memory and I will have to load samples or ranges of samples from disk. What is the best way to accomplish this while keeping storage and access t...
The easiest way to save anything in disk is by using pickle: import pickle import torch a = torch.rand(3,4,5) # save with open('filename.pickle', 'wb') as handle: pickle.dump(a, handle) # open with open('filename.pickle', 'rb') as handle: b = pickle.load(handle) You can also save things with pytorch direct...
https://stackoverflow.com/questions/62932368/
How to use a bert pretrained model somewhere else?
I followed this course https://www.coursera.org/learn/sentiment-analysis-bert about building a pretrained model for sentiment analysis. During the trining, at each epoch they saved the model using torch.save(model.state_dict(), f'BERT_ft_epoch{epoch}.model'). Now I want to use one of these models (the best one obviousl...
How to define, initialize, save and load models using Pytorch. Initializing a model. That is done inheriting the class nn.Module, consider the simple two layer model: import torch import torch.nn as nn class Model(nn.Module) def __init__(self, input_size=128, output_size=10): super(Model).__init__() ...
https://stackoverflow.com/questions/62938230/
pytorch training loss invariant with varying forward pass implementations
The following code (MNIST MLP in PyTorch) delivers approximately the same training loss regardless of having the last layer in the forward pass returning: F.log_softmax(x) (x) Option 1 is incorrect because I use criterion = nn.CrossEntropyLoss() and yet the results are almost identical. Am I missing anything? import ...
For numerical stability, the nn.CrossEntropyLoss() is implemented with the softmax layer inside it. So you should NOT use the softmax layer in your forward pass. From the docs (https://pytorch.org/docs/stable/nn.html#crossentropyloss): This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class. Usin...
https://stackoverflow.com/questions/62941089/
Received a make error while building warp-ctc pytorch
I am trying to build https://github.com/SeanNaren/warp-ctc.git on Google Colab, following this notebook. I am using these commands on Colab: !git clone https://github.com/SeanNaren/warp-ctc.git;\ cd warp-ctc;\ mkdir build;\ cd build;\ cmake ..;\ make; but I am receiving an error building it: [-11%] Building NVCC (Devi...
This post documents an apparent fix for this issue, which also affects the original warp-ctc repository: [...] the ctc_entrypoint.cu file needs to be a symlink. So, go to src dir and run: rm ctc_entrypoint.cu ln -s ctc_entrypoint.cpp ctc_entrypoint.cu Then, re-run make, which should resolve the issue.
https://stackoverflow.com/questions/62941402/
How is batching normally performed for sequence data for an RNN/LSTM
This Udacity course notebook batches data in a way that is not intuitive to me. For a long sequence of data, they first truncates the data so it can be evenly divided by batch_size. Next, they .reshape() the data to be (batch_size, -1). Then they creates a sliding window over these batches of sub-sequences. When the sl...
You should check the documentation on padded sequences from pytorch. (If I had more experience with it I would give you a more detailed explanation, but truth if that I never really understood them!) Packed Sequence: https://pytorch.org/docs/master/generated/torch.nn.utils.rnn.PackedSequence.html#torch.nn.utils.rnn.Pac...
https://stackoverflow.com/questions/62946271/
Flattening Efficientnet model
I am trying to remove the top layer in the efficientnet-pytorch implementation. However, if I simply replace the final _fc layer with my own fully connected layer, as suggested by the author in this github comment, I am worried that there is still a swish activation even after this layer, as opposed to having nothing a...
This is a common misunderstanding of what print(net) actually does. The fact that there is a _swish Module after the _fc simply means that for former was registered after the latter. You can check that in the code: class EfficientNet(nn.Module): def __init__(self, blocks_args=None, global_params=None): # [...
https://stackoverflow.com/questions/62954999/
Does my for loop run parallely, if all the tensors involved in the loop are on the GPU?
I have a list of tensors and all of them are present on the GPU. I obtained this list by splitting one tensor on the GPU using torch.split. I want to get list of sums of the list of tensors I have. So, in simple terms, I want to get a list in which, the first element is sum of first tensor in the list, and so on. If I ...
PyTorch runs GPU operations asynchronously (see docs). When you call a function that uses the GPU, the operations are enqueued to the particular device This means, your sum operations may run in parallel. I have made a simple experiment to test this. If I am right, it proves that you don't need to worry about paralle...
https://stackoverflow.com/questions/62966810/
PyTorch: NVIDIA NGC image or Docker Hub image?
What are the differences between the official PyTorch image on Docker Hub and the PyTorch image on NVIDIA NGC? The NGC page is more documented than the Docker Hub page, which has no description. But the NGC image is also heavier by a few gigabytes, and it seems to require a CUDA 10.2-compatible driver. Is there any adv...
I'm not a docker expert. To the best of my knowledge Nvidia puts a lot of effort to ship GPU-optimized containers such that running GPU pytorch on Nvidia GPU with Nvidia container should have best possible performance. Therefore, if you are using Nvidia hardware you should expect better performance using NGC containers...
https://stackoverflow.com/questions/62978545/
Why error FileNotFoundError: [Errno 2] No such file or directory: './ML/model.pth' occurs?
Error l_1 | from Ml import demo_model ml_1 | File "/app/Ml/demo.py", line 84, in ml_1 | model = torch.load('./ML/model.pth', map_location='cpu') ml_1 | File "/usr/local/lib/python3.7/site-packages/torch/serialization.py", line 584, in load ml_1 | with _...
It seems like you have a typo: the folders are Ml (small "l") while in the code it is ML (capital "L").
https://stackoverflow.com/questions/62980773/
Pytorch how to increase batch size
I currently have a tensor of torch.Size([1, 3, 256, 224]) but I need it to be input shape [32, 3, 256, 224]. I am capturing data in real-time so dataloader doesn't seem to be a good option. Is there any easy way to take 32 of size torch.Size([1, 3, 256, 224]) and combine them to create 1 tensor of size [32, 3, 256, 2...
You are probable using jit model, and the batch size must be exact like the one the model was trained on. t = torch.rand(1, 3, 256, 224) t.size() # torch.Size([1, 3, 256, 224]) t2= t.expand(32, -1,-1,-1) t2.size() # torch.Size([32, 3, 256, 224]) Expanding a tensor does not allocate new memory, but only creates a new v...
https://stackoverflow.com/questions/62981621/
How to convert PyTorch tensor to image and send it with flask?
I have a neural network in PyTorch which gives an image as a Tensor. I have converted it to a numpy array and then followed the explanation here to send that image to the html. The problem is that it's always black. This is my code in the PyTorch: def getLinearImage(): with torch.no_grad(): test_z = torch.randn...
Logically speaking, since the static image works, the error is somewhere in your getLinearImage code. I would suggest running things through using PDB (or a debugger of your choice) to figure out why it's not generated correctly. That said, I create a variable in your code: numpu = (numpy + 1) * 128 which you don't se...
https://stackoverflow.com/questions/62987619/
Loss Analysis of Deep Learning
I'm new to deep learning, and I have built a graph convolution network. I used 5 fold cross-validations. After plotting the mean train_loss (blue) and validate_loss (orange) together, I got this baby. MSE loss As you can see, from the curvilinear trend of validate_loss, it seems that my networks learn few things. (I gu...
This is pretty much what train and validation loss is supposed to do. Loss goes down over time; that's what an optimizer is trying to do. train_loss keeps going down after valid_loss levels out or plateaus, indicating the model starts overfitting after epoch ~100 or so. Whether MSE 0.3 is good or bad for your applic...
https://stackoverflow.com/questions/62988773/
Using pre-trained weights in PyTorch
I am working on implementing a research paper based on computer vision in PyTorch. I have built the model architecture by referring to the paper. The author has uploaded saved weights on GitHub in ".pth.tar" format. I want to put the same weights in my model so that I can skip training and optimization part a...
If you are using google colab #mount drive onto google colab from google.colab import drive drive.mount('/content/gdrive') Define the path of the weights weights_path="/content/gdrive/My Drive/weights.pth" Extract the tar file !tar -xvf weights.pth.tar Load the weights into the model net net=torch.load(we...
https://stackoverflow.com/questions/62994194/
Cuda out of memory in loop on second forward pass?
I have the following problem: model = MyModel() model.load_state_dict(checkpoint[weights]) model.train() data, label = get_data() # just take one trainings example data.cuda() for i in range(10): # lets predict data 10 times output = model(data) print(i) I can do one forward step (i is printed 0) but then I ge...
Ok you have to manually remove the output tensor. It is kept although the loop starts over again: This is fixable by for i in range(10): model.zero_grad() output = model(data) del output
https://stackoverflow.com/questions/62994816/
pytorch sliding window with unfold & fold
I'm trying to use a simple ssd that was trained on 300x300 data with annotated bounding boxes. If I crop the images manually, it works correctly but with full size images it fails (obviously) due to resizing large images to 300x300 removes many visual features. I figured the good old sliding window will work here, but ...
I'm posting that way so it's easier for others to find a solution if they encounter similar problem. Key Highlights: pytorch unfold will crop out part of the image that doesn't fit into the sliding window used. (ex. with 300x300 image and 100x100 window, nothing would get cropped, but with 290x290 image and same windo...
https://stackoverflow.com/questions/62995726/
Update targets in classification images
Why are we updating targets in the implementation of bayesian cnn with mc dropout here? https://github.com/sungyubkim/MCDO/blob/master/Bayesian_CNN_with_MCDO.ipynb?fbclid=IwAR18IMLcdUUp90TRoYodsJS7GW1smk-KGYovNpojn8LtRhDQckFI_gnpOYc def update_target(target, original, update_rate): for target_param, param in zi...
The implementation you have referred to is a data parallel one. Which means, the author intends to train multiple networks with the same architecture but different hyper-parameters. Although in an unconventional way, this is what update_target does: update_target(net_test, net, 0.001) It updates the net_test with a lo...
https://stackoverflow.com/questions/62998832/
load and freeze one model and train others in PyTorch
I have a model A that including three submodels model1, model2, model3. the model flow: model1 --> model2 --> model3 I have trained model1 in an independent project. The question is how to use the pre-trained model1 when training the model A? Now, I try to implement this as follow: I load the checkpoint of model1...
Yes, that is correct. When you structure your model the way you explained, what you are doing is correct. ModelA consists of three submodels - model1, models, model3 Then you load the weights of each individual model with model*.load_state_dict(torch.load(model*.pth)) Then make requires_grad=False for the model you wan...
https://stackoverflow.com/questions/62998911/
Getting different eigenvalues between using numpy.linalg.eigh() and torch.symeig()
I am trying to understand why am I getting different eigenvalues between using numpy.linalg.eigh() and torch.symeig(). An example is as below: Code: import numpy as np import torch arr_symmetric = np.array([[1.,2,3], [2,5,6], [3,6,9]]) arr_symmetric, arr_symmetric.dtype Output: (array([[1., 2., 3.], [2., 5., ...
4.05517871e-16 is very close to zero so is -2.6047e-16. They are very very close by. You can verify the same as below because input = V.e.V^T where e is a diagonal matrix with eigen values in the diagonal. import numpy as np import torch arr_symmetric = np.array([[1.,2,3], [2,5,6], [3,6,9]]) e, v = np.linalg.eigh(arr...
https://stackoverflow.com/questions/63000741/
What does it mean to assert an object in python?
We are getting an assertion error in this line "assert dataset". We are printing the dataset object and the value we got was this '<datasets.TextDataset object at 0x000002531F10E408>'. We are using 'python 3.7' in this code. Why are we getting assertion error on dataset object? We are basically trying t...
In this case, assert dataset is a not-very-clear way of checking if the dataset is empty. assert throws an exception if the expression (in this case the dataset object) evaluates to false. https://docs.python.org/3/library/stdtypes.html "Truth Value Testing" says By default, an object is considered true unl...
https://stackoverflow.com/questions/63001830/
How to use AMD GPU for fastai/pytorch?
I'm using a laptop which has Intel Corporation HD Graphics 5500 (rev 09), and AMD Radeon r5 m255 graphics card. Does anyone know how to it set up for Deep Learning, specifically fastai/Pytorch?
Update 2: Microsoft has release Pytorch_DML a few hours ago. You can now install it (in windows or WSL) using pypi package: pytorch-directml 1.8.0a0.dev211021 pip install pytorch-directml So if you are on windows or using WSL, you can hop in and give this a try! Update : As of Pytorch 1.8 (March 04, 2021), AMD ROCm ve...
https://stackoverflow.com/questions/63008040/
using huggingface Trainer with distributed data parallel
To speed up performace I looked into pytorches DistributedDataParallel and tried to apply it to transformer Trainer. The pytorch examples for DDP states that this should at least be faster: DataParallel is single-process, multi-thread, and only works on a single machine, while DistributedDataParallel is multi-process ...
Kind of late to the party but anyway. I'm going to leave this comment here to help anyone wondering if it is possible to keep the parallelism in the tokenizer. According to this comment on github the FastTokenizers seem to be the issue. Also according to another comment on gitmemory you shouldn't use the tokenizer befo...
https://stackoverflow.com/questions/63017931/
How does pytorch compute derivatives for simple functions?
When we talk about the auto-differentiation in the pytorch, we are usually presented a graphical structures of tensors based on their formulas, and pytorch will compute the gradients by tracing down the graphical tree using chain rules. However, I want to know what will happen at the leaf nodes? Does pytorch hardcode a...
See this paper for exact answer, specifically section 2.1 or figure 2. In short, PyTorch has a list of basic functions and the expression of their derivatives. So, what is done in your case (y =xx), is evaluating $$ y' = 2x $$. The numerical method you mentioned is called numerical differentiation or finite differences...
https://stackoverflow.com/questions/63026854/
pytorch Gradient with respect to 3D input
I want to construct sobolev network for 3D input regression In TensorFlow, the gradients of neural network model can be computed using tf.gradient like: dfdx,dfdy,dfdz = tf.gradients(pred,[x,y,z]) Let M be a torch neural network with 5 layers. If X is a set of (x,y,z) (3dim data) and M.forward(X) is a 1 dim output H...
If you want to compute gradient of this function for example y_i = 5*(x_i + 1)² Create tensor of size 2x1 filled with 1's that requires gradient x = torch.ones(2, requires_grad=True) Simple linear equation with x tensor created y = 5 * (x + 1) ** 2 Let take o as multiple dimension equation o = 1/2 *sum(y_i) in pyt...
https://stackoverflow.com/questions/63027843/
What are some ways to speed up data loading on large sparse arrays (~1 million x 1 million, density ~0.0001) in Pytorch?
I am working on a binary classification problem. I have ~1.5 million data points, and the dimensionality of the feature space is 1 million. This dataset is stored as a sparse array, with a density of ~0.0001. For this post, I'll limit the scope to assume that the model is a shallow feedforward neural network, and also ...
Your dataset in un-sparsified form would be 1.5M x 1M x 1 byte = 1.5TB as uint8, or 1.5M x 1M x 4 byte = 6TB as float32. Simply reading 6TB from memory to CPU could take 5-10 minutes on a modern CPU (depending on the architecture), and transfer speeds from CPU to GPU would be a bit slower than that (NVIDIA V100 on PCI...
https://stackoverflow.com/questions/63037571/
Why is the super constructor necessary in PyTorch custom modules?
Why does super(LR, self).__init__() need to be called in the code below? I get the error "AttributeError: cannot assign module before Module.init() call" otherwise. That error is caused by self.linear = nn.Linear(input_size, output_size). I don't understand what the connection is between calling super(LR, sel...
When you write self.linear = nn.Linear(...) inside your custom class, you are actually calling the __setattr__ function of your class. It just happens that when you extend nn.Module, there are a bunch of things that your class is inheriting, and one of them is the __setattr__. As you can see in the implementation (I p...
https://stackoverflow.com/questions/63058355/
How to fix Process finished with exit code -1073741819 (0xC0000005) when using Convolutional layers in pytorch, error on backward()
When I use Conv1d or Conv2d layers on pytorch, the process is killed unexpectedly. I am getting the error in the following line: loss.backward() My set up: Windows 10 cuda 10.2 cudnn 7.6.5 RTX 2060 Super Nvidia driver 451.67 Pycharm 2020.04 Error: Process finished with exit code -1073741819 (0xC0000005) In comparis...
There seems to be a known bug around this problem that happens with Pytorch on windows, when run on GPU(with CUDA) . Ensure all params supplied to Conv1d and Conv2d are correct especially padding value. Note that it can have different behaviour with other OS like linux/ubuntu. And also if you are using Python-3.6 or hi...
https://stackoverflow.com/questions/63059001/
Constant loss through epochs
I code this neural network to make a gaussian regression but I don't understand why my loss doesn't change through epochs. I set the learning rate to 1 to see the loss decreases but it does not. I chose to take 2000 poitns to train my Neural network. I watched several algorithms on this website and I don't really under...
I'm wondering why you don't have loss.backward() after the line that you compute the loss (i.e., loss = criterion(outputs,target)) in your training snippet. This will help backpropagating and ultimately updating the parameters of your network upon optimizer.step(). Also, try using lower learning rates as lr=1 normally ...
https://stackoverflow.com/questions/63060735/
pytorch when do I need to use `.to(device)` on a model or tensor?
I am new to Pytorch, but it seems pretty nice. My only question was when to use tensor.to(device) or Module.nn.to(device). I was reading the documentation on this topic, and it indicates that this method will move the tensor or model to the specified device. But I was not clear for what operations this is necessary, an...
It is necessary to have both the model, and the data on the same device, either CPU or GPU, for the model to process data. Data on CPU and model on GPU, or vice-versa, will result in a Runtime error. You can set a variable device to cuda if it's available, else it will be set to cpu, and then transfer data and model to...
https://stackoverflow.com/questions/63061779/
Pytorch and Torchvision are compiled different CUDA versions
RuntimeError: Detected that PyTorch and torchvision were compiled with different CUDA versions. PyTorch has CUDA Version=10.2 and torchvision has CUDA Version=10.1. Please reinstall the torchvision that matches your PyTorch install. I am trying to run YOLACT on my Google Colab and found this error. Can someone help so...
You need to upgrade your torchvision to one compiled with CUDA 10.2: pip install --upgrade torchvision>=0.6.0 or, if you're using Conda: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch Check here the version you should install based on your PyTorch.
https://stackoverflow.com/questions/63062741/
How to get occurrence count of item in array in-place
I have a array which I am trying to get weights for. It looks like this: Target: tensor([ 1, 6, 5, 8, 10, 5, 4, 5, 10, 10, 9, 8, 10, 4, 10, 9]) I need to get the counts of each item in the array. So I would like it to return this: Class count: [1, 1, 3, 2, 5, 3, 2, 3, 5, 5, 2, 2, 5, 2, 5, 2] This is my code right now...
Use return_inverse of numpy.unique: y = [ 1, 6, 5, 8, 10, 5, 4, 5, 10, 10, 9, 8, 10, 4, 10, 9] uniq, inv, cnt = np.unique(y, return_inverse=True, return_counts=True) cnt[inv] Output: array([1, 1, 3, 2, 5, 3, 2, 3, 5, 5, 2, 2, 5, 2, 5, 2])
https://stackoverflow.com/questions/63065765/
How to do hyperparameter tuning in Detectron2
Detectron2 COCO Person Keypoint Detection Baselines with Keypoint R-CNN R50-FPN How do I do hyperparameter tuning with the model above? Which files do I have to open? Thanks
You can use "config" to tune your model. Here is an official tutorial how you can use it (https://detectron2.readthedocs.io/tutorials/configs.html) And here is the file of all hyperparameters that you can tune (https://github.com/facebookresearch/detectron2/blob/master/detectron2/config/defaults.py)
https://stackoverflow.com/questions/63065916/
How to implement a Sparse Embedding in Tensorflow 2 like Pytorch Embedding(sparse=True)?
I have a network that has a lot of items that need to be embedded. However, in each training batch, only a very small portion of the items will actually be used. If I use the normal tf.keras.layers.Embedding layer, it will add all the items into the network parameter, thus consuming a lot of memory and decreasing speed...
My bad... checking tf.GradientTape() tells me that gradient of tf.gather is already a sparse tensor, so this needs no bother.
https://stackoverflow.com/questions/63069863/
migrating from keras to pytorch
i'm newly in pytorch it is the model with bidirectional lstm, is there any body to tel me what is the equivalent of this two different lstm & bi-lstm model? i try some torch codes but it do not worked.because this code has suitable acc in keras,i want the exact model in torch and i unfortunately can't find it:( fis...
class Model(nn.Module): def __init__(self, **kwargs): super().__init__() self.embeddings = nn.Embedding(num_embeddings=kwargs["vocab_size"], embedding_dim=kwargs["embedding_dim"], padding_idx=kwargs[&quo...
https://stackoverflow.com/questions/63076590/
PyTorch multiprocessing error with Hogwild
I've encountered a mysterious bug while trying to implement Hogwild with torch.multiprocessing. In particular, one version of the code runs fine, but when I add in a seemingly unrelated bit of code before the multiprocessing step, this somehow causes an error during the multiprocessing step: RuntimeError: Unable to han...
If you modify your code to create new processes like this: processes = [] ctx = mp.get_context('spawn') for rank in range(num_processes): p = ctx.Process(target=train, args=(model,)) it seems to run fine (rest of code same as yours, tested on pytorch 1.5.0 / python 3.6 / NVIDIA T4 GPU). I'm not completely sure wha...
https://stackoverflow.com/questions/63081486/
Reward not increasing while training a Bipedal System
I am completely new to reinforcement learning and this is my first program in practice. I am trying to train the bipedal system in the OpenAI gym environment using the policy gradient algorithm. However, the reward never changes, either at episode 0 or at episode 1000 and I cannot figure out what is going wrong. Could ...
Your learning rate is way too high! High learning rate may lead your model to never converge (in fact, the loss may diverge). A learning rate that is way too low will make the training process unnecessarily long. There is a trade-off you have to find for yourself. Tunning your learning rate may have a tremendous impact...
https://stackoverflow.com/questions/63083899/
Can I create an Upper triangular tensor in pytorch?
I want to create an upper triangular tensor in pytorch which I want that the lower half of the upper triangular tensor constant zeros. And the lower half of the upper triangular tensor have no grad. When I use torch.triu() to get upper triangular tensor, the lower half of the upper triangular tensor have grad which mea...
It does appear that torch.triu() gives you an upper triangular matrix and the gradients appear to be correct. For example, lets say that x = torch.randn(5, 5, requires_grad=True) produces tensor([[ 0.1907, -0.0990, 1.0373, 0.3676, -0.2752], [ 1.8987, 1.0265, -0.1133, 0.1476, -3.5617], [ 1.2581, 0....
https://stackoverflow.com/questions/63090384/
Function with torch.mm showing error while using torch.optim
I am kind of a newbie with PyTorch. Please forgive me if the question is childish. I am trying to minimize a function using PyTorch's optim. The function includes matrix multiplication. The details are given below. First I have a tensor: Xv.requires_grad_() XT.requires_grad_() My Objective Function: def errorFun(x): ...
I am not sure I understand your task. But it seems you are not using pytorch the way it was designed to be used. There are 5 things you have to have: Data for training; A task you are interested in per forming; A parameterized model (eg a neural network); A cost function to be minimized; An optimizer; Consider the si...
https://stackoverflow.com/questions/63093141/
PyTorch: Is it possible to differentiate a matrix?
How do you differentiate a matrix in PyTorch? I have tried the following but neither work: Instance 1: a = torch.tensor([1., 2, 3], requires_grad=True) b = torch.tensor([4., 5, 6], requires_grad=True) c = a*b c.backward() #print(b.grad) >>> RuntimeError: grad can be implicitly created only for scalar outputs...
It is possible but it doesn't really fit into the standard use case of PyTorch where you are generally interested in the gradient of a scalar valued function. The derivative of a matrix Y w.r.t. a matrix X can be represented as a Generalized Jacobian. For the case where both matrices are just vectors this reduces to th...
https://stackoverflow.com/questions/63096122/
Pytorch schedule learning rate
I am trying to re-implement one paper, which suggests to adjust the learning rate as below: The learning rate is decreased by a factor of the regression value with patience epochs 10 on the change value of 0.0001. Should I use the torch.optim.lr_scheduler.ReduceLROnPlateau()? I am not sure what value should I pass to...
torch.optim.lr_scheduler.ReduceLROnPlateau is indeed what you are looking for. I summarized all of the important stuff for you. mode=min: lr will be reduced when the quantity monitored has stopped decreasing factor: factor by which the learning rate will be reduced patience: number of epochs with no improvement after w...
https://stackoverflow.com/questions/63108131/
Does Pytorch-Lightning have a multiprocessing (or Joblib) module?
I have been googling around but can't seem to find if there is a multiprocessing module available in Pytorch-Lightning, just like how Pytorch has a torch.multiprocessing module. Does anyone know if Pytorch-Lightning has this (or a Joblib similar) module? I am looking for a Pytorch-Lightning module which allows me to pa...
Yes, basically all you have to do is to provide Trainer with appropriate argument gpus=N and specify backend: # train on 8 GPUs (same machine (ie: node)) trainer = Trainer(gpus=8, distributed_backend='ddp') # train on 32 GPUs (4 nodes) trainer = Trainer(gpus=8, distributed_backend='ddp', num_nodes=4) You can read mor...
https://stackoverflow.com/questions/63108616/
OSError: [WinError 127] The specified procedure could not be found. pytorch
I get this error OSError: [WinError 127] The specified procedure could not be found. OSError Traceback (most recent call last) in 5 import matplotlib.pyplot as plt 6 ----> 7 import torch 8 import torch.nn as nn 9 import torch.optim as optim ~\AppData\Loca...
I got a similar error with Python 3.9.2 on Windows 10 and solved it doing the following: I copied the CUDA 11 drivers (specifically cublas64_11.dll) from: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin to C:\<your python directory>\Lib\site-packages\torch\lib
https://stackoverflow.com/questions/63112597/
PyTorch: Running unseen text through generated model
I am trying to implement a PyTorch project, found here. import os from process_file import process_doc import random import torch torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False import numpy as np from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from sklearn.metrics im...
Well, your code does training and testing already. You just need an extra piece of code that loads the trained model and test data for inference. It should be something like that: # load trained model: model = Classifier({'num_layers': 1, 'hidden_dim': 512, 'bidirectional': True, 'embedding_dim': 1024, ...
https://stackoverflow.com/questions/63113593/
why does batch normalization make my batches so abnormal?
I'm playing with pytorch for the first time, and I've noticed that when training my neural net, about one time in four or so the loss takes a left turn towards infinity, then nan shortly after that. I've seen a few other questions about nan-ing, but the recommendations there seem to be essentially to do normalization; ...
Welcome to pytorch! Here is how I would set up your training. Please check the comments. # how the comunity usually does the import: import torch # some people do: import torch as th import torch.nn as nn import torch.optim as optim if __name__ == '__main__': # setting some parameters: batch_size = 32 ...
https://stackoverflow.com/questions/63127564/
get the index of element in NumPy array
I have a Numpy integer array with a lot of duplicate elements. For example: a = np.random.randint(0,5,20) a Out[23]: array([3, 1, 2, 4, 1, 2, 4, 3, 2, 3, 1, 4, 4, 1, 2, 4, 2, 4, 1, 1]) There are two cases: if one element is less than 4, get all the indexes of this element if one element is great than or equal to 4, s...
You can do it quite easily, using Pandas. First convert your array to a pandasonic Series: s = pd.Series(a) Then: Group it by its value. Apply to each group a function, which: for groups of size 4 or smaller returns just this group, for groups with more members, returns a random sample of 4 elements from them. Dro...
https://stackoverflow.com/questions/63129794/
How to concat two tensors of size [B,C,13,18] and [B,C,14,18] respectively in Pytorch?
I often met this problem when the height or width of an image or a tensor becomes odd. For example, suppose the original tensor is of size [B,C,13,18]. After forwarding a strided-2 conv and several other conv layers, its size will become [B,C,7,9]. If we upsample the output by 2 and concat it with the original feature ...
Concatenating tensors with incompatible shapes does not make sense. Information is missing, and you need to specify it by yourself. The question is, what do you are expected from this concatenation ? Usually, you pad the input with zeros, or truncate the output, in order to get compatible shapes (in the general case, b...
https://stackoverflow.com/questions/63138587/
How to make sure PyTorch has deallocated GPU memory?
Say we have a function like this: def trn_l(totall_lc, totall_lw, totall_li, totall_lr): self.model_large.cuda() self.model_large.train() self.optimizer_large.zero_grad() for fb in range(self.fake_batch): val_x, val_y = next(self.valid_loader) ...
I don't think the other answer is correct. Allocation and deallocation definitely happens during runtime, the thing to note is that the CPU code runs asynchronously from the GPU code, so you need to wait for any deallocation to happen if you want to reserve more memory after it. Take a look at this: import torch a = ...
https://stackoverflow.com/questions/63145729/
Is there an equivalent of pytorch.nn.functional.unfold() in keras or tensorflow?
I want to perform a similar operation in keras. However, I am unable to do the unfold operation in keras. I tried it with conv1D layer, but unable to figure out. Any help would be appreciated ''' import numpy as np import torch x = torch.tensor(np.random.rand(25,100,24)) # tensor of shape (batch_size, seq_length,fea...
I don't think there is. But you can do one thing. Use tensorly for unfolding. Make a function that unfolds the input array. Then using that funtion make a lambda layer in keras or tf2.0 . Suppose you have input array X : X = np.array([[[ 0, 1], [ 2, 3], [ 4, 5], ...
https://stackoverflow.com/questions/63156717/
What should be the size of input image for training a YOLOv3 Model Architecture CNN.?
I've implemented a YOLOv3 from scratch and I plan to fine-tune using MS-COCO weights for some different data. The dataset I've chosen has images of 720*1280 size. When I go through the YOLOv3 paper, 1st CONV2d layer is there with filter_size =3 and stride = 1, and output size is 256*256.... Can someone give me a walkth...
From Yolov3 paper: If best possible accuracy/mAP is what you want then use 608 x 608 as input layer size in the config. If you want good inference/speed at the cost of accuracy then use, 320 x 320 If balanced model is what you want then use 416 x 416 Note that first layer automatically resizes your images to the size...
https://stackoverflow.com/questions/63160524/
pytorch beginner :torch.data.new() torch.new()
I have a small question, what is the difference between tensor.data.new() and tensor.new()? It seems they all return an empty tensor with the same dtype and device as the self tensor. Thank you
There is no difference. It's a little convoluted, but, you can think of .data as being essentially the same object as the Tensor that holds it. Every Tensor has a .data, and the .data is, itself, a Tensor, so there's some circular references going on. The most important part is that they both always point to the same d...
https://stackoverflow.com/questions/63166005/
How to save and load models of custom dataset in Detectron2?
I have tried to save and load the model using: All keys are mapped but there is no prediction in output #1 from detectron2.modeling import build_model model = build_model(cfg) torch.save(model.state_dict(), 'checkpoint.pth') model.load_state_dict(torch.load(checkpoint_path,map_location='cpu')) I also tried doing it ...
cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file('COCO-Detection/faster_rcnn_R_101_FPN_3x.yaml')) cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # Set threshold for this model cfg.MODEL.WEIGHTS = '/content/model_final.pth' # Set path model .pth cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1 predictor = DefaultPredictor(...
https://stackoverflow.com/questions/63166152/
Problem of exporting batchnorm weight from pytorch to Keras
I follow Pytorch Batchnorm layer different from Keras Batchnorm, Pytorch Batchnorm implementation, but they do not solve my problem. I also read Wiki about Batchnorm. And search source code from tensorflow batchnorm and from pytorch source code. Below is my testing code, and the results between pytorch and keras are di...
Keras seems use different default value epsilon (1e-3) vs (1e-5) in Pytorch The input "var" in source code from tensorflow seems had already been taken 1/moving_variance somewhere. Besides batchnorm, the padding strategy of tensorflow vs pytorch may yield different result of output. It is recommended to us...
https://stackoverflow.com/questions/63177631/
Pytorch guide not using optim to train
I am currently working through a guide on the Pytroch website here: https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html I have done pytorch projects before and they have always made use of an optimizer. This guide instead uses the code here: # Add parameters' gradients to their values, ...
Why do you expect it to not work? Basically what it is doing is manually implementing an optimizer. p.data is the stored value of the parameter. It also provides an internal function add_ that calculates +=. Once loss.backward() is called, pytorch also calculates and stores the gradient. It is simply taking the the gra...
https://stackoverflow.com/questions/63181394/
RuntimeError: The expanded size of the tensor (7) must match the existing size (128) at non-singleton dimension 3
When I run AdaIN code def adaptive_instance_normalization(content_feat, style_mean, style_std): size = content_feat.size() content_mean, content_std = calc_mean_std(content_feat) normalized_feat = (content_feat - content_mean.expand( size)) / content_std.expand(size) return normalized_feat * st...
You should be more precise and descriptive while explaining your issue. You cannot expect from people to read your mind or be familiar with your exact problem. So first, what should be the expected output and which line is failing ? I guess from the expand calls that you would like to enable broadcasting. Unfortunately...
https://stackoverflow.com/questions/63185421/
How should I apply a variational autoencoder in a low-dimensional real value case?
I am trying to applying VAE in a simple toy example to familiarize with its property. However, I get stuck in training the model. The total loss and the reconstruction error does not seem to decrease. The toy example is listed below random generate 5000 observation from a 2-dimensional multivariate normal distribution...
Just to pose a potential reason that leads to the result. In a paper introduction the Hyperspherical Variational Auto-Encoders, the author suggests a problem of using gaussian as prior in the low dimensional setting. The problem is called origin gravity. Quote the paper. In low dimensions, the Gaussian density presents...
https://stackoverflow.com/questions/63188002/
Is it normal that accuracy decreases when advancing to the next epoch?
I’m training a CNN to predict digits using the MNIST database. I’m doing Data Augmentation and for some reason accuracy sharply decreases when advancing to next epoch (iteration 60 in the image) It has to do with data augmentation (transform = my_transforms in the code) because when I deactivate augmentation (transfor...
I replicated your model with data augmentation and tried to plot the Accuracy and Loss and it seems that the problem is the way you are plotting. In the following lines I attach my code and Loss and Accuracy plots: Code: # -- Imports -- # import torch from torch import nn, optim from torch.utils.data import DataLoader...
https://stackoverflow.com/questions/63194095/
Why Pytorch is slower than Tensorflow in read data
I tried two version code for iterate MNIST data to compare the elapsed time. Pytorch version import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" import torch from torchvision import datasets, transforms import matplotlib.pyplot as plt import time train_loader = torch.utils.data.DataLoader( datase...
Shijia li, You do everything correctly, it is just less fast code used in Pytorch (perhaps for a reason). I looked into Pytorch source code and found the following: train_loader generates indices for each batch(30000-long list) train_loaderindices to fetcher. Fetcher collects data from the dataset, but it only does it...
https://stackoverflow.com/questions/63202478/
How to add hidden neurons to a Pytorch RNN
How can I add hidden neurons to a Recurrent Neural Network in pytorch? In my understanding, torch.nn.RNN has n neurons with inputs being the input and the hidden state, where n is equal to the size of the hidden state. How can I add additional layers before the neurons go back to the hidden state? E.g. If i only have 1...
You can't define rnn without defining hidden neurons. Lets look at the official example: class RNNTutorial(Module): def __init__(self, input_size, hidden_size, output_size): super(RNNTutorial, self).__init__() self.hidden_size = hidden_size size_sum = input_size + hidden_siz...
https://stackoverflow.com/questions/63210533/
when importing pytorch microsoft visual C++ Redistributable is not installed
I work in a windows machine with GPU. I have installed pytorch in a conda environment with conda install pytorch torchvision cudatoolkit=10.1 -c pytorch then I run python and inside of python I do import torch and I get this error Python 3.6.10 |Anaconda, Inc.| (default, May 7 2020, 19:46:08) [MSC v.1916 ...
Get the Microsoft Visual C++ Redistributable installer from the link in the error, in this case is this. Run the installer and launch again your shell with conda configured when finished
https://stackoverflow.com/questions/63212096/
PyTorch tensors have same value after being added to a list
While learning gradients and optimizing the process by Pytorch, I wanted to figure out the change of loss function values vs weights values with the graph. While I tried to graph, I used both numpy and torch, because I wanted to compare. During to store list of grad. and loss function values. It works at numpy: def gra...
w.grad is a tensor; it (the same tensor) is appended to the list at each iteration, so the list contains copies of the same tensor, not copies of its value at each point in time as you'd probably intend. The standard way of handling this is to use: dw_list.append(w.grad.detach().cpu().numpy()) Please have a look at t...
https://stackoverflow.com/questions/63213881/
Number of layers vs list(net.parameters())
New to convolutional neural nets so sorry if this doesn't make much sense. I have this code: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Lin...
Quick answer : You get an extra parameter array for each layer containing the bias vector associated to the layer. Detailled answer: I will try to guide you in my process of investigating your questions. It seems like a good idea to see what our 10 parameters are : for param in net.parameters(): print(type(param), ...
https://stackoverflow.com/questions/63215362/
Fine-Tuning DistilBertForSequenceClassification: Is not learning, why is loss not changing? Weights not updated?
I am relatively new to PyTorch and Huggingface-transformers and experimented with DistillBertForSequenceClassification on this Kaggle-Dataset. from transformers import DistilBertForSequenceClassification import torch.optim as optim import torch.nn as nn from transformers import get_linear_schedule_with_warmup n_epoch...
Looking at running loss and minibatch loss is easily misleading. You should look at epoch loss, because the inputs are the same for every loss. Besides, there are some problems in your code, fixing all of them and the behavior is as expected: the loss slowly decreases after each epoch, and it can also overfit to a smal...
https://stackoverflow.com/questions/63218778/
RuntimeError: DataLoader worker (pid 27351) is killed by signal: Killed
I'm running the data loader below which applies a filter to a microscopy image prior to training. In order to count the red and green. This code filters the red cells. Since I have applied this to the code I keep on getting the error message above. I have tried increasing the memory allocation to the maximum allowance ...
Similar problem I met before. One possible solution is to disable cv2 multi-processing by def __getitem__(self, idx): import cv2 cv2.setNumThreads(0) # ... in your dataloader. It might be because the cv2 multi-processing is conflict with torch's DataLoader with multi-processing. Although it does not work ...
https://stackoverflow.com/questions/63221468/
How can I cross-validate by Pytorch and Optuna
I want to use cross-validation against the official Optuna and pytorch-based sample code (https://github.com/optuna/optuna/blob/master/examples/pytorch_simple.py). I thought about splitting the data for cross-validation and trying parameter tuning for each fold, but it seems that the average accuracy of each parameter ...
I think we need to evaluate all folds and calculate the mean inside an objective function. I create an example notebook, so please take a look. In the notebook, I slightly modified the objective function to pass the dataset with the arguments and added a wrapper function objective_cv to call the objective function with...
https://stackoverflow.com/questions/63224426/
Torch sum subsets of tensor
if the tensor is of shape [20, 5] then I need to take 10 at a time and sum them, so result is [2,5]. eg: shape[20,5] -> shape[2, 5] (sum 10 at a time) shape[100, 20] -> shape[10,20] (sum 10 at a time) Is there any faster/optimal way to do this? eg: [[1, 1], [1, 2], [3, 4], [1,2]] i want [[2, 3], [4, 6]] by taking...
It is not completely clear, but I cannot use a comment for this, so. For the first case you have: t1 = torch.tensor([[1., 1.], [1., 2.], [3., 4.], [1.,2.]]) t1.shape #=> torch.Size([4, 2]) t1 tensor([[1., 1.], [1., 2.], [3., 4.], [1., 2.]]) To get the desired output you should reshape: tr1 =...
https://stackoverflow.com/questions/63240702/
NameError: name 'base' is not defined, while running open AI gym in GOOGLE COLAB
I am going through the tutorial DQN reinforcement learning in Pytorch.org,https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html But here when I am trying to render a screen and display using python display, I am getting name base not found. Can anyone help me here? If you want to clear any clarity ab...
Use the gpu on colab. If with that isn't enought execute this cell at the beginning !apt install xvfb -y !pip install pyvirtualdisplay !pip install piglet from pyvirtualdisplay import Display display = Display(visible=0, size=(1400, 900)) display.start()
https://stackoverflow.com/questions/63250935/
Unable to create custom dataset and dataloader using torchtext
I have questions regarding building custom dataset and iterator using torchtext. I used the following code found in this post and modified based on my case: tokenizer = XLNetTokenizer.from_pretrained("xlnet-base-cased") text_field = Field(sequential=True, eos_token="[CLS]", tokenize=tokenizer) label...
I think as you are using a predefined tokenizer you dont't need to build vocab, instead you can follow this steps. Showing an example of how to do it using BERT tokenizer. Sentences: it is a list of of text data lables: is the label associated ###tokenizer = XLNetTokenizer.from_pretrained("xlnet-base-cased") ...
https://stackoverflow.com/questions/63254843/
Why cant I use ONNX Runtime training with pytorch?
When I run from onnxruntime.capi.ort_trainer import ORTTrainer as stated at https://github.com/microsoft/onnxruntime/#training-start, I get this error: ModuleNotFoundError: No module named 'onnxruntime.capi.ort_trainer' What can I do to fix this? I have onnxruntime installed via pip but I couldn't even find "ort_t...
You should build ort training from source. https://www.onnxruntime.ai/docs/how-to/build.html#training
https://stackoverflow.com/questions/63255037/
Pytorch and data augmentation: how to augmentate data with blur, rotations, etc
I want to do some data augmentation with Pytorch, but i don't know the libraries very well: I tried this: def gaussian_blur(img): image = np.array(img) image_blur = cv2.GaussianBlur(image,(65,65),10) new_image = image_blur im = Image.fromarray(new_image) return im data_transforms = { 'train':...
If you want to apply Gausian blur there is also already a pytorch class for: torchvision.transforms.GaussianBlur(kernel_size, sigma=(0.1, 2.0))
https://stackoverflow.com/questions/63288388/
CUDA out of memory runtime error, anyway to delete pytorch "reserved memory"
Like many othersm I'm getting a Runtime error of Cuda out of memory, but for some reason pytorch has reserved a large amount of it. RuntimeError: CUDA out of memory. Tried to allocate 2.00 MiB (GPU 0; 6.00 GiB total capacity; 4.31 GiB already allocated; 844.80 KiB free; 4.71 GiB reserved in total by PyTorch) I've tried...
From the given description it seems that the problem is not allocated memory by Pytorch so far before the execution but cuda ran out of memory while allocating the data that means the 4.31GB got already allocated (not cached) but failed to allocate the 2MB last block. Possible solution already worked for me, is to decr...
https://stackoverflow.com/questions/63293620/
Overlap and add tensor in pytorch using nn.fold
I have the following problem, I have tensor with shape (1,16198), first i would like to dive it into chunks so I used unfold like: my_tensor.unfold(-1, 178, 89) -> tensor with shape (1, 182, 178) which means 182 overlapping chunks of size 178, that's perfect. But now I would like to undo the operation adding the o...
Got it to work last night, i had to transpose to the (1, 182, 178) tensor to (1, 178, 182) then I used nn.Fold(my_tensor, (1, 16198), kernel_size=(1,178), stride=(1,89)) and i get back my tensor with overlapping sections added, thus completing the overlap and add algorithm, still not sure how nn.Fold works.
https://stackoverflow.com/questions/63293877/
Difference between hidden dimension and n_layers in rnn using pytorch
I am stuck between hidden dimension and n_layers. What I understood so far, is that n_layers in the parameters of RNN using pytorch, is number of hidden layers. If n_layers represents the number if hidden layers than what is hidden dimension?
Actually documentation is really clear about their differences. Hidden size is number of features of the hidden state for RNN. So if you increase hidden size then you compute bigger feature as hidden state output. However, num_layers is just multiple RNN units which contain hidden states with given hidden size. num_la...
https://stackoverflow.com/questions/63294347/
Loading enormous custom dataset using IterableDataset
I have a huge dataset with features (input_id,input_mask,segment_id,label_id) saved in batches of 64 in a pickle file. I read this file, create a TensorDataset and pass to dataloader for training. Since the features file is too big to create the full TensorDataset, I want to convert TensorDataset to IterableDataset so ...
I solved the problem by saving the dataset in a different manner. I saved the features as dictionary objects incrementally pickled in a pickle file and just read them off one at a time and pass on to dataloader for processing. Batching is done automatically by the dataloader. This is how the custom class looks now: cla...
https://stackoverflow.com/questions/63298647/
Index multidimensional torch tensor with array of variable length
I have a list of indices and a tensor with shape: shape = [batch_size, d_0, d_1, ..., d_k] idx = [i_0, i_1, ..., i_k] Is there a way to efficiently index the tensor on each dim d_0, ..., d_k with the indices i_0, ..., i_k? (k is available only at run time) The result should be: tensor[:, i_0, i_1, ..., i_k] #tensor.sh...
Unfortunately you can't provide1 a mix of slices and iterators to an indexing (e.g. a[:,*idx]). However, you can achieve almost the same thing by wrapping it in brackets to cast to an iterator: a[(slice(None), *idx)] In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is ju...
https://stackoverflow.com/questions/63309876/
trying to import png images to torchvision
I am attempting to import images for use with torch and torchvision. But I am receiving this error: TypeError: Caught TypeError in DataLoader worker process 0. Original Traceback (most recent call last): File "c:\python38\lib\site-packages\torch\utils\data\_utils\worker.py", line 178, in _worker_loop da...
Please note that I had wanted to automatically load all PNG images in a directory as pytorch tensors. I had previously looked at posts like this (and many other web pages): Loading a huge dataset batch-wise to train pytorch But instead I ended up using this where I am using Image.open one by one on all the images in t...
https://stackoverflow.com/questions/63332048/
How to transform labels in pytorch to onehot
How to give target_transform a function for changing the labels to onehot encoding? For example, the MNIST dataset in torchvision: train_dataset = torchvision.datasets.MNIST(root='./mnist_data/', train=True, download=True, ...
This is how I implemented it. Not sure if there's a cleaner way. train_dataset = torchvision.datasets.MNIST(root='./data/', train=True, transform=torchvision.transforms.ToTensor(), target_transform=torchvision.transforms.Compose([ ...
https://stackoverflow.com/questions/63342147/
Cant install pytorch - ModuleNotFoundError: No module named 'tools.nnwrap'
I cannot install PyTorch on python 3.7. This error occurs for others but the suggested fixes did not work. I have tried instaling wheel, and importing tools but neither work. Got error: ModuleNotFoundError: No module named 'tools.nnwrap' ran command pip install --pre torch torchvision -f https://download.pytorch.org/wh...
Fixed: needed to use python 64-bit not 32-bit
https://stackoverflow.com/questions/63345212/
pytorch dataset map-style vs iterable-style
A map-style dataset in Pytorch has the __getitem__() and __len__() and iterable-style datasets has __iter__() protocol. If we use map-style, we can access the data with dataset[idx] which is great, however with the iterable dataset we can't. My question is why this distinction was necessary? What makes the data random ...
I wrote a short post on how to use PyTorch datasets, and the difference between map-style and iterable-style dataset. In essence, you should use map-style datasets when possible. Map-style datasets give you their size ahead of time, are easier to shuffle, and allow for easy parallel loading. It’s a common misconception...
https://stackoverflow.com/questions/63347149/
pytorch code sudden fails on colab with NVIDIA driver on your system is too old
I had some code which worked on colab (gpu runtime) just a short while ago. Suddenly I am getting The NVIDIA driver on your system is too old (found version 10010). nvcc shows Cuda compilation tools, release 10.1, V10.1.243 I tried torch versions 1.5.1, then 1.13.0. Both keep getting this error. There is a discussion s...
The light-the-torch package is designed to solve exactly this type of issue. Try this: !pip install light-the-torch !ltt install torch torchvision
https://stackoverflow.com/questions/63349832/
will loop decrease the utilization of the GPU?
In PyTorch, I have a loop in my DeepLearning Pipeline's forward part to normalize the intermediate result. Will it run on CPU and decrease the utilization of the GPU? some snippet as follow: def forward(self): ... for b in range(batch_size): self.points[b] = self.unit_cube(self.points[b]) ....
In Pytorch, whether an operation is done on the GPU or CPU is decided by where the data is. One of the main selling points of Pytorch is that you don't (usually) have to care where the data is; the interface is the same. If the tensor data is on the GPU, then the operation is done on the GPU. If it's on the CPU, then t...
https://stackoverflow.com/questions/63350404/
torch.no_grad() affects on model accuracy
I am getting an error "CUDA out of memory" then i add torch.no_grad() function into my code. Is it affect on my accuracy? for iters in range(args.iterations): with torch.no_grad(): encoded, encoder_h_1, encoder_h_2, encoder_h_3 = encoder( res, encoder_h_1, encoder_h_2, encoder_h_3) with torch.no_gra...
torch.no_grad() just disables the tracking of any calculations required to later calculate a gradient. It won't have any effect on accuracy in a pure inference mode, since gradients are not needed there. Of course you can't use it during training time since we need the gradients to train and optimize. In general if you...
https://stackoverflow.com/questions/63351268/
Why is the accuracy difference so much when I use the image data set and pytorch's own data set directly?
For example, for the cifar10 data set, directly using the data set that comes with pytorch, the accuracy rate can reach 96% under the same network structure, but after I converted cifar10 into a picture, I tested it and the accuracy rate was only 92%. why? This is the previous code: train_dataset = dset.CIFAR10(args.da...
If the downloaded dataset, hyperparameters(such as batch size or learning rate), dataset transformation, etc were equal, I think it is because the randomness. Your dataloader shuffles the dataset randomly. The shuffled dataset will always be different every time you shuffle it, which might have led to the accuracy diff...
https://stackoverflow.com/questions/63352551/
Google Cloud Function Build timeout - all requirements have been loaded
I have the following code on my cloud function - import os import numpy as np import requests import torch from torch import nn from torch.nn import functional as F import math from torch.nn import BCEWithLogitsLoss from torch.utils.data import TensorDataset from transformers import AdamW, XLNetTokenizer, XLNetModel,...
It might be due to the torch import, as this causes you to import the PyTorch lib that contains CUDA and hence requires a GPU, which isn't available on Cloud Functions. Instead, you can use a direct link to the cpu only version in your requirements.txt, like this: certifi==2020.6.20 chardet==3.0.4 click==7.1.2 cycler==...
https://stackoverflow.com/questions/63369555/
Max function in PyTorch versus in NumPy
I am developing an algorithm that involves a CPU case, allowing for NumPy, and a GPU case, allowing for PyTorch. The object will almost always be 4D. Two versions of the object are as follows. B = [ [[[0.5000, 0.5625], [0.5000, 0.5625]], [[1.2500, 0.5000], [0.5625, 0.6875]], [[0.5625, 0.6250...
Not the most elegant way: B.max(dim=3)[0].max(dim=2)[0].max(dim=0)[0]
https://stackoverflow.com/questions/63369743/
Pytorch rename labels of a trained model
I have a trained model. During training there was some problem with string characters. So i converted my labels into numbers like: red : 0 blue: 1 green: 2 Now is it possible to rename my label back to actual label names. Hours of training. Would be helpful if anyone has an idea. Train and validate the model for epoch...
Use a dictionary for it! labels = [0, 1, 2, 1, 0, 2, 1] dct = {0: "red", 1: "blue", 2: "green"} renamed_labels = [dct[x] for x in labels] renamed_labels ## ["red", "blue", "green", "blue", "red", "green", "blue"]
https://stackoverflow.com/questions/63372759/
Summing over specific indices PyTorch (similar to scatter_add)
I have some matrix where rows belong to some label, unordered. I want to sum all rows for each label. Here is how it can be done with a loop: labels = torch.tensor([0, 1, 0]) x = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) torch.stack([torch.sum(x[labels == i], dim=0) for i in torch.unique(labels)]) desired output: ...
Just use torch.index_add function. labels = torch.tensor([0, 1, 0]) x = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) nrow = torch.unique(labels).size(0) ncol = x.size(1) out = torch.zeros((nrow, ncol), dtype=x.dtype) out.index_add_(0, labels, x) print(out) # the output will be # tensor([[ 8, 10, 12], # [ 4,...
https://stackoverflow.com/questions/63380445/
Creating a criterion that measures the F1 Loss
I am currently creating criterion to measure the MSE loss function using: loss_fcn = torch.nn.MSELoss() loss = loss_fcn(logits[getMaskForBatch(subgraph)], labels.float()) Now I need to change it to F1 score but I cannot seem to find one library that could be used for it
In particular, depending on the task you need to have a specific loss function. Loss function also known as objective, cost or error function is somehow opposite to the optimization function. Loss function creates the loss, optimization function reduces the loss. :). These two functions should live in equilibrium so we...
https://stackoverflow.com/questions/63400496/
torch.jit.script(module) vs @torch.jit.script decorator
Why is adding the decorator "@torch.jit.script" results in an error, while I can call torch.jit.script on that module, e.g. this fails: import torch @torch.jit.script class MyCell(torch.nn.Module): def __init__(self): super(MyCell, self).__init__() self.linear = torch.nn.Linear(4, 4) ...
Reason for your error is here, this bulletpoint precisely: No support for inheritance or any other polymorphism strategy, except for inheriting from object to specify a new-style class. Also, as stated at the top: TorchScript class support is experimental. Currently it is best suited for simple record-like types (th...
https://stackoverflow.com/questions/63401585/
Pytorch: How to train a network with two loss functions?
I want to pretrain a network with reconstruction loss first, then finetune it by crossentropy loss. But it seems that I have to define two network in this two stage. How to achieve it? class Net(): def __init__(self,pretrain): self.pretrain = pretrain def encoder(self,x): # do something here ...
You can achieve this by simply defining the two-loss functions and loss.backward will be good to go. See the relevant discussion here MSE = torch.nn.MSELoss() crossentropy = torch.nn.CrossEntropyLoss() def train(x,y): pretrain = True if pretrain: network = Net(pretrain=True) ...
https://stackoverflow.com/questions/63404656/
The use of meshgrid in pytorch/numpy
Below code is a snippet taken from https://blog.paperspace.com/how-to-implement-a-yolo-v3-object-detector-from-scratch-in-pytorch-part-3/, and I am confused as to what it is trying to achieve. grid = np.arange(grid_size) a,b = np.meshgrid(grid, grid) x_offset = torch.FloatTensor(a).view(-1,1) y_offset ...
If you are expecting the second output you show, simply change x_y_offset = ( torch.cat((x_offset, y_offset), 1).repeat(1, num_anchors).view(-1, 2).unsqueeze(0) ) to x_y_offset = ( torch.cat((y_offset, x_offset), 1).repeat(1, num_anchors).view(-1, 2).unsqueeze(0) ) It just has to do with the ordering of the o...
https://stackoverflow.com/questions/63417951/
Three dimensional autoencoder has low MSE loss but gives noisy reconstruction image
I am re-constructing spatio-temporal cuboids of 3-dimensional size with width and height equal to 32 and depth equal to 20. I am using Conv3d layers in my autoencoder architecture. So my input shape is 32x32x20, which I am reducing to size 2048, and then reconstructing it back to 32x32x20. The MSE loss of the model has...
I'm not sure what your loss term or training process looks like, but you may want to consider a couple of things: training for more epochs since 200 may be a relatively large MSE (and you may be stuck in a local minima for which case a higher gradient or different optimizer/optimizer hyper-parameters may help) changi...
https://stackoverflow.com/questions/63418904/
pytorch model saved from TPU run on CPU
I found interesting model - question generator, but can't run it. I got an error: Traceback (most recent call last): File "qg.py", line 5, in <module> model = AutoModelWithLMHead.from_pretrained("/home/user/ml-experiments/gamesgen/t5-base-finetuned-question-generation-ap/") File "...
As @cronoik suggested, I have installed transformers library form github. I clonned latest version, and executed python3 setup.py install in it's directory. This bug was fixed, but fix still not released in python's packets repository.
https://stackoverflow.com/questions/63419835/
Using pytorch Cuda on MacBook Pro
I am using MacBook Pro (16-inch, 2019, macOS 10.15.5 (19F96)) GPU AMD Radeon Pro 5300M Intel UHD Graphics 630 I am trying to use Pytorch with Cuda on my mac. All of the guides I saw assume that i have Nvidia graphic card. I found this: https://github.com/pytorch/pytorch/issues/10657 issue, but it looks like I need to...
No. CUDA works only with supported NVidia GPUs, not with AMD GPUs. There is an ongoing effort to support acceleration for AMD GPUs with PyTorch (via ROCm, which does not work on MacOS).
https://stackoverflow.com/questions/63423463/
AssersionError: Torch not compiled with CUDA enabled
I want to run this repo. I installed everything that is needed for this project. I have Windows 8.1 operating system, seems that I don't have NVIDIA GPU (from Device Manager: Display adapters - AMD Radeon HD 7660G + 7670M Dual Graphics and AMD Radeon HD 7670M). I installed torch with command that is presented on Pytorc...
I have already fixed this issue. There was a problem in source code where they use opt.device in main.py and violin_dataset.py. But this was declared as opt.device = torch.device('cuda:0') in config.py even if you didn't have cuda support. So I changed it to opt.device = torch.device('cpu') And everything works fine...
https://stackoverflow.com/questions/63440170/
Use SageMaker Pytorch image for training
I am trying to containerize the training process for a fine tuned BERT model and run it on SageMaker. I was planning to use the pre-built SageMaker Pytorch GPU containers (https://aws.amazon.com/releasenotes/available-deep-learning-containers-images/) as my starting point but I am having issues pulling the images durin...
You should run something like this, before running the docker build: aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin 763104351884.dkr.ecr.${region}.amazonaws.com
https://stackoverflow.com/questions/63440881/
How to know whether the data passed to GPU will cause CUDA out of memory or not
I am using GPU to run some very large deep learning models, when I choose a batch size of 8, it can fit into the memory, but if I use a batch size of 16, it will cause CUDA out-of-memory error, and I have to kill the process. My question is, before actually passing the data into GPU, is there a way that I could know ho...
I would recommend using the torchsummary package here. pip install torchsummary and in use from torchsummary import summary myModel.cuda() summary(myModel, (shapeOfInput)) # where shapeOfInput is a tuple of the sample's dimensions This will give you the size of the model, the size of the forward pass, and the size of...
https://stackoverflow.com/questions/63443270/
Runtime error while executing code from google colab document for creating Deepfakes image animation
enter image description hereI'm getting runtime error while executing code from google colab document for creating Deepfakes image animation. RuntimeError Traceback (most recent call last) <ipython-input-5-dbd18151b569> in <module>() 1 from demo import load_checkpoints 2 ge...
You may be running on a colab environment that only has TPU's available and not GPU's in which case you need to utilize XLA with PyTorch. You might find this notebook and repository very helpful if this is the case: https://colab.research.google.com/github/pytorch/xla/blob/master/contrib/colab/resnet18-training.ipynb h...
https://stackoverflow.com/questions/63445839/