instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Creating and train only specified weights in TensorFlow or PyTorch
I am wondering if there is a way in TensorFlow, PyTorch or some other library to selectively connect neurons. I want to make a network with a very large number of neurons in each layer, but that has very few connections between layers. Note that I do not think this is a duplicate of this answer: Selectively zero weig...
The usual, simple solution is to initialize your weight matrices to have zeros where there should be no connection. You store a mask of the location of these zeros, and set the weights at these positions to zero after each weight update. You need to do this as the gradient for zero weights may be nonzero, and this woul...
https://stackoverflow.com/questions/52866049/
PyTorch: new_ones vs ones
In PyTorch what is the difference between new_ones() vs ones(). For example, x2.new_ones(3,2, dtype=torch.double) vs torch.ones(3,2, dtype=torch.double)
For the sake of this answer, I am assuming that your x2 is a previously defined torch.Tensor. If we then head over to the PyTorch documentation, we can read the following on new_ones(): Returns a Tensor of size size filled with 1. By default, the returned Tensor has the same torch.dtype and torch.device as this ...
https://stackoverflow.com/questions/52866333/
What does the "greater than" operator ">" mean for PyTorch tensors?
I have a tensor it defined as: import torch it = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], device='cuda:0') Given this definition, what does it > 0 then mean?
Using the > operator is the same as using the torch.gt() function. In other words, it > 0 is the same as torch.gt(it, 0) and it returns a ByteTensor (a Boolean tensor) of the same shape as it where out[i] is True if it[i] > 0 and False otherwise.
https://stackoverflow.com/questions/52868102/
is it possible make cuda deterministic?
I am trying to refactor an application and testing new against old version by comparing outputs. At the first pytorch conv layer using identical input I get identical output when using CPU. However using cuda on GPU the output tensors differ in the 5th decimal place on some cells. Is there any way to eliminate this dif...
cpu and gpu can't produce the same result even if the seeds are set equal. Refer to this and this.
https://stackoverflow.com/questions/52874480/
Pytorch : significance of grad_h_relu.clone() in Backprop
I am learning Pytorch, while I'm looking to the tutorial on their site I can't understand the significance of grad_h = grad_h_relu.clone(). h = x.mm(w1) h_relu = h.clamp(min=0) y_pred = h_relu.mm(w2) # Compute and print loss loss = (y_pred - y).pow(2).sum().item() print(t, loss) # Backprop to compute gradients of w1...
grad_h = grad_h_relu.clone() It means that you are making a copy of the gradient of relu such that it does not share the memory with the original grad_h_relu. Then you perform some operation on it. As they are stored in two different locations, changing the value of grad_h by the following operation will not affect t...
https://stackoverflow.com/questions/52875989/
What is the equivalent of torch.nn.functional.grid_sample in Tensorflow / Numpy?
I am new to pytorch and have been trying to convert some code . Can't find this particular functionality . Does it exist in tensorflow ?
I do not think there is anything like that provided in TensorFlow. Here is a possible implementation for the 2D case (I have not considered padding, but the code should behave like the border mode). Note that, unlike the PyTorch version, I am assuming the input dimension order is (batch_size, height, width, channels) (...
https://stackoverflow.com/questions/52888146/
PyTorch autocomplete (code completion) in Sublime Text 3
I'm a fan of Sublime Text 3 and would like to get code autocompletion for PyTorch. However, I can't get this working yet. Any suggestions or starting points where I can begin to get this working? I have searched in the packages repository of Sublime Text but unfortunately there's none. Note: I have looked at a relate...
Not a sublime user, but Jedi autocompletion handles PyTorch suggestions just fine. Jedi is an autocompletion engine and should work for any Python package, including the ones in virtual environment if you set it up and including PyTorch/Tensorflow. Anyway, sublime version seems to be missing a few things like results...
https://stackoverflow.com/questions/52957809/
Error while executing RNN code on pyTorch?
I am running a code on Binary Addition of two strings using PyTorch. However, while training the model I am getting the following error: can't convert np.ndarray of type numpy.object. The only supported types are: double, float, float16, int64, int32, and uint8. Can anyone help me? Here is my code: featDim=2 #...
The main problem here is the type of your y. You haven't given any information about this, therefore this here will be more general: But obviously your ndarray doesn't contain numeric data types. You have to use one of these mentioned in your error message: The only supported types are: double, float, float16, int...
https://stackoverflow.com/questions/52966950/
How can I visualize what happens during loss.backward()?
I am confident in my understanding of the forward pass of my model, how can I control its backward pass? This is not a theoretical question about what back-propagation is. The question is a practical one, about whether or not there are tools suited to visualize/track/control what happens during back-propagation. Idea...
There has been been already mention of pytorchviz which lets you visualize the graph. Here is a small example that might help you to understand how pytorchviz does trace the graph using the grad_fn: import torch from torch import nn d = 5 x = torch.rand(d, requires_grad=True) print('Tensor x:', x) y = torch.ones(d, ...
https://stackoverflow.com/questions/52988876/
KL Divergence of Normal and Laplace isn't Implemented in TensorFlow Probability and PyTorch
In both TensorFlow Probability (v0.4.0) and PyTorch (v0.4.1) the KL Divergence of the Normal distribution (tfp, PyTorch) and the Laplace distribution (tfp, PyTorch) isn't implemented resulting in a NotImplementedError error being thrown. >>> import tensorflow as tf >>> import tensorflow_probability a...
IIRC, Edward's KLqp switches tries to use the Analytic form, and if not switches to using the sample KL. For TFP, and I think PyTorch, kl_divergence only works for distributions registered, and unlike Edward only computes the analytic KL. As you mention, these aren't implemented in TFP, and I would say that's more of...
https://stackoverflow.com/questions/53036403/
Pytorch is not using GPU even it detects the GPU
I made my windows 10 jupyter notebook as a server and running some trains on it. I've installed CUDA 9.0 and cuDNN properly, and python detects the GPU. This is what I've got on the anaconda prompt. >>> torch.cuda.get_device_name(0) 'GeForce GTX 1070' And I also placed my model and tensors on cuda by .cuda...
I had a similar problem with using PyTorch on Cuda. After looking for possible solutions, I found the following post by Soumith himself that found it very helpful. https://discuss.pytorch.org/t/gpu-supposed-to-be-used-but-isnt/2883 The bottom line is, at least in my case, I could not put enough load on GPUs. There was ...
https://stackoverflow.com/questions/53043713/
Importing pytorch in Spyder crashes kernel after installing matplotlib
I created an environment in Anaconda3 and installed pytorch and spyder on a Linux machine. Here are the specifications: spyder 3.3.1 ipython 7.0.1 python 3.7.0 pytorch 0.4.1 torchvision 0.2.1 When I open spyder and im...
I have ipython 7.0.1 and matplotlib 2.0.2 and the same problem, it seems like ipython crashes after the following two commands: %matplotlib auto followed by import torch. This happens both in spyder as in jupyter notebook when the two commands are in seperate blocks. What worked for me was: First making sure that spy...
https://stackoverflow.com/questions/53047983/
Pytorch 3-GPUs, just can only use 2 of them to train
I have three 1080TI, but when train I can only use 2 of them.. Code: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.cuda() criterion = nn.CrossEntropyLoss().cuda() optimizer_conv = optim.SGD(model.classifier.parameters(), lr=0.0001, momentum=0.9) exp_lr_scheduler = lr_scheduler.StepLR(op...
eeeee.. I found the reason: my batchsize = 4 when there are three GPUs so Change batchsize bigger can solve this "weird" problem
https://stackoverflow.com/questions/53078632/
PyTorch Cuda with anaconda not available
I'm using anaconda to regulate my environment, for a project i have to use my GPU for network training. I use pytorch for my project and i'm trying to get CUDA working. I installed cudatoolkit, numba, cudnn still, when i try this command: torch.cuda.is_available() I get "False" as output. This is my environment: ...
You need to install pytorch "in one go" using https://pytorch.org/get-started/locally/ to construct the anaconda command. With the standard configuration in anaconda, you get: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch (Please always check on https://pytorch.org/get-started/locally/ whethe...
https://stackoverflow.com/questions/53102436/
Error in training PyTorch classifier from the 60 minute blitz in GPU
I've started to learn pytorch with their official 60 minute blitz tutorial in a jupyter lab (using their .ipynb file, link to the tutorial), and have completed it successfully until the conversion and training of the classifier using the gpu. I think that I have managed to change the device for the net, inputs and labe...
You also need to move your inputs and labels to GPU inside the training loop. for i, data in enumerate(trainloader, 0): # get the inputs inputs, labels = data # move to GPU inputs = inputs.to(device) labels = labels.to(device) ...
https://stackoverflow.com/questions/53106369/
Pytorch: is there a function similar to torch.argmax which can really keep the dimension of the original data?
For example, the code is input = torch.randn(3, 10) result = torch.argmax(input, dim=0, keepdim=True) input is tensor([[ 1.5742, 0.8183, -2.3005, -1.1650, -0.2451], [ 1.0553, 0.6021, -0.4938, -1.5379, -1.2054], [-0.1728, 0.8372, -1.9181, -0.9110, 0.2422]]) and result is tensor([[ 0, 2, 1, 2...
Finally, I solved it. But this solution may not be efficient. Code as follow, input = torch.randn(3, 10) result = torch.argmax(input, dim=0, keepdim=True) result_0 = result == 0 result_1 = result == 1 result_2 = result == 2 result = torch.cat((result_0, result_1, result_2), 0)
https://stackoverflow.com/questions/53116477/
Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor for argument #2 'weight'
Firstly I have used like 'model.cuda()' to convert model and data to cuda. But it still has such a problem. I debug every layer of the model, and weights for every module has iscuda=True. So does anyone know why there is such a problem? I have two models, one is resnet50 and another one which contains the first one as...
Somewhere down in the stack trace, Torch is expecting a CPU tensor (torch.FloatTensor) but is getting a GPU / CUDA tensor (torch.cuda.FloatTensor). Given a tensor tensor: tensor.to('cpu') returns the CPU version of the tensor tensor.to('cuda') returns the CUDA version of the tensor To write hardware-agnostic code:...
https://stackoverflow.com/questions/53156298/
How do you convert a .onnx to tflite?
I've exported my model to ONNX via: # Export the model torch_out = torch.onnx._export(learn.model, # model being run x, # model input (or a tuple for multiple inputs) EXPORT_PATH + "mnist.onnx", # where to save the model (can be a f...
I think the ONNX file i.e. model.onnx that you have given is corrupted I don't know what is the issue but it is not doing any inference on ONNX runtime. Now you can run PyTorch Models directly on mobile phones. check out PyTorch Mobile's documentation here This answer is for TensorFlow version 1, For TensorFlow vers...
https://stackoverflow.com/questions/53182177/
Making custom non-trivial loss function in pytorch
I'm just started with pytorch and trying to understand how to deal with custom loss functions, especially with some non trivial ones. Problem 1. I'd like to stimulate my nn to maximize true positive rate and at the same time minimize false discovery rate. For example increase total score on +2 for true positive, and ...
@Shai already summed it up: Your loss function is not differentiable. One way to think about it is that your loss function should be plottable, and the "downhill" slope should "roll" toward the desired model output. In order to plot your loss function, fix y_true=1 then plot [loss(y_pred) for y_pred in np.linspace(0,...
https://stackoverflow.com/questions/53215816/
CUDNN_STATUS_MAPPING_ERROR when training with pose2body
I'm trying to train https://github.com/NVIDIA/vid2vid. I'm... ...executing with pretty much the vanilla parametrization shown in the readme, I had to change the number of GPUs though and increased the number of threads for reading the dataset. Command: python train.py \ --name pose2body_256p \ --dataroot datasets/p...
In case anybody deals the same issue: Training on P100 cards worked. Seems like the V100 architecture clashes with version of pytorch used in the supplied Dockerfile at some point. Not quite a solution, but a workaround.
https://stackoverflow.com/questions/53222648/
Trouble using openCV to load a net from ONNX (python/pytorch)
I'm trying to load a trained .onnx model (from a neural-style-transfer algorithm) into cv2. I've seen that there is a cv.dnn.readNetFromONNX() function, but there is no such function in cv2. I can't seem to import or load opencv as cv, and as such can't seem to load my model in cv2. Does anyone know a solution? I...
Update your opencv to a newer version. It should help. pip install opencv-python==4.1.0.25
https://stackoverflow.com/questions/53224685/
What does flatten_parameters() do?
I saw many Pytorch examples using flatten_parameters in the forward function of the RNN self.rnn.flatten_parameters() I saw this RNNBase and it is written that it Resets parameter data pointer so that they can use faster code paths What does that mean?
It may not be a full answer to your question. But, if you give a look at the flatten_parameters's source code , you will notice that it calls _cudnn_rnn_flatten_weight in ... NoGradGuard no_grad; torch::_cudnn_rnn_flatten_weight(...) ... is the function that does the job. You will find that what it actually does is...
https://stackoverflow.com/questions/53231571/
Error in Google Colaboratory - AttributeError: module 'PIL.Image' has no attribute 'register_decoder'
I am running this code on Google Colaboratory and I am getting error of register decoder image_data = dset.ImageFolder(root="drive/SemanticDataset/train/", transform = transforms.Compose([ transforms.Scale(size=img_size), transforms.Center...
First, check the version of pillow you have by using: import PIL print(PIL.PILLOW_VERSION) and make sure you have the newest version, the one I am using right now is 5.3.0 If you have like 4.0.0, install a new version by using: !pip install Pillow==5.3.0 in the Colab environment. Second, restart your Google colab e...
https://stackoverflow.com/questions/53237161/
Pytorch Chatbot Tutorial problem: How can I solve List Index Out of Range
I’m new to pytorch and have been following the many tutorials available. But, When I did The CHATBOT TUTORIAL is not work. Like the figure below What should I do and what is causing this?
A little late, but I hit this same error at this line before on this same tutorial. I am also running on 3.6 on Windows, had no issues loading PyTorch or running anything with CUDA. The issue for me was in the data. It was because there was a blank line somewhere in the source data, so when it went to split the word...
https://stackoverflow.com/questions/53247475/
Python - importing fastai results in SyntaxError
I am trying to setup an ML model using fastai and have to do the following imports: import fastai.models import fastai.nlp import fastai.dataset However, it gives me the following error by the fastai imports. Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credi...
Strings in the shape of: f'{path}/*.*' are called f-strings and were introduced in Python3.6. That's why you get the SyntaxError - for versions lower than Python3.6 a SyntaxError will be raised, as this syntax just doesn't exist in lower versions. So obviously fast-ai is programmed for Python3.6 or higher. When y...
https://stackoverflow.com/questions/53258219/
pytorch RuntimeError: CUDA error: device-side assert triggered
I've a notebook on google colab that fails with following error --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/fastai/basic_train.py in fit(epochs, model, loss_func, opt, dat...
Be sure that your targets values starts from zero to number of classes - 1. Ex: you have 100 classification class so your target should be from 0 to 99
https://stackoverflow.com/questions/53268442/
When using Pytorch-GPU in Anaconda, is it not necessary to install CUDA?
I found that after installing Pytorch 0.4 GPU version in Anaconda, you don't need to install CUDA locally to call gpu acceleration. When running code, the GPU core can be used at more than 90%. Edit:I used it in Windows 10. Don't know if it works in Linux.
@talonmies Thanks for your url. It seems that pytorch don't need cuda in Windows, since its dependencies are cffi, mkl, numpy, and python. I entered this command conda search -c pytorch pytorch=0.4.0 --info in Anaconda Prompt and it says Loading channels: done pytorch 0.4.0 py35_cuda80_cudnn7he774522_1 -------------...
https://stackoverflow.com/questions/53292107/
Pytorch Exception in Thread: ValueError: signal number 32 out of range
I'm getting this error: Exception in Thread: ValueError: signal number 32 out of range The specific tutorial that raises an issue for me is the training a classifier (https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html), the specific line is: dataiter = iter(trainloader) and the full error traceb...
I have faced a similar issue and it got resolved when I set: num_workers=0
https://stackoverflow.com/questions/53300965/
Pytorch speed comparison - GPU slower than CPU
I was trying to find out if GPU tensor operations are actually faster than CPU ones. So, I wrote this particular code below to implement a simple 2D addition of CPU tensors and GPU cuda tensors successively to see the speed difference: import torch import time ###CPU start_time = time.time() a = torch.ones(4,4) for _...
GPU acceleration works by heavy parallelization of computation. On a GPU you have a huge amount of cores, each of them is not very powerful, but the huge amount of cores here matters. Frameworks like PyTorch do their to make it possible to compute as much as possible in parallel. In general matrix operations are very ...
https://stackoverflow.com/questions/53325418/
pytorch delete model from gpu
I want to make a cross validation in my project based on Pytorch. And I didn't find any method that pytorch provided to delete the current model and empty the memory of GPU. Could you tell that how can I do it?
Freeing memory in PyTorch works as it does with the normal Python garbage collector. This means once all references to an Python-Object are gone it will be deleted. You can delete references by using the del operator: del model You have to make sure though that there is no reference to the respective object left, o...
https://stackoverflow.com/questions/53350905/
Issues loading from Drive with pytorch' datasets.DatasetFolder
The loading works great using jupyter and local files, but when I adapted to Colab, fetching data from a Drive folder, datasets.DatasetFolder always loads 9500 odd datapoints, never the full 10 000. Anyone had similar issues? train_data = datasets.DatasetFolder('/content/drive/My Drive/4 - kaggle/data', np.load, list(...
Loading lots of files from a single folder in Drive is likely to be slow and error-prone. You'll probably end up much happier if you either stage the data on GCS or upload an archive (.zip or .tar.gz) to Drive and copy that one file to your colab VM, unarchive it there, and then run your code over the local data.
https://stackoverflow.com/questions/53363663/
Theoretical underpinning behind Hardmax operator
In the tensor flow Github repository, in the file attentionwrapper.py, hardmax operator has been defined. On the docs, it has been mentioned tf.contrib.seq2seq.hardmax I want to know what's the theoretical underpinning behind providing this functionality for hardmax operator. Prima facie google searches for past few w...
Hardmax is used when you have no choice but to make a decision nonprobabalistically. For example, when you are using a model to generate a neural architecture as in neural module networks, you have to make a discrete choice. To make this trainable (since this would be non-differentiable as you state), you can use REINF...
https://stackoverflow.com/questions/53367724/
PyTorch element-wise product of vectors / matrices / tensors
In PyTorch, how do I get the element-wise product of two vectors / matrices / tensors? For googlers, this is product is also known as: Hadamard product Schur product Entrywise product
Given two tensors A and B you can use either: A * B torch.mul(A, B) A.mul(B) Note: for matrix multiplication, you want to use A @ B which is equivalent to torch.matmul().
https://stackoverflow.com/questions/53369667/
PyTorch mapping operators to functions
What are all the PyTorch operators, and what are their function equivalents? Eg, is a @ b equivalent to a.mm(b) or a.matmul(b)? I'm after a canonical listing of operator -> function mappings. I'd be happy to be given a PyTorch documentation link as an answer - my googlefu couldn't track it down.
The Python documentation table Mapping Operators to Functions provides canonical mappings from: operator -> __function__() Eg: Matrix Multiplication a @ b matmul(a, b) Elsewhere on the page, you will see the __matmul__ name as an alternate to matmul. The definitions of the PyTorch __functions__ ar...
https://stackoverflow.com/questions/53370003/
Get the data type of a PyTorch tensor
I understand that PyTorch tensors are homogenous, ie, each of the elements are of the same type. How do I find out the type of the elements in a PyTorch tensor?
There are three kinds of things: dtype || CPU tensor || GPU tensor torch.float32 torch.FloatTensor torch.cuda.FloatTensor The first one you get with print(t.dtype) if t is your tensor, else you use t.type() for the other two.
https://stackoverflow.com/questions/53374499/
Check if PyTorch tensors are equal within epsilon
How do I check if two PyTorch tensors are semantically equal? Given floating point errors, I want to know if the the elements differ only by a small epsilon value.
At the time of writing, this is a undocumented function in the latest stable release (0.4.1), but the documentation is in the master (unstable) branch. torch.allclose() will return a boolean indicating whether all element-wise differences are equal allowing for a margin of error. Additionally, there's the undocumente...
https://stackoverflow.com/questions/53374928/
How does pytorch's parallel method and distributed method work?
I'm not an expert in distributed system and CUDA. But there is one really interesting feature that PyTorch support which is nn.DataParallel and nn.DistributedDataParallel. How are they actually implemented? How do they separate common embeddings and synchronize data? Here is a basic example of DataParallel. import torc...
That's a great question. PyTorch DataParallel paradigm is actually quite simple and the implementation is open-sourced here . Note that his paradigm is not recommended today as it bottlenecks at the master GPU and not efficient in data transfer. This container parallelizes the application of the given :attr:module by ...
https://stackoverflow.com/questions/53375422/
load test data in pytorch
All is in the title, I just want to know, how can I load my own test data (image.jpg) in pytorch in order to test my CNN.
You need to feed images to net the same as in training: that is, you should apply exactly the same transformations to get similar results. Assuming your net was trained using this code (or similar), you can see that an input image (for validation) undergoes the following transformations: transforms.Compose([ ...
https://stackoverflow.com/questions/53379887/
Wasserstein GAN critic training ambiguity
I'm running a DCGAN-based GAN, and am experimenting with WGANs, but am a bit confused about how to train the WGAN. In the official Wasserstein GAN PyTorch implementation, the discriminator/critic is said to be trained Diters (usually 5) times per each generator training. Does this mean that the critic/discriminator t...
The correct is to consider an iteration as a batch. In the original paper, for each iteration of the critic/discriminator they are sampling a batch of size m of the real data and a batch of size m of prior samples p(z) to work it. After the critic is trained over Diters iterations, they train the generator which also...
https://stackoverflow.com/questions/53401431/
Apply transformation for Tensor without including it in Backward
Let's say I have n layered neural network. After running l layers, I want to apply some transformation to the l^th layer output, without including that transformation in backpropagation. For e.g. : output_layer_n = self.LinearLayer(output_layer_prev) #apply some transformation to output_layer_n, but don't want to t...
If you just don't want to compute gradients for your TransformationFunction, it is easiest to turn off gradient computation for all parameters involved in this computation by setting the requires_grad flag to False. Excluding subgraphs from backward: If there’s a single input to an operation that requires gradien...
https://stackoverflow.com/questions/53424056/
How can I change the padded input size per channel in Pytorch?
I am trying to set up an image classifier using Pytorch. My sample images have 4 channels and are 28x28 pixels in size. I am trying to use the built-in torchvision.models.inception_v3() as my model. Whenever I try to run my code, I get this error: RuntimeError: Calculated padded input size per channel: (1 x 1). ...
It could be due the following. Pytorch documentation for Inception_v3 model notes that the model expects input of shape Nx3x299x299. This is because the architecture contains a fully connected layer which fixed shape. Important: In contrast to the other models the inception_v3 expects tensors with a size of N x 3 ...
https://stackoverflow.com/questions/53438146/
How to handle Multi Label DataSet from Directory for image captioning in PyTorch
I need a help in PyTorch, Regarding Dataloader, and dataset Can someone aid/guide me Here is my query : I am trying for Image Captioning using https://github.com/yunjey/pytorch-tutorial/tree/master/tutorials/03-advanced/image_captioning. Here they have used Standard COCO Dataset. I have dataset as images/ and ca...
First, using str() to convert the list of captions into a single string (caption_str = str(caption_all_for_a_image)) is a bad idea: cap = ['a sentence', 'bla bla bla'] str(cap) Returns this sting: "['a sentence', 'bla bla bla']" Note that [', and ', ' are part of the resulting string! You can pick one of the ...
https://stackoverflow.com/questions/53442510/
Convert PyTorch CUDA tensor to NumPy array
How do I convert a torch.Tensor (on GPU) to a numpy.ndarray (on CPU)?
Use .detach() to convert from GPU / CUDA Tensor to numpy array: tensor.detach().cpu().numpy()
https://stackoverflow.com/questions/53467215/
one of the variables needed for gradient computation has been modified by an inplace operation
Here is my LossFunction, when I use this function, it will make this error. And I have tested that using the nn.L1Loss() instead of my LossFunction, and the network is ok. what should I do? Thanks for your help! class LossV1(nn.Module): def __init__(self,weight=1,pos_weight=1,scale_factor=2.5): super(LossV...
I just remove the objmask,and compute it in my generation function,then pass it on to LossFunction with truth label,and the network works. I can't understand I have already done that making the requires_grad=False,why pytroch still compute the gradient.
https://stackoverflow.com/questions/53467460/
Anoconda does not allow Torchvision to be installed
I tried the following commands conda create -n torch_env -c pytorch pytorch torchvision conda install -c soumith/label/pytorch torchvision conda install -c soumith torchvision Provided by Anaconda but none of them works. Please help me I am stack ! Error message: Solving environment: failed PackagesNotFoundError: T...
I encountered the same problem. https://github.com/pytorch/pytorch/issues/12210 Then I found that torchvision should be installed together with pytorch in anaconda. conda install -c pytorch torchvision
https://stackoverflow.com/questions/53471393/
PyTorch: get input layer size
I want to programatically find the size of my input layer. If my first layer is called fc1, how do I find out its input?
Assuming your model is called model, this will give the number of input features of the fc1 layer: model.fc1.in_features This is useful inside the .forward() method: def forward(self, x): x = x.view(-1, self.fc1.in_features) # resize the input to match the input layer ...
https://stackoverflow.com/questions/53475580/
Increasingly large, positive WGAN-GP loss
I'm investigating the use of a Wasserstein GAN with gradient penalty in PyTorch, but consistently get large, positive generator losses that increase over epochs. I'm heavily borrowing from Caogang's implementation, but am using the discriminator and generator losses used in this implementation because I get Invalid gra...
Batch Normalization in the discriminator breaks Wasserstein GANs with gradient penalty. The authors themselves advocate the usage of layer normalization instead, but this is clearly written in bold in their paper (https://papers.nips.cc/paper/7159-improved-training-of-wasserstein-gans.pdf). It is hard to say if there a...
https://stackoverflow.com/questions/53479523/
Pytorch RuntimeError: CUDA error: out of memory at loss.backward() , No error when using CPU
I'm training a Fully convolutional network (FCN32) for semantic segmentation on Tesla K80 with more than 11G memory. The input image is pretty large: 352x1216. Network structure is shown below. I used batch_size=1, but still encounter the out_of_memory error. Criterion is nn.BCEWithLogitsLoss() The network works f...
Usually this happens because of memory on your GPU. If you have more powerful GPUs, your problem could be solved (as you mentioned in your answer). But if you do not have, you can scale down your images into about 256*x sizes. It is also good practice for performance's sake.
https://stackoverflow.com/questions/53494498/
Gradient is none in pytorch when it shouldn't
I am trying to get/trace the gradient of a variable using pytorch, where I have that variable, pass it to a first function that looks for some minimum value of some other variable, then the output of the first function is inputted to a second function, and the whole thing repeats multiple times. Here is my code: imp...
I have a similar experience with this. Reference: https://pytorch.org/docs/stable/tensors.html For Tensors that have requires_grad which is True, they will be leaf Tensors if they were created by the user. This means that they are not the result of an operation and so grad_fn is None. Only leaf Tensors will have thei...
https://stackoverflow.com/questions/53507346/
Concatenate Two Tensors in Pytorch
How do I pad a tensor of shape [71 32 1] with zero vectors to make it [100 32 1]? RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 2. Got 32 and 71 in dimension 0 at /pytorch/aten/src/THC/generic/THCTensorMath.cu:87 I tried by concatenating a padding vector of zeros of shape [29 32 1]...
In order to help you better, you need to post the code that caused the error, without it we are just guessing here... Guessing from the error message you got: 1. Sizes of tensors must match except in dimension 2 pytorch tries to concat along the 2nd dimension, whereas you try to concat along the first. 2. Got 32 an...
https://stackoverflow.com/questions/53512281/
RuntimeError: reduce failed to synchronize: device-side assert triggered
File "/home/username/anaconda3/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 433, in forward reduce=self.reduce) File "/home/username/anaconda3/lib/python3.6/site-packages/torch/nn/functional.py", line 1483, in binary_cross_entropy return torch._C._nn.binary_cross_entropy(input, target, weight...
When using cuda you may get this generic error which is not very helpful. Try switching to cpu device instead, device = torch.device("cpu"), to see the actual error stack trace. In my case, the issue was caused because binary cross entropy expected the input values to be between 0~1, but I was sending in values betwee...
https://stackoverflow.com/questions/53530810/
Is there any way to copy all parameters of one Pytorch model to another specially Batch Normalization mean and std?
I have found many correct ways online to copy one pytorch model parameters to another but somehow the copy-paste operation always misses the batch normalization parameters. Everything works fine as long as I only use modules such as conv2d, linear, drop out, max pool etc in my model. But as soon as I add Batch normali...
net.load_state_dict(copy_net.state_dict()) should work. As per @dxtx, in pytorch's philosophy, the state dict should cover all the states in a 'module', e.g. in batch norm module , the running mean and var, if I remembered correctly, should be part of the state dict. But in fact, if you wrote module like batch norm y...
https://stackoverflow.com/questions/53568501/
Should I run a separate thread to save the model in Pytorch
Consider the following snippet from PyTorch Imagenet Example (Please notice the "#AREA OF INTEREST"): try: for epoch in range(1, args.epochs+1): epoch_start_time = time.time() train() val_loss = evaluate(val_data) # Save the model if the validation loss is the best we've seen so far. if not best_va...
It depends on your model size. If you have slow IO and big model it may take time. But usual FS cache is big enough to store a whole model.
https://stackoverflow.com/questions/53569555/
Documentation for PyTorch .to('cpu') or .to('cuda')
I've searched through the PyTorch documenation, but can't find anything for .to() which moves a tensor to CPU or CUDA memory. I remember seeing somewhere that calling to() on a nn.Module is an in-place operation, but not so on a tensor. Is there a in-place version for Tensors? Where do I find the doco for to() for b...
You already found the documentation! great. .to is not an in-place operation for tensors. However, if no movement is required it returns the same tensor. In [10]: a = torch.rand(10) In [11]: b = a.to(torch.device("cuda")) In [12]: b is a Out[12]: False In [18]: c = b.to(torch.device("cuda")) In [19]: c is b Out[1...
https://stackoverflow.com/questions/53570334/
Calculate the output size in convolution layer
How do I calculate the output size in a convolution layer? For example, I have a 2D convolution layer that takes a 3x128x128 input and has 40 filters of size 5x5.
you can use this formula [(W−K+2P)/S]+1. W is the input volume - in your case 128 K is the Kernel size - in your case 5 P is the padding - in your case 0 i believe S is the stride - which you have not provided. So, we input into the formula: Output_Shape = (128-5+0)/1+1 Output_Shape = (124,124,40) NOTE: Strid...
https://stackoverflow.com/questions/53580088/
How does pytorch calculate matrix pairwise distance? Why isn't 'self' distance not zero?
If this is a naive question, please forgive me, my test code like this: import torch from torch.nn.modules.distance import PairwiseDistance list_1 = [[1., 1.,],[1., 1.]] list_2 = [[1., 1.,],[2., 1.]] mtrxA=torch.tensor(list_1) mtrxB=torch.tensor(list_2) print "A-B distance :",PairwiseDistance(2).forward(mtrxA, ...
Looking at the documentation of nn.PairWiseDistance, pytorch expects two 2D tensors of N vectors in D dimensions, and computes the distances between the N pairs. Why "self" distance is not zero - probably because of floating point precision and because of eps = 1e-6.
https://stackoverflow.com/questions/53607710/
Loss Function & Its Inputs For Binary Classification PyTorch
I'm trying to write a neural Network for binary classification in PyTorch and I'm confused about the loss function. I see that BCELoss is a common function specifically geared for binary classification. I also see that an output layer of N outputs for N possible classes is standard for general classification. However,...
For binary outputs you can use 1 output unit, so then: self.outputs = nn.Linear(NETWORK_WIDTH, 1) Then you use sigmoid activation to map the values of your output unit to a range between 0 and 1 (of course you need to arrange your training data this way too): def forward(self, x): # other layers omitted x = se...
https://stackoverflow.com/questions/53628622/
Pytorch Adam optimizer's awkward behavior? better with restart?
I'm trying to train a CNN text classifier with Pytorch. I'm using the Adam optimizer like this. optimizer = torch.optim.Adam(CNN_Text.parameters(), lr=args.lr) I figured out that the optimizer converges really fast, and then it keeps on slowly dropping on accuracy. (the validation loss decreases a lot in 1-2 minutes,...
What is param_group? With that code snippet it looks like a variable not associated with the optimizer in any way. What you need to modify is the 'lr' entry of each element of optimizer.param_groups, which is what ADAM actually looks at. Either way, unless you have a good reason to hand-roll it yourself, I suggest you...
https://stackoverflow.com/questions/53644632/
How to create Datasets Like MNIST in Pytorch?
I have looked Pytorch source code of MNIST dataset but it seems to read numpy array directly from binaries. How can I just create train_data and train_labels like it? I have already prepared images and txt with labels. I have learned how to read image and label and write get_item and len, what really confused me is ho...
There are two ways to go. First, the manual. Torchvision.datasets states the following: datasets are subclasses of torch.utils.data.Dataset i.e, they have __getitem__ and __len__ methods implemented. Hence, they can all be passed to a torch.utils.data.DataLoader which can load multiple samples parallelly using torc...
https://stackoverflow.com/questions/53665225/
Load pytorch model from 0.4.1 to 0.4.0?
I trained a DENSENET161 model using pytorch 0.4.1 (GPU) and on testing environment I have to load it in pytorch version 0.4.0 (CPU). I am already using model.cpu() but when I am loading static dictionary model.load_state_dict(checkpoint['state_dict']) I am getting following error: RuntimeError: Error(s) in loading...
It seems to stem from the difference in implementation of normalization layers between PyTorch 0.4.1 and 0.4 - the former tracks some state variable called num_batches_tracked, which pytorch 0.4 does not expect. Assuming there are only unexpected keys and no missing keys (which I can't tell for sure since you've clippe...
https://stackoverflow.com/questions/53678133/
Pytorch parameter matrix from loss function of transformation
I have a pytorch tensor k x (n+k-1) tensor w with requires_grad=True. I want to transform it into a kxn tensor p also with as such: p[i] = w[i][i:i+n]. How do I do this, such that by calling backward() on a loss function of p in the end, I will learn w?
Any sort of indexing operation would do, with the backward function being <CopySlices> A naive way of doing this would be using simple python indexing: w_unrolled = torch.zeros(p.size()) for i in range(w.shape[0]): w_unrolled[i] = w[i][i:i+n] loss = criterion(w_unrolled, p) You can then reduce your loss vi...
https://stackoverflow.com/questions/53683076/
Pytorch, efficient way extend a tensor by its first and last element
I have a tensor in pytorch. I want to extend it on a specific dimension from the beginning and the end by k positions with the first and last elements of that dimension respectively. Say I have the tensor with data [[0, 0, 0], [1, 1, 1], [2, 2, 2]]. Operation extend(dim, k) would change it in this way: extend(0, 1):...
You are looking for torch.nn.functional.pad, with mode='replicate'. However, there are two things you need to pa attention to to get this to work: 1. pad does not work with 2D tensors. Thus, you need to add leading singleton dimensions before pad and squeezeing them afterwards. 2. The order of pad values pad expects is...
https://stackoverflow.com/questions/53688217/
OpenAI gym 0.10.9 'module' object has no attribute 'benchmark_spec'
benchmark = gym.benchmark_spec('Atari40M') AttributeError: 'module' object has no attribute 'benchmark_spec' I just got this error for gym-0.10.9. Any idea? Thx
According to this post on GitHub, the function 'benchmark_spec' is no longer supported.
https://stackoverflow.com/questions/53689624/
Pytorch: Learnable threshold for clipping activations
What is the proper way to clip ReLU activations with a learnable threshold? Here's how I implemented it, however I'm not sure if this is correct: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.act_max = nn.Parameter(torch.Tensor([0]), requires_grad=True) self.c...
There are two problems with that code. The implementation-level one is that you're using an in-place operation which generally doesn't work well with autograd. Instead of relu1[relu1 > self.act_max] = self.act_max you should use an out-of-place operation like relu1 = torch.where(relu1 > self.act_max, self.a...
https://stackoverflow.com/questions/53698950/
pytorch batch normalization in distributed train
wondering how distributed pytorch handle batch norm, when I add a batch norm layer, will pytorch engine use the same allreduce call to sync the data cross node? or the batch norm only happen on local node.
Similarly to DataParallel (check the first Warning box). It will compute the norm separately for each node (or, more precisely, each GPU). It will not sync the rolling estimates of the norm either, but it will keep the values from one of the GPUs in the end. So assuming the examples are distributed across your cluster ...
https://stackoverflow.com/questions/53709406/
vgg pytorch is probability distribution supposed to add up to 1?
I've trained a vgg16 model to predict 102 classes of flowers. It works however now that I'm trying to understand one of it's predictions I feel it's not acting normally. model layout # Imports here import os import numpy as np import torch import torchvision from torchvision import datasets, models, transforms impor...
I cannot tell with certainty without seeing your training code, but it's most likely your model was trained with cross-entropy loss and as such it outputs logits rather than class probabilities. You can turn them into proper probabilities by applying the softmax function.
https://stackoverflow.com/questions/53711470/
Dice Loss and samples containing no data in target tensors?
I have a highly imbalanced 3D dataset, where about 80% of the volume is background data, I am only interested in the foreground elements which constitute about 20% of the total volume at random locations. These locations are noted in the label tensor given to the network. The target tensor is binary where 0 represents ...
You will get return of 1 if your algorithm predicts that all background voxels should have a value of exactly 0, but if it predicts any positive value (which it will surely do if you're using sigmoid activation) it can still improve the loss by outputting as little as possible. In other words, the numerator cannot go a...
https://stackoverflow.com/questions/53711976/
Best way to handle OOV words when using pretrained embeddings in PyTorch
I am using word2vec pretrained embedding in PyTorch (following code here). However, it does not seem to handle unseen words. Is there any good way to solve it?
FastText builds character ngram vectors as part of model training. When it finds an OOV word, it sums the character ngram vectors in the word to produce a vector for the word. You can find more detail here.
https://stackoverflow.com/questions/53715016/
Pytorch modify dataset label
This is a code snippet for loading images as dataset from pytorch transfer learning tutorial: data_transforms = { 'train': transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0...
Yes, though not (easily) programmatically. The labels are coming from torchvision.datasets.ImageFolder and reflect the directory structure of your dataset (as seen on your HDD). Firstly, I suspect you may want to know the directory name as a string. This is poorly documented but the dataloader has a classes attribute w...
https://stackoverflow.com/questions/53751882/
Trouble using transforms.FiveCrop()/TenCrop() in PyTorch
I am trying to increase my CNN’s performance and thus i decided to “play” with some transformations in order to see how they affect my model. I read that FiveCrop() and TenCrop() might help because they generate extra data to train on. However, when i try to train the model, using one of the transformations mentioned a...
Right, your error is coming from transforms.ToTensor(), which is directly downstream of your TenCrop in the composed transformation. It expects an image but gets a tuple of crops instead. You should follow a procedure similar to the one shown in the documentation not only for testing but also for training in order to r...
https://stackoverflow.com/questions/53763758/
How to change a Pytorch CNN to take color images instead of black and white?
This code I found has a neural net that is setup to take black and white images. (It's a siamese network but that part's not relevant). When I change it to take my images and NOT convert them to black and white I get an error shown below. I tried changing the first Conv2d, the sixth line down from a 1 to a 3 class Sia...
The error seems to be in fully connected part below: self.fc1 = nn.Sequential( nn.Linear(8*100*100, 500), nn.ReLU(inplace=True), nn.Linear(500, 500), nn.ReLU(inplace=True), nn.Linear(500, 5)) It seems the output of cnn is of shape[8,300,300] and not [8,100,100] To solve thi...
https://stackoverflow.com/questions/53769948/
How to predict a label in MultiClass classification model in pytorch?
I am currently working on my mini-project, where I predict movie genres based on their posters. So in the dataset that I have, each movie can have from 1 to 3 genres, therefore each instance can belong to multiple classes. I have total of 15 classes(15 genres). So now I am facing with the problem of how to do predicti...
You're right, you're looking to perform binary classification (is poster X a drama movie or not? Is it an action movie or not?) for each poster-genre pair. BinaryCrossEntropy(WithLogits) is the way to go. Regarding the best metric to evaluate your resulting algorithm, it's up to you, what are you looking for. But you ...
https://stackoverflow.com/questions/53788828/
computing gradients for every individual sample in a batch in PyTorch
I'm trying to implement a version of differentially private stochastic gradient descent (e.g., this), which goes as follows: Compute the gradient with respect to each point in the batch of size L, then clip each of the L gradients separately, then average them together, and then finally perform a (noisy) gradient desc...
I don't think you can do much better than the second method in terms of computational efficiency, you're losing the benefits of batching in your backward and that's a fact. Regarding the order of clipping, autograd stores the gradients in .grad of parameter tensors. A crude solution would be to add a dictionary like c...
https://stackoverflow.com/questions/53798023/
RuntimeError: size mismatch m1: [a x b], m2: [c x d]
Can anyone help me in this.? I am getting below error. I use Google Colab. How to Solve this error.? size mismatch, m1: [64 x 100], m2: [784 x 128] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:2070 Below Code I am trying to Run. import torch from torch import nn import torch.nn.functional as F ...
All you have to care is b=c and you are done: m1: [a x b], m2: [c x d] m1 is [a x b] which is [batch size x in features] m2 is [c x d] which is [in features x out features]
https://stackoverflow.com/questions/53828518/
How does adaptive pooling in pytorch work?
Adaptive pooling is a great function, but how does it work? It seems to be inserting pads or shrinking/expanding kernel sizes in what seems like a pattered but fairly arbitrary way. The pytorch documentation I can find is not more descriptive than "put desired output size here." Does anyone know how this works or ca...
In general, pooling reduces dimensions. If you want to increase dimensions, you might want to look at interpolation. Anyway, let's talk about adaptive pooling in general. You can look at the source code here. Some claimed that adaptive pooling is the same as standard pooling with stride and kernel size calculated from...
https://stackoverflow.com/questions/53841509/
Pytorch Convolutional Autoencoders
How one construct decoder part of convolutional autoencoder? Suppose I have this (input -> conv2d -> maxpool2d -> maxunpool2d -> convTranspose2d -> output): # CIFAR images shape = 3 x 32 x 32 class ConvDAE(nn.Module): def __init__(self): super().__init__() # input: batch x 3 x 32...
For the torch part of the question, unpool modules have as a required positional argument the indices returned from the pooling modules which will be returned with return_indices=True. So you could do class ConvDAE(nn.Module): def __init__(self): super().__init__() # input: batch x 3 x 32 x 32 -&g...
https://stackoverflow.com/questions/53858626/
How to get all the tensors in a graph?
I would like to access all the tensors instances of a graph. For example, I can check if a tensor is detached or I can check the size. It can be done in tensorflow. I don't want visualization of the graph.
You can get access to the entirety of the computation graph at runtime. To do so, you can use hooks. These are functions plugged onto nn.Modules both for inference and when backpropagating. At inference, you can hook a callback function with register_forward_hook. Similarly for backpropagation, you can use register_ful...
https://stackoverflow.com/questions/53878476/
PyTorch transfer learning with pre-trained ImageNet model
I want to create an image classifier using transfer learning on a model already trained on ImageNet. How do I replace the final layer of a torchvision.models ImageNet classifier with my own custom classifier?
Get a pre-trained ImageNet model (resnet152 has the best accuracy): from torchvision import models # https://pytorch.org/docs/stable/torchvision/models.html model = models.resnet152(pretrained=True) Print out its structure so we can compare to the final state: print(model) Remove the last module (generally a sing...
https://stackoverflow.com/questions/53884692/
TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
I am using a modified predict.py for testing a pruned SqueezeNet Model [phung@archlinux SqueezeNet-Pruning]$ python predict.py --image 3_100.jpg --model model_prunned --num_class 2 prediction in progress Traceback (most recent call last): File “predict.py”, line 66, in prediction = predict_image(imagepath) File “predic...
Change index = output.data.numpy().argmax() to index = output.cpu().data.numpy().argmax() This means data is first moved to cpu and then converted to numpy array.
https://stackoverflow.com/questions/53900910/
How to transfer weight of own model to same network but different number of classin last layer?
I have my own network in Pytorch. It first trained for the binary classifier (2 classes). After 10k epochs, I obtained the trained weight as 10000_model.pth. Now, I want to use the model for 4 classes classifier problem using the same network. Thus, I want to transfer all trained weights in the binary classifier to 4 c...
Both networks have the same layers and therefore the same keys in state_dict, so indeed pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} does nothing. The difference between the two is the weight tensors (their shape) and not their names. In other words, you can distinguish the two by ...
https://stackoverflow.com/questions/53901603/
In tensorflow, how to enumerate training data (compared to pytorch)
In pytorch, this is how I enumerate training data. for epoch in range(0, args.epoches): for i, batch in enumerate(train_data): model.update(batch) train_data contains multiple batches and batches are getting enumerated and updating the model, which is very clear to me. I think this is a basic example ...
TensorFlow has a History object for this purpose. You get History object as a return from the model.fit() method. A History object and its History.history attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if app...
https://stackoverflow.com/questions/53906008/
Problem with missing and unexpected keys while loading my model in Pytorch
I'm trying to load the model using this tutorial: https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference . Unfortunately I'm very beginner and I face some problems. I have created checkpoint: checkpoint = {'epoch': epochs, 'model_state_dict': model.state_dict(), 'optimiz...
So your Network is essentially the classifier part of AlexNet and you're looking to load pretrained AlexNet weights into it. The problem is that the keys in state_dict are "fully qualified", which means that if you look at your network as a tree of nested modules, a key is just a list of modules in each branch, joined ...
https://stackoverflow.com/questions/53907073/
Truncated Backpropagation Through Time (BPTT) in Pytorch
In pytorch, I train a RNN/GRU/LSTM network by starting the Backpropagation (Through Time) with : loss.backward() When the sequence is long, I'd like to do a Truncated Backpropagation Through Time instead of a normal Backpropagation Through Time where the whole sequence is used. But I can't find in the Pytorch API a...
Here is an example: for t in range(T): y = lstm(y) if T-t == k: out.detach() out.backward() So in this example, k is the parameter you use to control the timesteps you want to unroll.
https://stackoverflow.com/questions/53912956/
Pytorch inputs for nn.CrossEntropyLoss()
I am trying to perform a Logistic Regression in PyTorch on a simple 0,1 labelled dataset. The criterion or loss is defined as: criterion = nn.CrossEntropyLoss(). The model is: model = LogisticRegression(1,2) I have a data point which is a pair: dat = (-3.5, 0), the first element is the datapoint and the second is the ...
For the most part, the PyTorch documentation does an amazing job to explain the different functions; they usually do include expected input dimensions, as well as some simple examples. You can find the description for nn.CrossEntropyLoss() here. To walk through your specific example, let us start by looking at the exp...
https://stackoverflow.com/questions/53936136/
TypeError: add(): argument 'other' (position 1) must be Tensor, not numpy.ndarray
I am testing a ResNet-34 trained_model using Pytorch and fastai on a linux system with the latest anaconda3. To run it as a batch job, I commented out the gui related lines. It started to run for a few hrs, then stopped in the Validation step, the error message is as below. ... ^M100%|█████████▉| 452/453 [1:07:07<...
Ok, the error seems be for the latest pytorch-1.0.0, when degrade pytorch to pytorch-0.4.1, the code seems work (passed the error lines at this point). Still have no idea to make the code work with pytorch-1.0.0
https://stackoverflow.com/questions/53938977/
How to install CUDA in Google Colab - Cannot initialize CUDA without ATen_cuda library
I am trying to use cuda in Goolge Colab but while running my program I get the following error. RuntimeError: Cannot initialize CUDA without ATen_cuda library. PyTorch splits its backend into two shared libraries: a CPU library and a CUDA library; this error has occurred because you are trying to use some CUDA func...
Have you tried the following? Go to Menu > Runtime > Change runtime. Change hardware acceleration to GPU. How to install CUDA in Google Colab GPU's
https://stackoverflow.com/questions/53946404/
How to optimize the inference script to get a faster prediction of the classifier?
I have written the following prediction code that predicts from a trained classifier model. Now the prediction time is around 40s which I want to reduce as much as possible. Can I do any optimization to my inference script or should I look for developments in training script? import torch import torch.nn as nn from t...
Without output from your profiler it's difficult to tell how much of that is because of inefficiencies in your code. That being said, PyTorch has a lot of startup overhead - in other words it's slow to initialize the library, model, load weights and to transfer it to GPU, as compared to inference time on a single image...
https://stackoverflow.com/questions/53954653/
Use Pytorch SSIM loss function in my model
I am trying out this SSIM loss implement by this repo for image restoration. For the reference of original sample code on author's GitHub, I tried: model.train() for epo in range(epoch): for i, data in enumerate(trainloader, 0): inputs = data inputs = Variable(inputs) optimizer.zero_grad()...
The author is trying to maximize the SSIM value. The natural understanding of the pytorch loss function and optimizer working is to reduce the loss. But the SSIM value is quality measure and hence higher the better. Hence the author uses loss = - criterion(inputs, outputs) You can instead try using loss = 1 - criterio...
https://stackoverflow.com/questions/53956932/
About autograd in pyorch, Adding new user-defined layers, how should I make its parameters update?
everyone ! My demand is a optical-flow-generating problem. I have two raw images and a optical flow data as ground truth, now my algorithm is to generate optical flow using raw images, and the euclidean distance between generating optical flow and ground truth could be defined as a loss value, so it can implement a ba...
Tensor values have their gradients calculated if they Have requires_grad == True Are used to compute some value (usually loss) on which you call .backward(). The gradients will then be accumulated in their .grad parameter. You can manually use them in order to perform arbitrary computation (including optimization)....
https://stackoverflow.com/questions/53958898/
Windows 10,CUDA 9,: CUDA driver version is insufficient for CUDA runtime version at ..\src\THC\THCG
My env configuration: python:3.6 tensorflow-GPU 1.3 CUDA:9.0 VS:2013 torch:0.4.0 run CUDA 9.0 sample:success but when I run the pytorch code,I get the error info as follows: File "D:\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 249, in return self._apply(lambda t: t.cuda(device)) RuntimeError:...
It is telling you the GPU driver you have installed cannot cope with the CUDA version you are using. Either update your driver to the latest version or downgrade your CUDA runtime to a version supported by your GPU driver.
https://stackoverflow.com/questions/53959762/
Pytorch: How does SGD with momentum works when optimizer has to call zero_grad() to help accumulation of gradients?
In pytorch, the backward() function accumulates gradients and we have to reset it every mini-batch by calling optimizer.zero_grad(). In this case, how does the SGD with momentum works when actually momentum SGD updates the weights using exponential average of some past mini-batches. For a beginner in Pytorch, I am co...
When using momentum you need to store a one-element history for each parameter, other solvers (e.g. ADAM) requires even more. The optimizer knows how to store this history data and accumuate new gradients in an orderly fashion. You do not have to worry about it. So why zero_grad(), you probably ask yourself? well, som...
https://stackoverflow.com/questions/53981485/
How can I select single indices over a dimension in pytorch?
Assume I have a tensor sequences of shape [8, 12, 2]. Now I would like to make a selection of that tensor for each first dimension which results in a tensor of shape [8, 2]. The selection over dimension 1 is specified by indices stored in a long tensor indices of shape [8]. I tried this, however it selects each index ...
sequences[torch.arange(sequences.size(0)), indices]
https://stackoverflow.com/questions/53986301/
How does torch.empty calculate the values?
Every time I run torch.empty(5, 3) I get one of those two results: >>> torch.empty(5, 3) tensor([[ 0.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 0.0000], [ 0.0000, -0.0000, 0.0000], [ 0.0000, ...
torch.empty returns "a tensor filled with uninitialized data." If you want to have a tensor filled with zeros, use torch.zeros.
https://stackoverflow.com/questions/53987380/
Too many files open
import PIL as Image Image.fromarray(cv2.imread(link, cv2.IMREAD_GRAYSCALE)) I'm currently trying to complete a project but I'm constantly getting too many files open error on my linux GPU server which crashes the server. I'm loading 3 images for CNN classification using the code as shown above. Anyone facing the sam...
Try switching to the file strategy system by adding this to your script import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system')
https://stackoverflow.com/questions/54000317/
AssertionError: Torch not compiled with CUDA enabled
From https://pytorch.org/ to install pytorch on MacOS the following is stated : conda install pytorch torchvision -c pytorch # MacOS Binaries dont support CUDA, install from source if CUDA is needed Why would want to install pytorch without cuda enabled ? Reason I ask is I receive error : -------------------...
To summarize and expand on the comments: CUDA is an Nvidia proprietary (apparently unlicensed) technology to allow general computing on GPU processors. Very few Macbook Pro's have an Nvidia CUDA-capable GPU. Take a look here to see whether your MBP has an Nvidia GPU. Then, look at the table here to see if that GPU s...
https://stackoverflow.com/questions/54014220/
Pylint with pytorch: Is there a way to tell pylint to look for module in different place?
I am using pytorch and pylint does not recognize few functions for ex: torch.stack however, if I do import torch._C as torch it seems to work fine. If I do above, actual modules that exist inside torch package like torch.cuda or torch.nn need to imported individually as simply doing torch.cuda would point to torch._C...
A solution for now is to add torch to generated-members: pylint --generated-members="torch.*" ... or in pylintrc under the [TYPECHECK] section: generated-members=torch.* I found this solution in a reply to the github discussion of the pytorch issue [Minor Bug] Pylint E1101 Module 'torch' has no 'from_numpy' membe...
https://stackoverflow.com/questions/54030714/
Tensorflow finfo (numeric limits)
How do I access something like numpy.finfo (Or torch.finfo) in the tensorflow Python API? I want to look up things like the smallest increment or largest finite value of the given type (for example tf.float32). Some attributes are accessible directly; tf.float32.max >> -3.4028235e+38 tf.float32.min >> -3.4...
You can always check this via PyTorch. Should be the same as in TF. import torch print(torch.finfo(torch.float16).eps) #0.0009765625 print(torch.finfo(torch.float32).eps) #1.1920928955078125e-07 print(torch.finfo(torch.float64).eps) #2.220446049250313e-16 print(torch.finfo(torch.double).eps) #2.220446049250313e-16 ...
https://stackoverflow.com/questions/54047155/
Speed up datasets loading on Google Colab
I am working on Image classification on the German Traffic Sign Dataset on Google Colab with Pytorch. Here is the structure of the dataset: GTSRB Training 00000/ *.ppmm … 00043/ *.ppmm Test *.ppmm … labels.csv I have managed to upload the whole dataset to my drive(it took a long time!!!). I have use...
If your problem truly is the network speed between Colab and Drive, you should try uploading the files directly to the Google Colab instance, rather than accessing them from Drive. from google.colab import files dataset_file_dict = files.upload() Doing this will save the files directly to your Colab instance, allowi...
https://stackoverflow.com/questions/54049440/
Can't send pytorch tensor to cuda
I create a torch tensor and I want it to go to GPU but it doesn't. This is so broken. What's wrong? def test_model_works_on_gpu(): with torch.cuda.device(0) as cuda: some_random_d_model = 2 ** 9 five_sentences_of_twenty_words = torch.from_numpy(np.random.random((5, 20, T * d))).float() five_...
Your issue is the following lines: five_sentences_of_twenty_words.to(cuda) five_sentences_of_twenty_words_mask.to(cuda) .to(device) only operates in place when applied to a model. When applied to a tensor, it must be assigned: five_sentences_of_twenty_words = five_sentences_of_twenty_words.to(cuda) five_sentences_of_t...
https://stackoverflow.com/questions/54060499/
How do i add an layer to an Nural network in pytorch
i want to add a layer to a Nural network programicaly it returned this error TypeError: forward() missing 1 required positional argument: 'x' class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(1, 120) self.fc2 = nn.Linear(120, 84) self.fc3...
Ok so there are several things. Beginning with why are you calling netz(), you already instiantiated the object earlier with netz =Net(), so this make no sense. Second thing, nn.Sequential expects *args as "constructor" argument, so you directly pass subclasses of modules: netz = nn.Sequential(Net(), nn.Linear(100,1...
https://stackoverflow.com/questions/54062495/