instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Input type (MPSFloatType) and weight type (torch.FloatTensor) should be the same
I am trying to run this notebook on Apple M1 (1st gen) running MacOS 12.4, libs freeze: >pip3 freeze anyio @ file:///private/tmp/jupyterlab--anyio-20211211-70040-1yv1wmx/anyio-3.4.0 appnope==0.1.2 argon2-cffi @ file:///private/tmp/jupyterlab--argon2-cffi-20211211-70040-1er07d0/argon2-cffi-21.2.0 argon2-cffi-binding...
My guess is that the model has not been placed onto the MPS device. If you place your model onto the MPS device (by calling model.to(device)), does your code work?
https://stackoverflow.com/questions/72421284/
How can I efficiently mask out certain pairs in (2, N) tensor?
I have a torch tensor edge_index of shape (2, N) that represents edges in a graph. For each (x, y) there is also a (y, x), where x and y are node IDs (ints). During the forward pass of my model I need to mask out certain edges. So, for example, I have: n1 = [0, 3, 4] # list of node ids as x n2 = [1, 2, 1] # list of...
If you're ok with the way you suggested at Edit#1, you get the complement result by: edge_index[:, [i for i in range(edge_index.shape[1]) if not (i in _except)]] hope this is fast enough for your requirement. Edit 1: from functools import reduce ids = torch.stack([torch.tensor(n1), torch.tensor(n2)], dim=1) ids = tor...
https://stackoverflow.com/questions/72427054/
Difference between sum and mean in .backward()
I know we are converting the tensor in scaler than applying backward(), but when to sum and when to mean? some_loss_function.sum().backward() -OR- some_loss_function.mean().backward()
There is no canonical answer to your question. Essentially what you're asking is should I average or sum my loss, as readers we have no knowledge of your problem and what this loss function corresponds to. It all depends on your use case. Generally though, you would average over summation because you often don't wish t...
https://stackoverflow.com/questions/72429838/
Difference between forward and train_step in Pytorch Lightning?
I have a transfer learning Resnet set up in Pytorch Lightning. the structure is borrowed from this wandb tutorial https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY and from looking at the documentation https://pytorch-lightning.readthedocs.io/en/latest/common/...
I am confused about the difference between the def forward () and the def training_step() methods. Quoting from the docs: "In Lightning we suggest separating training from inference. The training_step defines the full training loop. We encourage users to use the forward to define inference actions." So forw...
https://stackoverflow.com/questions/72437583/
How to rescale a pytorch tensor to interval [0,1]?
I would like to rescale a pytorch tensor named outmap to the [0, 1] interval. I tried this: outmap_min = torch.min(outmap, dim=1, keepdim=True) outmap_max = torch.max(outmap, dim=1, keepdim=True) outmap = (outmap - outmap_min) / (outmap_max - outmap_min) And I am getting this error: TypeError: unsupported operand type...
There are many ways to answer the question posed in your title (e.g., min-max normalization, or one of many non-linear functions mapping (-infinity, infinity) to [0, 1]). Based on the context of the post, I'm assuming you just want to implement min-max normalization. torch.min() does not return a tensor; it returns a t...
https://stackoverflow.com/questions/72440228/
Convert from tensor to cpu for dictionary values
I have a dictionary which has the following values and I am trying to convert my tensors in 'train_acc' to a list of float values like the rest so that I can use it to plot graph but I have no idea how to do it. defaultdict(list, {'train_acc': [tensor(0.9889, device='cuda:0', dtype=torch.float64), ...
It can be done .cpu() - moving to cpu then get the value of the tensor by .item(). If the dict looks like below: dict = { 'train_acc': [tensor(0.9889, device='cuda:0', dtype=torch.float64), tensor(0.9909, device='cuda:0', dtype=torch.float64), tensor(0.9912, device='cuda:0', dtype=torch.flo...
https://stackoverflow.com/questions/72443945/
How to stop updating the parameters of a part of a layer in a CNN model (not the parameters of the whole layer)?
For example, there are ten parameters(filters) in a CNN layer, how I can do to only update five of them and keep the rest unchanged?
In Pythorch is easy to freeze only part of the net thanks to the requires_grad property: Here is a simple script: def freeze_layers(model, num_of_layers): freezed = 0 for layer in model.children(): freezed += 1 if layer < num_of_layers: layer.requires_grad = False Consider howeve...
https://stackoverflow.com/questions/72473409/
Training on GPU produces slightly different results then when trained on CPU
I just tried my new Script to train a model on the GPU rather than on the CPU. And the training values (loss, metrics) differ to when trained on the CPU. I was under the impression that running on cuda vs on cpu should not make a difference. Was I wrong or has it something to do with my code? Using pytorch=10.1.2 and c...
How big a difference? Tiny differences are to be expected. Order of commutative operations matters for floating point computations. That is: serialised_total = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 parallelised_total = (0.1 + 0.1 + 0.1) + (0.1 + 0.1 + 0.1) # No actual parallelisation is performed. The above is just exampl...
https://stackoverflow.com/questions/72477224/
how to transform a posting file to a pytorch tensor
Is there a python package that transforms a postings file to a pytorch tensor? By a posting file I mean a csv file with the following format: "docID" ,"wordID" ,"count" I also have a dictionary.txt which associates each wordID to a word. At the end, my text data consists of postings file a...
No, you have to do it youself. You can simply convert each elemnt into a pytorch tensor or use the pytorch dataset api like this. import csv import torch from torch.utils.data import Dataset from typing import List, NamedTuple CsvRowItem = NamedTuple("CsvRowItem", [ ("docId", int), ("w...
https://stackoverflow.com/questions/72481831/
What is the purpose of with torch.no_grad():
Consider the following code for Linear Regression implemented using PyTorch: X is the input, Y is the output for the training set, w is the parameter that needs to be optimised import torch X = torch.tensor([1, 2, 3, 4], dtype=torch.float32) Y = torch.tensor([2, 4, 6, 8], dtype=torch.float32) w = torch.tensor(0.0, dt...
The requires_grad argument tells PyTorch that we want to be able to calculate the gradients for those values. However, the with torch.no_grad() tells PyTorch to not calculate the gradients, and the program explicitly uses it here (as with most neural networks) in order to not update the gradients when it is updating th...
https://stackoverflow.com/questions/72504734/
How to setup CMake project to use PyTorch C++ API installed via Conda
I have Miniconda3 on a Linux system (Ubuntu 22.04). The environment has Python 3.10 as well as a functioning (in Python) installation of PyTorch (installed following official instructions). I would like to setup a CMake project that uses PyTorch C++ API. The reason is not important and also I am aware that it's beta (t...
Using this conda env: name: pytorch_latest channels: - pytorch - conda-forge - defaults dependencies: - pytorch=1.11.0 - torchvision - torchaudio - cpuonly I copied the small example from here and got it to run. The key was to set the correct library directories (both torch in site-packages, but also th...
https://stackoverflow.com/questions/72531611/
Is GradScaler necessary with Mixed precision training with pytorch?
So going the AMP: Automatic Mixed Precision Training tutorial for Normal networks, I found out that there are two versions, Automatic and GradScaler. I just want to know if it's advisable / necessary to use the GradScaler with the training becayse it is written in the document that: Gradient scaling helps prevent grad...
Short answer: yes, your model may fail to converge without GradScaler(). There are three basic problems with using FP16: Weight updates: with half precision, 1 + 0.0001 rounds to 1. autocast() takes care of this one. Vanishing gradients: with half precision, anything less than (roughly) 2e-14 rounds to 0, as opposed t...
https://stackoverflow.com/questions/72534859/
module 'torch' has no attribute 'has_mps'
I just followed a youtube video that teaches how to install PyTorch nightly for MacBook to accelerate by m1 chip. However, I came across a problem really wierd. I can see in the jupyter notebook that torch.has_mps = True. But in jupyter notebook in vscode, it shows that module 'torch' has no attribute 'has_mps'. Can a...
Just make sure you installed the nightly build of PyTorch. Apple Silicon support in PyTorch is currently available only in nightly builds. e.g., if you're using conda, try this: conda install pytorch torchvision -c pytorch-nightly or with pip pip3 install --pre torch torchvision --extra-index-url https://download.pyto...
https://stackoverflow.com/questions/72535034/
RuntimeError: torch.nn.functional.binary_cross_entropy and torch.nn.BCELoss are unsafe to autocast
I am trying to implement U^2 Net for Salient Object detection. Since this code is not optimised for training, following this official documentation for AMP, I have made some changes to the original code in my fork to check the effects. I have used the code exactly and when you run my version of training code on colab a...
The main reason why it was due to unstable nature of Sigmoid + BCE. Referring to documentation and torch community, all I had to to do was to replace the models from F.sigmoid(d0)... to d0..... and then in turn replace nn.BCELoss(size_average=True) with nn.BCEWithLogitsLoss(size_average=True). Now the model is running ...
https://stackoverflow.com/questions/72536002/
Find the biggest of two pytorch tensor on size
How to find the biggest of two pytorch tensors on size >>> tensor1 = torch.empty(0) >>> tensor2 = torch.empty(1) >>> tensor1 tensor([]) >>> tensor2 tensor([5.9555e-34]) torch.maximum is returrning the empty tensor as the biggest tensor >>> torch.maximum(tensor1,tensor2) ten...
Why not comparing their first dimension size? To do so you can use equivalents: x.size(0), x.shape[0], and len(x). To return the tensor with longest size, you can use the built-in max function with the key argument: >>> max((tensor1, tensor2), key=len)
https://stackoverflow.com/questions/72540912/
Keras to Pytorch -> troubles with layers and shape
I am in the process of converting a Keras model to PyTorch and would need your help. Keras Code: def model(input_shape): input_layer = keras.layers.Input(input_shape) conv1 = keras.layers.Conv1D(filters=16, kernel_size=3, padding="same")(input_layer) conv1 = keras.layers.BatchNormalization()(conv1...
My Current Code is: class Net(nn.Module): def __init__(self): super(Net,self).__init__() self.conv1 = nn.Conv1d(256,128,1) self.batch1 = nn.BatchNorm1d(128) self.avgpl1 = nn.AvgPool1d(1, stride=1) self.fc1 = nn.Linear(128,3) def forward(self,x): x = self.conv...
https://stackoverflow.com/questions/72547478/
pip install does not work with python3 on windows
I am getting acquainted with python development and it's been some time since I wrote python code. I am setting up my IDE (Pycharm) and Python3 binaries on Windows 10. I want to start working with the pytorch library and I am used to before in python2 just typing pip install and it works fine. Now it seems pip is not ...
PyTorch Documentation does have a selector that will give you the commands for pip and conda. However, Python3 should have pip installed, it may just be pip3 (that's what it was for me).
https://stackoverflow.com/questions/72549322/
Vectorised pairwise distance
TLDR: given two tensors t1 and t2 that represent b samples of a tensor with shape c,h,w (i.e, every tensor has shape b,c,h,w), i'm trying to calculate the pairwise distance between t1[i] and t2[j] for all i,j efficiently some more context - I've extracted ResNet18 activations for both my train and test data (CIFAR10) ...
It is common to have to reshape your data before feeding it to a builtin PyTorch operator. As you've said torch.cdist works with two inputs shaped (B, P, M) and (B, R, M) and returns a tensor shaped (B, P, R). Instead, you have two tensors shaped the same way: (b, c, h, w). If we match those dimensions we have: B=b, M=...
https://stackoverflow.com/questions/72551247/
How to prevent NVIDIA from automatically upgrading the driver on Ubuntu?
I was training models last night on my Ubuntu workstation, and then woke up this morning and saw this message: Failed to initialize NVML: Driver/library version mismatch Apparently the NVIDIA system driver automatically updated itself, and now I need to reboot the machine to use my GPUs... How do I prevent automatic u...
I think I have had the same issue. It is because of so-called unattended upgrades on Ubuntu. Solution 1: check the changed packages and revert the updates Check the apt history logs less /var/log/apt/history.log Then you can see what packages have changed. Use apt or aptitude to revert the changes. Solution 2: disable...
https://stackoverflow.com/questions/72560165/
how to expand the dimensions of a tensor in pytorch
i'm a newcomer for pytorch. if i have a tensor like that: A = torch.tensor([[1, 2, 3], [ 4, 5, 6]]), but my question is how to get a 2 dimensions tensor like: B = Tensor([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
You can concatenate ... A tensor([[[1., 2., 3.], [4., 5., 6.]]]) B = torch.cat((a, a)) B tensor([[[1., 2., 3.], [4., 5., 6.]], [[1., 2., 3.], [4., 5., 6.]]])
https://stackoverflow.com/questions/72566000/
FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version
I am building a model to train it for binary classification. While processing the data before feeding it to the model i come across this warning FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead. Here is my code import torch import torch.nn as nn import ma...
you are trying to access the new_df with predictors which is set. convert it to list. example: print(new_df[list(predictors)].head())
https://stackoverflow.com/questions/72583625/
How to use pytorch to perform gradient descent, and print out the true minimum?
I'm trying to use a gradient method to find a minimizer of a function f, where x(k+1)=x(k)-α▽f(x), and α=0.1. The function f is f(x) = 2*(x^3+1)^(-1/2), x(0)=1 Here is the pytorch sample import torch import torch.nn as nn from torch import optim alpha = 0.1 class MyModel(nn.Module): def __init__(self): ...
There are a few things that need to be considered ... For x to be a parameter (model.parameter()) x should be nn.Parameter(torch.as_tensor([1.])) You are passing what (and why) x to the forward method? The function f(x) = 2*(x^3+1)^(-1/2) is inversely proportional to x. When x goes up in value, the function goes down....
https://stackoverflow.com/questions/72596741/
Pytorch NLP Huggingface: model not loaded on GPU
I have this code that init a class with a model and a tokenizer from Huggingface. On Google Colab this code works fine, it loads the model on the GPU memory without problems. On Google Cloud Platform it does not work, it loads the model on gpu, whatever I try. class OPT: def __init__(self, model_name: str = "fa...
You should use the .to(device) method like this: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = nameofyourmodel.to(device)
https://stackoverflow.com/questions/72601714/
How to learn multiple binary classifiers?
I have an input of shape 14 x 10 x 128 x 128, where 14 is batch_size, 10 is the sequence_length and each item in the sequence is of shape 128 x 128. I want to learn to map this input to output of shape 14 x 10 x 128, i.e., for each item in the sequence I want to learn 128-binary classifiers. Does the following model ma...
Not really convinced a 1D convolution will get you anywhere since it reasons in two dimensions only. In your case, you are dealing with a sequence of 2D elements. Naturally a nn.Conv2d would seem more appropriate for this kind of task. You are looking to do a one-to-one mapping with your sequence elements and can there...
https://stackoverflow.com/questions/72623344/
Loss for Multi-label Classification
I am working on a multi-label classification problem. My gt labels are of shape 14 x 10 x 128, where 14 is the batch_size, 10 is the sequence_length, and 128 is the vector with values 1 if the item in sequence belongs to the object and 0 otherwise. My output is also of same shape: 14 x 10 x 128. Since, my input sequenc...
It is usually recommended to stick with batch-wise operations and avoid going into single-element processing steps while in the main training loop. One way to handle this case is to make your dataset return padded inputs and labels with additionally a mask that will come useful for loss computation. In other words, to ...
https://stackoverflow.com/questions/72626063/
AttributeError: module 'torch.distributed' has no attribute 'is_initialized' in pytorch==1.11.X
whenever we are creating the object for TrainingArguments from transformers import Trainer, TrainingArguments batch_size = 64 logging_steps = len(emotions_encoded["train"]) // batch_size model_name = f"{model_ckpt}-finetuned-emotion" training_args = TrainingArguments(output_dir=model_name, ...
In order to solve this problem Actually Window and Mac doesn't support distributed training facility so this issue is occuring To solve this problem go to your transformers package where you install it in my case it is Desktop/rajesh/pytorch_env/env/lib/python3.8/site-packages/transformers/training_args.py replace lin...
https://stackoverflow.com/questions/72641886/
How do I get my conda environment to recognize my GPU?
I'm pretty new to this and I'm wondering how do I get my conda environment to be able to recognize my GPU? Purpose is for me to emulate the Linux environment on my windows 10 device. I'm using the Anaconda prompt. I'm following the instructions in this set up guide : https://medium.com/analytics-vidhya/4-steps-to-insta...
Check your CUDA version. Not all the version of CUDA supports official pytorch. Check the official website of pytorch
https://stackoverflow.com/questions/72641958/
fastest way to calculate edges (derivatives) of a big torch tensor
Given a tensor with shape (b,c,h,w), I want to extract edges of the spatial data, that is, calculate x, y direction derivatives of the (h,w) and calculate the magnitude I=sqrt(|x_amplitude|^2+|y_amplitude|^2) My current implementation is as followed row_mat = np.asarray([[0, 0, 0], [1, 0, -1], [0, 0, 0]]) col_mat = ro...
For this specific operation you might be able to speed things up a bit by doing it "manually": import torch.nn.functional as nnf def derivative(batch: torch.Tensor) -> torch.Tensor: # pad batch x = nnf.pad(batch, (1, 1, 1, 1), mode='reflect') dx2 = (x[..., 1:-2, :-2] - x[..., 1:-2, 2:])**2 dy2 = (...
https://stackoverflow.com/questions/72644166/
How can I Modify pytorch dataset __getitem__ function to return a bag of 10 images?
I have a directory with multiple images separated into folders. Each folder has up to 3000 images. I would like to modify the pytorch dataset getitem function so that it returns bags of images, where each bag contains 10 images. Here is what I have so far: transform = transforms.Compose([transforms.Resize(255), ...
Why do you need "bags of 10 images"? If you need them as mini batches for training -- don't change the Dataset, but use a DataLoader for that. A DataLoader takes a dataset and does the "batching" for you. Alternatively, you can overload the __getitem__ method and implement your own that returns 10 i...
https://stackoverflow.com/questions/72646497/
Deep Convolutional GAN (DCGAN) works really well on one set of data but not another
I am working on using PyTorch to create a DCGAN to use to generate trajectory data for a robot based on a dataset of 20000 other simple paths. The DCGAN works great on the MNIST dataset, but does not work well on my custom dataset. I am trying to tweak/tune the DCGAN to give good results after being trained with my cus...
(Not enough reputation to comment yet, so I'll reply) Since your code works fine on the MNIST dataset, the main problem here is that the trajectories in your training data are practically imperceptible, even to a human observer. Note that the trajectory lines are much thinner than the digit lines in the MNIST dataset.
https://stackoverflow.com/questions/72651806/
How can I extract features from pytorch fasterrcnn_resnet50_fpn
I tried to extract features from following code. However, it says 'FasterRCNN' object has no attribute 'features' I want to extract features with (36, 2048) shape features when it has 36 classes. Is there any method to extract with pretrained pytorch models. model = torchvision.models.detection.fasterrcnn_resnet50_fpn(...
The function you are calling returns a FasterRCNN object which is based on GeneralizedRCNN. As you have experienced, this object doesn't indeed have a feature attribute. Looking at its source code, if you want to acquire the feature maps, you can follow L83 and L101: >>> images, _= model.transform(images, None...
https://stackoverflow.com/questions/72655498/
Find jaccard similarity among a batch of vectors in PyTorch
I'm having a batch of vectors of shape (bs, m, n) (i.e., bs vectors of dimensions mxn). For each batch, I would like to calculate the Jaccard similarity of the first vector with the rest (m-1) of them Example: a = [ [[3, 8, 6, 8, 7], [9, 7, 4, 8, 1], [7, 8, 8, 5, 7], [3, 9, 9, 4, 4]], [[7, 3, 8, 1,...
I don't know how you could achieve this in pytorch, since AFAIK pytorch doesn't support set operations on tensors. In your js() implementation, union calculation should work, but intersection = union[counts > 1] doesn't give you the right result if one of the tensors contains duplicated values. Numpy on the other ha...
https://stackoverflow.com/questions/72657212/
Print activations of a neural network in Pytorch
I was doing as suggested in this StackOverflow's questions: Pytorch: why print(model) does not show the activation functions? Basically I want to train a neural network on MNIST, and I want to print the activations. This is the neural networks: class Net(nn.Module): def __init__(self): super().__init__() ...
I think you are getting mixed up between what the an activation function is an what you might be trying to show which are the activations of your intermediate layers. The question you are linking is asking about why isn't the activation function not showing in the summary of the PyTorch model. On one hand, activation f...
https://stackoverflow.com/questions/72660186/
Does Huggingface's "resume_from_checkpoint" work?
I currently have my trainer set up as: training_args = TrainingArguments( output_dir=f"./results_{model_checkpoint}", evaluation_strategy="epoch", learning_rate=5e-5, per_device_train_batch_size=4, per_device_eval_batch_size=4, num_train_epochs=2, weight_decay=0.01, p...
You also should add resume_from_checkpoint parametr to trainer.train with link to checkpoint trainer.train(resume_from_checkpoint="{<path-where-checkpoint-were_stored>/checkpoint-0000") 0000- example of checkpoin number. Don't forget to mount your drive during whole this process.
https://stackoverflow.com/questions/72672281/
How to bin a pytorch tensor into an array of values
Say I have an array of values w = [w1, w2, w3, ...., wn] and this array is sorted in ascending order, all values being equally spaced. I have a pytorch tensor of any arbitrary shape. For the sake of this example, lets say that tensor is: import torch a = torch.rand(2,4) assuming w1=torch.min(a) and wn=torch.max(a), ...
You could compute for all points in a, the difference with each bin inside w. For this, you need a little bit of broadcasting: >>> z = a[...,None]-w[None,None] tensor([[[ 0.7192, 0.3892, 0.0592, -0.2808], [ 0.6264, 0.2964, -0.0336, -0.3736], [ 0.5180, 0.1880, -0.1420, -0.4820], [...
https://stackoverflow.com/questions/72673094/
PyTorch running under WSL2 getting "Killed" for Out of memory even though I have a lot of memory left?
I'm on Windows 11, using WSL2 (Windows Subsystem for Linux). I recently upgraded my RAM from 32 GB to 64 GB. While I can make my computer use more than 32 GB of RAM, WSL2 seems to be refusing to use more than 32 GB. For example, if I do >>> import torch >>> a = torch.randn(100000, 100000) # 40 GB tens...
According to this blog post, WSL2 is automatically configured to use 50% of the physical RAM of the machine. You'll need to add a memory=48GB (or your preferred setting) to a .wslconfig file that is placed in your Windows home directory (\Users\{username}\). [wsl2] memory=48GB After adding this file, shut down your d...
https://stackoverflow.com/questions/72693671/
Practically understanding gradient dimensions on backprop
I've wrote this piece of torch code that implements a Linear(1,1) -> Linear(1,1) -> MSE forward/backward pass: l1 = torch.nn.Linear(1, 1, bias=False) l2 = torch.nn.Linear(1, 1, bias=False) l1.weight = torch.nn.Parameter( torch.tensor([[ 0.6279 ]])) l2.weight = torch.nn.Parameter( torch.tensor([[ 0...
I'm not a 100% sure if I understood your problem correctly, but the gradient w.r.t a particular layer does have the same dimensionality as that layer's output. The gradient w.r.t (linearly applied) weights in that layer, is not computed by backpropagation but by multiplying the input activations (those before the weigh...
https://stackoverflow.com/questions/72693772/
How to select fairseq option `--ddp-backend`
I'm learning how to use fairseq to implement a simple translation model based on Transformer. I would like to use 2 GeForce RTX 3090 GPUs on my lab server. Which option should I select for --ddp-backend of fairseq-train? Furthermore, could you explain about the meaning of all following options for --ddp-backend and whe...
I am not too sure, but I found this on GitHub DDP_BACKEND_CHOICES = ChoiceEnum( [ "c10d", # alias for pytorch_ddp "fully_sharded", # FullyShardedDataParallel from fairscale "legacy_ddp", "no_c10d", # alias for legacy_ddp "pytorc...
https://stackoverflow.com/questions/72694641/
What are the PyTorch's model.eval() + no_grad() equivalent in TensorFlow?
I am trying to extract BERT embeddings and reproduce this code using tensorflow instead of pytorch. I know tf.stop_gradient() is the equivalent of torch.no_grad() but what about model.eval() / combination of both ? # Put the model in "evaluation" mode, meaning feed-forward operation. model.eval() # Run the t...
TLDR; eval and no_grad are two completely different things but will often be used in conjunction, primarily for performing fast inference in the case of evaluation/testing loops. The nn.Module.eval function is applied on a PyTorch module and gives it the ability to change its behaviour depending on the stage type: trai...
https://stackoverflow.com/questions/72716490/
Create custom connection/ non-fully connected layers in Pytorch
As shown in the figure, it is a 3 layer with NN, namely input layer, hidden layer and output layer. I want to design the NN(in PyTorch, just the arch) where the input to hidden layer is fully-connected. However, from hidden layer to output, the first two neurons of the hidden layer should be connected to first neuron ...
As @Jan said here, you can overload nn.Linear and provide a point-wise mask to mask the interaction you want to avoid having. Remember that a fully connected layer is merely a matrix multiplication with an optional additive bias. Looking at its source code, we can do: class MaskedLinear(nn.Linear): def __init__(sel...
https://stackoverflow.com/questions/72725944/
How convert this Pytorch loss function to Tensorflow?
This Code for a paper I read had a loss function written using Pytorch, I tried to convert it as best as I could but am getting all Zero's as model predictions, so would like to ask the following: Are the methods I used the correct equivalent in Tensorflow? Why is the model predicting only Zero's? Here is the functio...
Try this custom_loss: def custom_loss(y_pred, y_true): alpha = 2.0 loss = (y_pred - y_true) ** 2.0 adj = tf.math.multiply(y_pred,y_true) adj = tf.where(tf.greater(adj, 0.0), tf.constant(1/alpha), adj) adj = tf.where(tf.less(adj, 0.0), tf.constant(alpha), adj) loss = loss * adj return tf.red...
https://stackoverflow.com/questions/72750343/
undo torch.chunk to rebuild image in right order
I am trying to process a 3D image in chunks (non-overlapping windows). Once this is done I want to put the chunks back together in the right order. I have been chunking the image as below: tens = torch.tensor(range(64)) tens = tens.view((4,4,4)) print(tens) >>>tensor([[[ 0, 1, 2, 3], [ 4, 5, 6, ...
Operator torch.chunk doesn't reduce dimensions so its inverse is torch.cat, not torch.stack. Here are the transforms with the corresponding inverse operations: Splitting the last dimension in two: >>> chunks = tens.chunk(chunks=2, dim=-1) >>> torch.cat(chunks, dim=-1) Splitting the second dimensio...
https://stackoverflow.com/questions/72750405/
How to flow gradient through parameter updates?
I have a parameter import torch import torch.nn as nn x = nn.Parameter(torch.tensor([1.0])) I need to update the value of this parameter while maintaining the gradient flow (for a meta learning problem). PyTorch does not allow in-place operations on leaf-variable like a = torch.tensor([2.0], requires_grad=True) x.copy...
What you are looking for is torch.Tensor.clone: This function is differentiable, so gradients will flow back from the result of this operation to input. To create a tensor without an autograd relationship to input see detach(). >>> a = torch.tensor([2.0], requires_grad=True) >>> x = a.clone() >&g...
https://stackoverflow.com/questions/72758128/
Fine Tuning Blenderbot
I have been trying to fine-tune a conversational model of HuggingFace: Blendebot. I have tried the conventional method given on the official hugging face website which asks us to do it using the trainer.train() method. I also tried it using the .compile() method. I have tried fine-tuning using PyTorch as well as Tensor...
Here is a link I am using to fine-tune the blenderbot model. Fine-tuning methods: https://huggingface.co/docs/transformers/training Blenderbot: https://huggingface.co/docs/transformers/model_doc/blenderbot from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration mname = "facebook/blenderbot...
https://stackoverflow.com/questions/72774975/
Blenderbot FineTuning
I have been trying to fine-tune a conversational model of HuggingFace: Blendebot. I have tried the conventional method given on the official hugging face website which asks us to do it using the trainer.train() method. I tried it using the .compile() method. I have tried fine-tuning using PyTorch as well as TensorFlow ...
Maybe try using the TFBlenderbotForConditionalGeneration class for Tensorflow. It has what you need: import tensorflow as tf from transformers import BlenderbotTokenizer, TFBlenderbotForConditionalGeneration mname = "facebook/blenderbot-400M-distill" model = TFBlenderbotForConditionalGeneration.from_pretrain...
https://stackoverflow.com/questions/72776834/
why is my loss function only returning NaN values?
below is my code import numpy as np import torch from torch.utils import data import torch.nn as nn import pandas as pd # PREPPING DATA FROM CSV FILE csvFile = pd.read_csv('/Users/ericbeep999/Desktop/Web Development/Projects/Python/pytorch/3. Linear Regression/weather.csv') labels, features = csvFile.iloc[:, 4], csvFi...
I changed your learning rate to 0.001 and it runs without giving NaNs (albeit not learning anything since predicting min temperature from max temperature in that data may not be easily learned). My guess is the issue is with the scale of your input/output data, i.e. they're in the range of something like 0-40 which isn...
https://stackoverflow.com/questions/72778247/
How to set a 3-d tensor to 0 according to the value of a 2-d tensor
Suppose I have a 3-d tensor P shaped (B, N, d) and a 2-d tensor Q shaped (B,N), where values in Q are smaller than d. I want to set some values in P to 0 using the indices from Q: For instance, P = torch.randn(2,3,6) Q = torch.tensor([[0,3,4], [2,1,3]]) How can I set P[0,0,0]=0; P[0,1,3]=0; P[0,2,4]=0; P[1,0,2]=0; P[1...
What you are looking to do is: P[i, j, Q[i, j]] = 0 This is the perfect use case for torch.Tensor.scatter, which has the effect of placing an arbitrary value at designated positions. We first need the input and indexer to have matching shapes: >>> Q_ = Q[...,None].expand_as(P) And apply the scatter function ...
https://stackoverflow.com/questions/72785645/
PyTorch - How to specify an input layer? Is it included by default?
I am working on a Reinforcement Learning problem in StableBaselines3, but I don't think that really matters for this question. SB3 is based on PyTorch. I have 101 input features, and even though I designed a neural architecture with the first layer having only 64 nodes, the network still works. Below is a screenshot of...
We can do a little bit of digging inside Stable Baselines' source code. Looking inside the MaskableActorCriticPolicy, we can see it builds a MLP extractor by initializing an instance of MlpExtractor and creating the policy_net sub-network here whose layers are defined in this loop. Ultimately the layers feature sizes a...
https://stackoverflow.com/questions/72792063/
Creating an image grid of tensors out of a batch using matplotlib/pytorch
I am trying to create a grid of images (e.g. 3 by 3) from a batch of tensors that will be fed into a GAN through a data loader in the next step. With the below code I was able to transform the tensors into images that are displayed in a grid in the right position. The problem is, that they are all displayed in a separa...
And here is how to display a variable number of wonderful CryptoPunks using matplotlib XD: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid import matplotlib.image as mpimg row_count = 3 col_count = 3 cryptopunks = [ mpimg.imread(f"cryptopunks/{i}.png") for i in range(row_co...
https://stackoverflow.com/questions/72803919/
my nn.sigmoid() gradient different with my manual calculation
so im doing a manual calculation of lstm backpropagation in excel and want to compare it to my code, but im having trouble with the gradient of sigmoid at the pytorch. : the output here: tensor([[0.8762]], grad_fn=<SigmoidBackward>) tensor([-0.1238]) epoch: 0 loss: 0.13214068 so the first line is the sigmoid v...
I can't reproduce your error. For one thing, your value of 0.10845 is not correct: remember that it might be computed that way (i.e. z * (1 - z)) because you expect z to be logistic(z) in your implementation. But, in any case, the value I compute agrees with what PyTorch produces. Here's the logistic function: import n...
https://stackoverflow.com/questions/72809218/
GAN LOSS of Generator and Discriminator Lowest at First Epoch - Is that normal?
I am trying to train a simple GAN and I noticed that the loss for the generator and discriminator is the lowest in the first epoch? How can that be? Did I miss something? Below you find the plot of the Loss over the iterations: Here is the code I was using: I adapted the code according to your suggest @emrejik. It does...
I didn't see the proper use of loss function for the discriminator. You should give real samples and generated samples separately to the discriminator. I think you should change your code to a form like this: fake = generator(noise) disc_real = disc(real) loss_disc_real = loss_func(disc_real, torch.ones_like(disc_real...
https://stackoverflow.com/questions/72815092/
How to reduce the size of Bert model(checkpoint/model_state.bin) using pytorch
I used torch.quantization.quantize_dynamic to reduce the model size but it is reducing my prediction Accuracy score. I'm using that model file inside the Flask and doing some real time predictions, Due to the large size i'm facing issues while predicting. So could anyone please help me on reducing the bert model size u...
Here is the doc of torch.quantization.quantize_dynamic where dtype is set to torch.qint8. so if you dont want your accuracy to drastically decrease use the below syntax torch.quantization.quantize_dynamic(model, qconfig_spec=None, dtype=torch.float16)
https://stackoverflow.com/questions/72818221/
Overfitting LSTM pytorch
I was following the tutorial on CoderzColumn to implement a LSTM for text classification using pytorch. I tried to apply the implementation on the bbc-news Dataset from Kaggle, however, it heavily overfits, achieving a max accuracy of about 60%. See the train/loss curve for example: Is there any advice (I am quite new...
Have you tried adding nn.Dropout layer before the self.fc? Check what p = 0.1 / 0.2 / 0.3 will do. Another thing you can do is to add regularisation to your training via weight_decay parameter: optimizer = torch.optim.Adam(model.parameters(), lr=1e-4, weight_decay=1e-5) Use small values first, and increase by 10 time...
https://stackoverflow.com/questions/72854736/
PyTorch: Handling multiple functions and arguments
I have a large number of neural networks (such that I have to use list comprehension to produce them), say [f_1, f_2, f_3 ...], collectively denoted by F. I have the argument X = [x_1, x_2, x_3 ...], such that input tensor x_i is intended for the network f_i. The tensors I have will be big, owing to the data and then t...
You could again use a list comprehension: out = [f(x) for f,x in zip(F,X)]
https://stackoverflow.com/questions/72855924/
Difficulties in using jacobian of torch.autograd.functional
I am solving PDE, so I need the jacobian matrix of the residual with respect to variables. Here is my code import torch from torch.autograd.functional import jacobian def get_residual (pgnew, swnew): residual_w = 5*(swnew-swold)+T_w*((pgnew[2:,:,:]-pgnew[1:-1,:,:])-(pc[2:,:,:]-pc[1:-1,:,:])) - T_w*((pgnew[1:-1,:,:...
You have to give the jacobian a tuple as second argument, containing the arguments of get_residual: print('Check Jacobian \n', jacobian(get_residual, (pgnew, swnew))) (You may need to make sure that they have the shape you want etc.)
https://stackoverflow.com/questions/72862653/
PyTorch lightening resume training from last epoch and weights
I am using PyTorch Lightening trainer for pre-training a large model. I know I can resume training from old weights but that does not contain old hyper-parameters (lr, last_epoch, etc.). Is there any automatic way to resume training? OR Do I need to overload Checkpoint Callback or CSVLogger to search for old cvs logs a...
Instead of load from checkpoint, use resume_from_checkpoint in trainer. # resume from a specific checkpoint trainer = Trainer(resume_from_checkpoint="some/path/to/my_checkpoint.ckpt") See more details here https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html#resume-from-checkpoint .
https://stackoverflow.com/questions/72870376/
Good way to down-dimension (extract) of a 3D tensor (or same as numpy)
I have some data stored in a certain 3D tensor data1 = torch.ones(3, 3, 3, requires_grad=True, dtype=torch.float64) data2 = torch.zeros(3, 3, 3, requires_grad=True, dtype=torch.float64) When I perform the calculation temp= data1[:,0,0]+data2[:,0,0] I would like to see the result in form of size ([3])tensor inst...
As @paime said, you can use single element slices instead of single indexes: >>> data1[:,:1,:1] + data2[:,:1,:1] tensor([[[1.]], [[1.]], [[1.]]], dtype=torch.float64, grad_fn=<AddBackward0>) Alternatively, there are different ways of unsqueezing multiple dimensions at the same time: U...
https://stackoverflow.com/questions/72872462/
Neural Network for Regression using PyTorch
I am trying to implement a Neural Network for predicting the h1_hemoglobin in PyTorch. After creating a model, I kept 1 in the output layer as this is Regression. But I got the error as below. I'm not able to understand the mistake. Keeping a large value like 100 in the output layer removes the error but renders the mo...
Since you are performing regression, the CrossEntropyLoss() internally implements the NLLLoss() function. The CrossEntropyLoss() expects C classes for C predictions but you have specified only one class. The NLLLoss() tries to index into the prediction logits based on the ground-truth value. E.g., in your case, the gro...
https://stackoverflow.com/questions/72874433/
How to use fairseq interactive with multiple gpu?
I am trying to generate new prediction for the model, but I found it is not that intuitive to use fairseq. I found fairseq-interactive could help to generate with a good settings of batch_size, however, it seems that it will use 1 GPU at a time, I wonder if it is possible to use multiple GPU? Hope someone can kindly he...
You cannot do this natively within fairseq. The best way to do this is to shard your data and run fairseq-interactive on each shard in the background. Be sure to set CUDA_VISIBLE_DEVICES for each shard so you put each shard's generation on a different GPU. This advice also applies to fairseq-generate (which will be sig...
https://stackoverflow.com/questions/72881589/
Using reshape or view in a certain fashion
import torch import numpy as np a = torch.tensor([[1, 4], [2, 5],[3, 6]]) bb=a.detach().numpy() b = a.view(6).detach().numpy() Element b is like: [1 4 2 5 3 6] How do I reshape back to the following: [1 2 3 4 5 6] This is just an example, want some generic answers, even 3D.
If you want to remain in PyTorch, you can view b in a's shape, then apply a transpose and flatten: >>> b.view(-1,2).T.flatten() tensor([1, 2, 3, 4, 5, 6]) In the 3D case, you can perform similar manipulations using torch.transpose which enables you to swap two axes. You get the desired result by combining it ...
https://stackoverflow.com/questions/72888827/
How to understand the code "cc[bb] += aa" in pytorch?
import torch aa=torch.tensor([[1,2,3],[4,5,6]]).T bb=torch.tensor([0,1,1]).T cc = torch.zeros(2, 2) cc[bb] += aa Then the result is cc=tensor([[1., 4.],[3., 6.]]), why?
Let us reason with pseudo code: >>> aa = [[1,2,3], [4,5,6]].T >>> aa [[1,4], [2,5], [3,6]] >>> bb = [0,1,1].T >>> b [0, 1, 1] >>> cc = zeros(2, 2) >>> cc [[0,0], [0,0]] The next instruction is an assignment which consists in first indexing cc with ...
https://stackoverflow.com/questions/72895220/
Count all different pixel values given a set of images
In order to sanity check masks for the semantic segmentation task, I would like to know how I can find all different pixel values, given a set of images. I tried: l = [] for img in glob.glob('/content/Maschere/*png'): im = Image.open(img) data = torch.from_numpy(np.asarray(im)) v = torch.unique(data) l.append(v...
I didnt' test it, but something along the lines of: l = set() for img in glob.glob('/content/Maschere/*png'): im = Image.open(img) data = torch.from_numpy(np.asarray(im)) v = set(torch.unique(data)) l.update(v) print(l) It maintains a single set which you update with any new values you encounter.
https://stackoverflow.com/questions/72923811/
Model training converges to a fixed value of loss with low accuracy
I have been trying to train a simple model on Chinese MNIST Kaggle dataset. However it keeps converging to a CrossEntropyLoss of 2.708050 even with model training setting picked up from pytorch tutorials. The losses change but converge to a high value with low accuracy (everytime < 10%). There is no error in how th...
Calculating accuracy with sigmoid is not an issue as you are using argmax, and softmax and sigmoid will return different values but they will be in the same order. However, one issue i'm seeing with your code is that you are including your activation within your forward pass code. What I might encourage you to do is to...
https://stackoverflow.com/questions/72930012/
How to solve RuntimeError: CUDA out of memory?
I try to run an inference using a cli to get the predictions from a detection and recognition model. With cuda10.2 it takes 15 mins for the inference to complete but I have cuda11.3 which takes 3 hours, I want to reduce this time. Note : My hardware does not support cuda10.2. hence I have following packages installed, ...
I use the following solutions whenever I encounter "CUDA out of memory" error. Here are the solutions, from simple to hard: 1- Try to reduce the batch size. First, train the model on each datum (batch_size=1) to save time. If it works without error, you can try a higher batch size but if it does not work, you...
https://stackoverflow.com/questions/72950365/
BCEWithLogitsLoss Multi-label Classification
I'm a bit confused about how to accumulate the batch losses to obtain the epoch loss. Two questions: Is #1 (see comments below) correct way to calculate loss with masks) Is #2 correct way to report epoch loss) optimizer = torch.optim.Adam(model.parameters, lr=1e-3, weight_decay=1e-5) criterion = torch.nn.BCEWithLogit...
In your criterion, you have got the default reduction field set (see the docs), so your masking approach won't work. You should use your masking one step earlier (prior to the loss calculation) like so: batch_loss = (criterion(outputs*masks, gt_labels.float()*masks)).mean() OR batch_loss = (criterion(outputs[masks], g...
https://stackoverflow.com/questions/72959174/
unable to load torchaudio even after installing
I'm trying to use torchaudio but I'm unable to import it. I have installed it and it is also visible through the pip list. <ipython-input-6-4cf0a64f61c0> in <module> ----> 1 import torchaudio ModuleNotFoundError: No module named 'torchaudio' pytorch-lightning 1.2.0 torch 1.1...
Since you are using linux and CPU, you should consider uninstalling every pytorch related packages and re-install them via: pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cpu as shown here.
https://stackoverflow.com/questions/72962998/
Dataloades TypeError: __getitem___() takes 1 positional argument but 2 were given
it's my first time approaching pytorch. I built a dataset class to load tensors by Dataloader, like this: train_loader = DataLoader(dataset_train, batch_size=6, drop_last=True) But at the following line: for i,train_batch in enumerate(train_loader): I receive this error: TypeError: __ getitem__() takes 1 positional a...
I believe you expected to enumerate your dataloader: for i, train_batch in enumerate(dataloader): # train loop
https://stackoverflow.com/questions/72963448/
How can I delete the background outside the drawn contours?
How can I delete the background outside the drawn contours? My main goal is measure size of ONLY cardboard boxes. I have 2 differend code. First code measuring EVERYTHING with aruco marker. Second code is detecting boxes with yolo.(I need this because measure code detects everything) Both of them drawn contours. My mea...
Create black mask image. For each detection draw it contour on mask: cv2.drawContours(img, contours, -1, color=(255, 255, 255), thickness=cv2.FILLED) And after make bitwise_and with this mask.
https://stackoverflow.com/questions/72973571/
MultiplicativeLR scheduler not working properly when call scheduler.step()
PytorchLightning Framework, I am configuring the optimizers like this: def configure_optimizers(self): opt = torch.optim.Adam(self.model.parameters(), lr=cfg.learning_rate) #modified to fit lightning sch = torch.optim.lr_scheduler.MultiplicativeLR(opt, lr_lambda = 0.95) #decrease of 5% every epoch ...
I think that you need to change the value of `lr_lambda'. Here is the link to the documentation: https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.MultiplicativeLR.html lr_lambda (function or list) – A function which computes a multiplicative factor given an integer parameter epoch, or a list of such f...
https://stackoverflow.com/questions/72981846/
Upsampling Only the Last Two Dimensions of a 5D Tensor
I have a 5D tensor x (frames of a video) and I want to upsample the spatial size (the last two dimensions) of this tensor but when I use upsampling, the last three dimensions of the tensor are upsampled. For upsampling I use the following class: class Upsample(nn.Module): def __init__(self, scale_factor, mode, alig...
The trilinear mode of pytorch's interpolate function only supports interpolation of 5D tensor including your third dimension. If you don't mind in resizing your input tensor, you may reduce the dimension and apply bicubic mode for interpolation. class Upsample(nn.Module): def __init__(self, scale_factor, mode = 'bi...
https://stackoverflow.com/questions/73004534/
Cannot import name 'ResNet50_Weights' from 'torchvision.models.resnet'
I was previously loading a ResNet model with the ResNet50_Weights parameter successfully, but then suddenly I started getting the following error: Traceback (most recent call last): File "splitting_models.py", line 3, in <module> from torchvision.models.resnet import ResNet50_Weights ImportError: ...
The problem took me some days to solve it. Before running a code containing the Pytorch models, make sure you are connected to a stable network. This because for the first time when you are running a Pytorch model such resnet50, alexnet, resnet18 it downloads its' functionalities, so incase of installation error it cac...
https://stackoverflow.com/questions/73029425/
Pytorch fine tuned CNN model giving always the same prediction in training and validation data
I decided to move from TensorFlow to Pytorch and I am with some issues in understanding how it works. I tried to follow This Tutorial which has a very simple example of Feature Extraction from ImegeNet CNNs for a binary classification problem. In summary, in my code, the network is defined and called as follows #Functi...
Be careful, img_to_test is in the HWC format. You are reshaping the image when you should be transposing its axes from HWC to CHW. You may want to replace the following: >>> test_x = img_to_test.reshape(1, 3, 224, 224) With a call to np.transpose or torch.transpose instead: >>> test_x = image_to_test...
https://stackoverflow.com/questions/73033021/
Segfault in pytorch on M1: torch.from_numpy(X).float()
I'm using an M1. I'm trying to use pytorch for a conv net. I have a numpy array that I'm trying to turn into a torch tensor. When I call torch.from_numpy(X) pytorch throws an error that it got a double when it expected a float. When I call torch.from_numpy(X).float() on a friends computer, everything is fine. But when ...
What's your pytorch vision? I've encountered the same problem on my Macbook Pro M1, and my pytorch version is 1.12.0 at first. The I downgraded it to version 1.10.0 and the problem is solved. I suspect this has something to do with the compatibility with M1 in newer torch versions. Actually I first uninstalled torch us...
https://stackoverflow.com/questions/73044398/
How do I save custom functions and parameters in PyTorch?
Firstly, the network function is defined: def softmax(X): X_exp=torch.exp(X) partition=X_exp.sum(1,keepdim=True) return X_exp/partition def net(X): return softmax(torch.matmul(X.reshape(-1,W.shape[0]),W)+b) Then update the function parameters by training train(net,train_iter,test_iter,cross_entropy,nu...
The correct way is to implement your own nn.Module and then use the provided utilities to save and load the model's state (their weights) on demand. You must define two functions: __init__: the class initializer logic where you define your model's parameters. forward: the function which implements the model's forward...
https://stackoverflow.com/questions/73046375/
Can I use pytorch .backward function without having created the input forward tensors first?
I have been trying to understand RNNs better and am creating an RNN from scratch myself using numpy. I am at the point where I have calculated a Loss but it was suggested to me that rather than do the gradient descent and weight matrix updates myself, I use pytorch .backward function. I started to read some of the do...
Yes, this will only work on PyTorch Tensors. If the tensors are on CPU, they are basically numpy arrays wrapped into PyTorch Tensors API (i.e., running .numpy() on such a tensor returns exactly the data, it can modified etc.)
https://stackoverflow.com/questions/73057998/
Split PyTorch tensor into overlapping chunks
Given a batch of images of shape (batch, c, h, w), I want to reshape it into (-1, depth, c, h, w) such that the i-th "chunk" of size d contains frames i -> i+d. Basically, using .view(-1, d, c, h, w) would reshape the tensor into d-size chunks where the index of the first image would be a multiple of d, wh...
IIUC, You need torch.Tensor.unfold. import torch x = torch.arange(1, 13) x.unfold(dimension = 0,size = 2, step = 1) tensor([[ 1, 2], [ 2, 3], [ 3, 4], [ 4, 5], [ 5, 6], [ 6, 7], [ 7, 8], [ 8, 9], [ 9, 10], [10, 11], [11, 12]]) An...
https://stackoverflow.com/questions/73061237/
cudnn error when runnung pytorch on Google Colab
Since yesterday when I try to run Pytorch using GPU on Google Colab I recieve the error provided below. Previously it worked fine. I have tried to install different versions of Pytorch and I have got different errors. # Use PyTorch to check versions, CUDA version and cuDNN import torch print("PyTorch version: &q...
Use this code to upgrade Python to newer version(3.9), this solved a problem for me. !wget -O mini.sh https://repo.anaconda.com/miniconda/Miniconda3-py39_4.9.2-Linux-x86_64.sh !chmod +x mini.sh !bash ./mini.sh -b -f -p /usr/local !conda install -q -y jupyter !conda install -q -y google-colab -c conda-forge !python -m i...
https://stackoverflow.com/questions/73062764/
In simple terms, what is the relationship between the GPU, Nvidia driver, CUDA and cuDNN in the context for using a deep learning framework?
I have always been doing deep learning on Google Colab or on school clusters that have everything set up nicely. Recently I needed to set up a workstation to do deep learning from scratch and I realized I have very limited understanding of the things that I need to install to run a framework like tensorflow or pytorch ...
Python code runs on the CPU, not the GPU. This would be rather slow for complex Neural Network layers like LSTM's or CNN's. Hence, TensorFlow and PyTorch know how to let cuDNN compute those layers. cuDNN requires CUDA, and CUDA requires the NVidia driver. All of the last 3 components are provided by NVidia; they've dec...
https://stackoverflow.com/questions/73074402/
nn.Parameter not getting updated not sure about the usage
I have declared two nn.Parameter() variables with requires_grad=True and I am using those in a different function that's being called inside the init method of the class where variables are declared. lparam and rparam are not getting updated My question is am I doing it the right way? if not how it should be done? here...
thanks, I got the solution here https://discuss.pytorch.org/t/nn-parameter-not-getting-updated-not-sure-about-the-usage/157226 I had to remove the cuda(device=opt.gpu_ids[0]) because it is supposed to get the device that the model is put on.
https://stackoverflow.com/questions/73074622/
How do I convert a 3*1 vector into a 2*2 lower triangular matrix in pytorch
I have created a network in pytorch, whose output is B*N*H*W. I want that N is equal to 3 and then convert the output into a 2*2 lower trangular matrix with a upper zero in the 2nd demension. There may be two ways to achieve that. class Net(nn.Module): def __init__(self, in_ch=3, out_ch=N): super()....
Try this: You can easily calculate N from len(a) as N*(N+1)/2 = len(a) => N Here is the numpy version: a = np.array([2.3, 5.1, 6.3]) N = 2 c = np.zeros((N, N)) c[np.tril_indices(N)] = a Output: c >array([[2.3, 0. ], [5.1, 6.3]]) Here is the pytorch version: a = torch.tensor([2.3, 5.1, 6.3]) c = torch...
https://stackoverflow.com/questions/73075280/
Why this operation results in a tensor full of 'nan'?
err = reduce((mu_students - teacher_pred)**2, 'b h w vec -> b h w', 'sum') where mu_students and teacher_pred are 2 tensors with size (1,14,14,256). The two tensors do not contain nan values before the reduce. Moreover, this exact same operation work fine with the previous layer of the network, when mu_students and ...
Could you provide more about the function reduce and the input tensors? By assuming that; (1) reduce is from einops and written as from einops import reduce as reduce (2) mu_students and teacher_pred is random tensors, when I try this code on Google Colab, it works well without NaN. !pip install einops from einops ...
https://stackoverflow.com/questions/73082317/
AssertionError: If capturable=False, state_steps should not be CUDA tensors
I get this error while loading model weights of a previous epoch on Google colab. I'm using PyTorch version 1.12.0. I can't downgrade to a lower version as there are external libraries that Im using that require Pytorch 1.12.0 Thanks!
If you are using pytorch 1.12.0 with cuda binaries 11.6/11.7 then on your shell or command prompt, paste the following; pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu116 The Adam Optimizer regression was removed in the updated torch ve...
https://stackoverflow.com/questions/73095460/
Error happend when import torch (pytorch)
Try to use pytorch, when I do import torch --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-2-eb42ca6e4af3> in <module> ----> 1 import torch C:\Big_Data_app\Anaconda3\lib\site-packages\t...
I solved the problem. Just reinstall your Anaconda. !!Warning!!: you will lose your lib. Referring solution: Problem with Torch 1.11
https://stackoverflow.com/questions/73098560/
Pytorch-Lightning Misconfiguration Exception; The closure hasn't been executed
I have been trying to train a torch.nn.TransformerEncoderLayer using the standard Pytorch-Lightning Trainer class. Before the first epoch even starts, I face the following error: MisconfigurationException: The closure hasn't been executed. HINT: did you call optimizer_closure() in your optimizer_step hook? It could als...
You are right. This happens because the special optimizer you have does not call the closure when passing it to the .step() method. But Lightning relies on this because it calls the step method like this: optimizer.step(training_step_closure) where training_step_closure consists of essentially executing the LightningM...
https://stackoverflow.com/questions/73111496/
module 'torch' has no attribute 'frombuffer' in Google Colab
data_root = os.path.join(os.getcwd(), "data") transform = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) fashion_mnist_dataset = FashionMNIST(data_root, download = True, train = True, transform = transform) Error Message /usr/local/lib/python3.7/dist-packages/torchvis...
I tried your code in my Google Colab by adding the codes (to import the libraries) below, but it works well without errors. import os from torchvision import transform from torchvision.datasets import FashionMNIST I used torchvision 0.13.0+cu113 google-colab 1.0.0 Runtime GPU (when I set "None," it al...
https://stackoverflow.com/questions/73116818/
how to multiply three arrays with different dimension in PyTorch
enter image description here L array dimension is (d,a) ,B is (a,a,N) and R is (a,d). By multiplying these arrays I have to get an array size of (d,d,N). How could I implement this is PyTorch
A possible and straightforward approach is to apply torch.einsum (read more here): >>> torch.einsum('ij,jkn,kl->iln', L, B, R) Where j and k are the reduced dimensions of L and R respectively. And n is the "batch" dimension of B. The first matrix multiplication will reduce L@B (let this interme...
https://stackoverflow.com/questions/73119792/
Force a neural network to have 0-sum outputs
I have a pytorch neural net with n-dimensional output which I want to have 0-sum during training (my training data, i.e. the true outputs, have 0 sum). Of course I could just add a line computing the sum s and then subtract s/n from each element of the output. But this way, the network would be driven even less to actu...
Your approach with "explicitly substracting the mean" is the correct way. The same way we use softmax to nicely parametrise distributions, and you could complain that "this makes the network not learn about probability even more!", but in fact it does, it simply does so in its own, unnormalised spac...
https://stackoverflow.com/questions/73122031/
Logging in Custom Handler for TorchServe
I have written a custom handler for an DL model using torch-serve and am trying to understand how to add manual log messages to the handler. I know that I can simply print any messages and it will show them within the MODEL_LOG logger at level INFO. What if I want to add a custom message at DEBUG level or ERROR level? ...
I am trying to do something similar. I found example logger usage in base_handler.py, where the logger is initialized on line 23 as: logger = logging.getLogger(__name__) and used in several places in the rest of the source file, typically as: logger.debug() or logger.warning(), etc. I am assuming that these messages en...
https://stackoverflow.com/questions/73136920/
Implement "same" padding for convolution operations with dilation > 1, in Pytorch
I am using Pytorch 1.8.1 and although I know the newer version has padding "same" option, for some reasons I do not want to upgrade it. To implement same padding for CNN with stride 1 and dilation >1, I put padding as follows: padding=(dilation*(cnn_kernel_size[0]-1)//2, dilation*(cnn_kernel_size[1]-1)//2...
I figured it out! The reason that I ended up with the wrong dimension was that I didn't put a numeric value for padding. I gave it the numeric value of dilation and based on that it calculate itself the value for padding as padding=(dilation*(cnn_kernel_size[0]-1)//2, dilation*(cnn_kernel_size[1]-1)//2)) I think Pytorc...
https://stackoverflow.com/questions/73149873/
Can I create a color image with a GAN consisting of only FC layers?
I understand that in order to create a color image, three channel information of input data must be maintained inside the network. However, data must be flattened to pass through the linear layer. If so, can GAN consisting of only FC layer generate only black and white images?
Your fully connected network can generate whatever you want. Even three channel outputs. However, the question is: does it make sense to do so? Flattened your input will inherently lose all kinds of spatial and feature consistency that is naturally available when represented as an RGB map. Remember that an RGB image ca...
https://stackoverflow.com/questions/73161416/
Deep Neural Network in Python with 3 inputs and 3 outputs
I would like to implement a deep neural network in Python (preferably PyTorch, but TensorFlow is also possible) which predicts the next location and the time of the arrival at that location. For the raw data I have a csv file with a sequence of three values: latitude, longitude, and time: 39.984702,116.318417,2008-10-2...
Just a tip, for the time I would transform it into an Epoch Unix Timestamp.
https://stackoverflow.com/questions/73166253/
"PackagesNotFoundError: The following packages are not available from current channels:" While Installing PyTorch in Anaconda
When trying to install PyTorch inside an Anaconda environment with the command conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge, I get the error: PackagesNotFoundError: The following packages are not available from current channels: - pytorch - cudatoolkit=11.6 - torchaudio...
You have a 32 bit version of anaconda. You need to uninstall and install a 64 bit version to have access to these packages
https://stackoverflow.com/questions/73212317/
Custom Operations on Multi-dimensional Tensors
I am trying to compute the tensor R (see image) and the only way I could explain what I am trying to compute is by doing it on a paper: o = torch.tensor([[[1, 3, 2], [7, 9, 8], [13, 15, 14], [19, 21, 20], [25, 27, 26]], [[31, 33, 32], [37, 39, 38], [43, 45, 44], [49, 51, 50], [55, 57, 56]]]) p = torch.tensor([[[19, 21...
You can construct a helper tensor containing the resulting values sum(o) + o' + p': >>> v = o.sum(2, True) + o_prime[...,None] + o_prime[...,None] tensor([[[ 7.2000], [ 25.4000], [ 43.6000], [ 61.8000], [ 80.0000]], [[ 98.2000], [116.4000], [134.6...
https://stackoverflow.com/questions/73217240/
Constant training and test accuracy in GCNConv
I am new to pytorch and I'm trying to write a classifier for graph data. I have a dataset of 91 adj matrices (two classes in ratio 50/41, correlation matrices obtained from fMRI data). Currently I am struggling with classification task: my training and test accuracy doesn't change, although loss looks normal (?). Here'...
Try to add nn.Sigmoid() on top of self.lin output and remove dropout
https://stackoverflow.com/questions/73218977/
Unable to train a self-supervised(ssl) model using Lightly CLI
I am unable to train a self-supervised(ssl) model to create image embeddings using the lightly cli: Lightly Platform Link. I intend to select diverse example from my dataset to create an object detection model further downstream and the image embeddings created with the ssl model will help me to perform Active Learning...
The error is from an incompatibility with the latest PyTorch Lightning version (version 1.7 at the time of this writing). A quick fix is to use a lower version (e.g. 1.6). We are working on a fix :) Let me know in case that does not work for you!
https://stackoverflow.com/questions/73233965/
Given a torch DataLoader, how can I create another DataLoader which is a subset
Given an torch.utils.data.dataloader.DataLoader (let's say stored as variable data_loader_original), how can I create a new torch.utils.data.dataloader.DataLoader which contains a subset of data_loader_original? I've seen this post how to adjust dataloader and make a new dataloader?, but I don't want to take a subset o...
I'm not sure how can you split the subset, for the simple version, the snipcode below may help: import torch from torch.utils.data import DataLoader bs = 50 shuffle = False num_workers = 0 dataset = torch_dataset() data_loader_original = DataLoader(dataset, batch_size=bs, shuffle=shuffle) def create_subset_data_loade...
https://stackoverflow.com/questions/73243683/
Predict with pytorch lightning when using BCEWithLogitsLoss for training
I'm trying to see how my trained model would predict a single instance of y and have of list of predicted and actual y. It seems I'm missing a few steps and I'm not sure how to implement the predict_step, here is what I currently have: mutag = ptgeom.datasets.TUDataset(root='.', name='MUTAG') train_idx, test_idx = tra...
The crux here is that you use F.binary_cross_entropy_with_logits in your training_step (for numerical stability I suppose). This means that nn.Sigmoid has to be applied to your output both in validation_step and predict_step as the operation is not part of forward(). Check this for more information. Notice that you may...
https://stackoverflow.com/questions/73250651/
How to pad the left side of a list of tensors in pytorch to the size of the largest list?
In pytorch, if you have a list of tensors, you can pad the right side using torch.nn.utils.rnn.pad_sequence import torch 'for the collate function, pad the sequences' f = [ [0,1], [0, 3, 4], [4, 3, 2, 4, 3] ] torch.nn.utils.rnn.pad_sequence( [torch.tensor(part) for part in f], batch_first=True ) ...
You can reverse the list, do the padding, and reverse the tensor. Would that be acceptable to you? If yes, you can use the code below. torch.nn.utils.rnn.pad_sequence([ torch.tensor(i[::-1]) for i in f ], # reverse the list and create tensors batch_first=True) ...
https://stackoverflow.com/questions/73256206/
mat1 and mat2 shapes cannot be multiplied Pytorch lightning CNN
I'm working on a CNN for a project using Pytorch lightning. I don't know why am I getting this error. I've check the size of the output from the last maxpool layer and it is (-1,10,128,128). The error is for the linear layer. Any help would be appreciated. def __init__(self): super().__init__() self.model =...
You have to match the dimension by putting the view method between the feature extractor and the classifier. And it would be better not to use the relu function in the last part. Code: import torch import torch.nn as nn class M(nn.Module): def __init__(self): super(M, self).__init__() self.feature_...
https://stackoverflow.com/questions/73257506/
Huggingface: How to use bert-large-uncased in hugginface for long text classification?
I am trying to use the bert-large-uncased for long sequence ending, but it's giving the error: Code: from transformers import BertTokenizer, BertModel tokenizer = BertTokenizer.from_pretrained('bert-large-uncased') model = BertModel.from_pretrained("bert-large-uncased") text = "Replace me by any text yo...
I might be wrong, but I think you already have your answers here: How to use Bert for long text classification? Basically you will need some kind of truncation on your text, or you will need to handle it in chunks, and stick them back together. Side note: large model is not called large because of the sequence length. ...
https://stackoverflow.com/questions/73259489/