instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
How PyTorch model layer weights get initialized implicitly?
I basically defined a model with a Conv2D and linear layer with PyTorch and trained it with a sample dataset. The model seems to run and converge. But I am wondering I did not explicitly initialize the model layer weights (normal or Xavier). Does that mean when I call model.train() before each epoch training, the layer...
The type of initialization depends on the layer. You can check it from the reset_parameters method or from the docs as well. For both linear and conv layers, it's He initialization (torch.nn.init.kaiming_uniform_). It's mentioned in the documentation as The values are initialized from U(−sqrt(k),sqrt(k)). For embeddi...
https://stackoverflow.com/questions/65606553/
RuntimeError: Given input size: (40x256x1). Calculated output size: (40x253x-2). Output size is too small
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.autograd import Variable from sklearn import preprocessing batch_size = 32 num_classes = 8 epochs = 10 ...
I'm assuming you are working with images. In that case, there are several issues with your code. Also reading from the comments, there are a couple of things I need to clarify. I think the most important is the fact you've switched up the axes on the input shape. Unlike in Tensorflow, PyTorch multi-channel maps are sh...
https://stackoverflow.com/questions/65616189/
How to replicate PyTorch normalization in OpenCV or NumPy?
I need to replicate PyTorch image normalization in OpenCV or NumPy. Quick backstory: I'm doing a project where I'm training in PyTorch but will have to inference in OpenCV due to deploying to an embedded device where I won't have the storage space to install PyTorch. After training in PyTorch and saving a PyTorch grap...
This probably would be helpful If you look at actual implementation of torchvision.transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], ) Below block is what it actually does: import numpy as np from PIL import Image MEAN = 255 * np.array([0.485, 0.456, 0.406]) STD = 255 * n...
https://stackoverflow.com/questions/65617755/
what is Pytorch's add_module()?
I stumbled upon the method add_module() in a Pytorch model. The doc only states Adds a child module to the current module. The module can be accessed as an attribute using the given name. I don't understand what "adding a child module" means. How is it different from just setting a pointer to the other modu...
As mentioned here: https://discuss.pytorch.org/t/when-to-use-add-module-function/10534 In general, you won’t need to call add_module. One potential use case is the following: class Net(nn.Module): def __init__(self): super(Net, self).__init__() modules = [...] # some list of modules for module ...
https://stackoverflow.com/questions/65619076/
How to merge two torch.utils.data dataloaders with a single operation
I have two dataloaders and I would like to merge them without redefining the datasets, in my case train_dataset and val_dataset. train_loader = DataLoader(train_dataset, batch_size = 512, drop_last=True,shuffle=True) val_loader = DataLoader(val_dataset, batch_size = 512, drop_last=False) Wanted result: train_loader = ...
Data loaders are iterators, you can implement a function that returns an iterator which yields the dataloaders' content, one dataloader after the other. Given a number of iterators itrs, it would iterate over each iterator and in turn iterate over each iterator yielding one batch at a time. A possible implementation wo...
https://stackoverflow.com/questions/65621414/
Input batch size doesn't match target batch size in CrossEntropyLoss function
I've been trying to build a model from scratch to recognize handwritten digits from the MNIST dataset with the help of PyTorch and the DataLoader class from FastAI. So far, I've been using a linear model that has 784 inputs (a flattened grayscale 28 by 28 handwritten digit image tensor) and 10 outputs. simple_linear = ...
The torch.nn.CrossEntropyLoss function doesn't take targets as one-hot-encodings! Just pass the label index, so basically: train_y = torch.tensor([0] * len(zeros) + [1] * len(ones) + [2] * len(twos) + [3] * len(threes) + [4] * len(fours) + [5] * len(fives) + [6] * len(sixes) + [7] * ...
https://stackoverflow.com/questions/65631215/
Loading the pre-trained model of torch and sentence_transformers when running in a docker container failing
I am getting below error while loading the pre-trained model of torch and sentence_transformers("distilbert-base-nli-stsb-mean-tokens") when trying to run in a docker container. Error: Invalid value for '-A' / '--app': Unable to load celery application. While trying to load the module app.celery the follow...
sentence-transformers downloads and stores model in ~/.cache directory (or whatever the cache_folder evaluates to be in - https://github.com/UKPLab/sentence-transformers/blob/a13a4ec98b8fdda83855aca7992ea793444a207f/sentence_transformers/SentenceTransformer.py#L63). For you this looks like the /nonexistant directory. T...
https://stackoverflow.com/questions/65633918/
Problems identifying images in pytorch
I am really new at deep learning and I am studying how to properly run neural networks using pytorch. Currently I am trying to read a dataset of images using the following code: from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms from torchvision import transforms, utils trans...
I finally found the problem. This post was very useful. The gist of it is that PIL has problems importing images of certain sizes (I do not have all the details about this). At the end I use cv2 to import the pgm images one by one and then convert them into 32-bit ndarrays to export them in jpeg format. Here is my code...
https://stackoverflow.com/questions/65636906/
Batch normalization makes training worse
I am trying to implement the batch normalization with Pytorch and use a simple fully connected neural network to approximate a given function. The code is as follows. The result shows that the neural network without the batch normalization performs better than that with the batch normalization technique. This means tha...
To provide an alternate view to the answer that Khalid linked in the comments, which puts a stronger focus on generalization performance rather than training loss, consider this: Batch Normalization has been postulated to have a regularizing effect. Luo et al. look at BN as a decomposition into population normalization...
https://stackoverflow.com/questions/65637165/
What's the best way of handling the GAN training output?
Supervising the training of GANs usually involves outputting not only metrics, but also images at a certain interval of epochs. My application also involves printing tables. I use jupyter notebooks, but just printing it all on the notebooks makes each notebook for each experiment way too large (+100 MB), and the intern...
Well It's a matter of preference, how someone likes to have it. When I trained a GAN, I handled it in the following way, for the loss and other such values I printed them simply on the notebook per epoch manner as we would do with any other models along with that I would generate an image made by the generator and save...
https://stackoverflow.com/questions/65637608/
Validation and training loss per batch and epoch
I am using Pytorch to run some deep learning models. I am currently keeping track of training and validation loss per epoch, which is pretty standard. However, what is the best way of going about keeping track of training and validation loss per batch/iteration? For training loss, I could just keep a list of the loss a...
Well, you're right that's the way to do it "run the whole validation step after each training batch and keeping track of those" and also as you've thought it's pretty time-consuming and would be overkill. However, If that's something you really need then there's a way you can do it. What you can do is, let's ...
https://stackoverflow.com/questions/65638101/
pytorch runs slow when data are pre-transported to GPU
I have a model written in pytorch. Since my dataset is small, I can directly load all of the data to GPU. However, I found the forward speed becomes slow if I do so. The following is a runnable example. Specifically, I have the model: import numpy as np from time import time import random import torch import torch.nn a...
I played around with the code a little bit, and I think the problem is that you are measuring times for both cases in the same run. Here is my boiled down version of your code since your model crushed my GPU memory: class DGCNN(nn.Module): def __init__(self, num_layers): super(DGCNN, self).__init__() ...
https://stackoverflow.com/questions/65642697/
Getting an error while training Resnet50 on Imagenet at 14th Epoch
I am training Resnet50 on imagenet using the script provided from PyTorch (with a slight trivial tweak for my purpose). However, I am getting the following error after 14 epochs of training. I have allocated 4 gpus in the server I'm using to run this. Any pointers as to what this error is about would be appreciated. Th...
It is difficult to tell what the problem is just by looking at the error you have posted. All we know is that there was an issue reading the file at '/data/users2/oiler/github/imagenet-data/val/n02102973/ILSVRC2012_val_00009130.JPEG'. Try the following: Confirm the file actually exists. Confirm that it is infact a val...
https://stackoverflow.com/questions/65668608/
Difference between CrossEntropyLoss and NNLLoss with log_softmax in PyTorch?
When I am building a classifier in PyTorch, I have 2 options to do Using the nn.CrossEntropyLoss without any modification in the model Using the nn.NNLLoss with F.log_softmax added as the last layer in the model So there are two approaches. Now, what approach should anyone use, and why?
They're the same. If you check the implementation, you will find that it calls nll_loss after applying log_softmax on the incoming arguments. return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction) Edit: seems like the links are now broken, here's the C++ implementation which shows...
https://stackoverflow.com/questions/65669511/
Loading a single graph into a pytorch geometric data object for node classification
I have one graph, defined by 4 matrices: x (node features), y (node labels), edge_index (edges list) and edge_attr (edge features). I want to create a dataset in Pytorch Geometric with this single graph and perform node-level classification. It seems that just wrapping these 4 matrices into a data object fails, for som...
For node classification: Create custom dataset. class CustomDataset(InMemoryDataset): def __init__(self, root, transform=None, pre_transform=None): super(CustomDataset, self).__init__(root, transform, pre_transform) self.data, self.slices = torch.load(self.processed_paths[0]) @property ...
https://stackoverflow.com/questions/65670777/
Pytorch BatchNorm3d / InstanceNorm3d not working when data size (1,C,1,1,1)
I'm training a neural network in PyTorch which at some point has a BatchNorm3d(C). Normally, I'm training it with a batch size of 1, and the input of this specific level will then be of shape (1, C, 1, 1, 1). Unfortunately, the BatchNorm then fails with the error message: ValueError: Expected more than 1 value per cha...
All these normalization layers keep running estimates of the mean and variance of your data over the batch dimension (see doc). Since the variance is computed with the unbiased estimator (notice the n-1 in the denominator), the computation cannot work with less than 2 data points. Therfore, you need a batch size of at ...
https://stackoverflow.com/questions/65682794/
Is it possible to save Tensorboad session?
I'm using Tensorboard and would like to save and send my report (email outside my organization), without losing interactive abilities. I've tried to save it as a complete html but that didn't work. Anyone encountered the same issue and found a solution?
Have you seen tensorboard.dev? This page allows you to host your tensorboard experiment & share it with others using a link (it's still interactive) for free. Also you can use it from the command line; try this from your CLI for more information: $ tensorboard dev --help
https://stackoverflow.com/questions/65683052/
TypeError: 'torch.dtype' object is not callable. how to call this function?
How to call this torch.dtype? because here the error shows it's not callable. before I used floatTensor and it shows the error like this can't convert np.ndarray of type numpy.object_ and now I using float64 it showing the error 'torch.dtype' object is not callable. please help with this issue. import torch a = tor...
torch.float64 is a dtype object and not a function so it cannot be called. To make it into a double float (or at least to make sure it is), I would instead call: y_train = torch.from_numpy(y_train).double().cuda()
https://stackoverflow.com/questions/65696312/
How to get logits as neural network output
Simple and short question. I have a network (Unet) which performs image segmentation. I want the logits as the output to feed into the cross entropy loss (using pytorch). Currently my final layer looks as so: class Logits(nn.Sequential): def __init__(self, in_channels, n_class ...
When people talk about "logits" they usually refer to the "raw" n_class-dimensional output vector. For multi-class classification (n_class > 2) you want to convert the n_class-dimensional vector of raw "logits" into a n_class-dim probability vector. That is, you want prob = f(logits) wi...
https://stackoverflow.com/questions/65703071/
Using tensordot with torch.sparse tensors
Is it possible to use a similar method as "tensordot" with torch.sparse tensors? I am trying to apply a 4 dimensional tensor onto a 2 dimensional tensor. This is possible using torch or numpy. However, I did not find the way to do it using torch.sparse without making the sparse tensor dense using ".to_de...
Your specific tensordot can be cast to a simple matrix multiplication by "squeezing" the first two and last two dimensions of tensor4D. In short, what you want to do is raw = tensor4D.view(nb_x*nb_y, nb_x*nb_y) @ inp.flatten() out = raw.view(nb_x, nb_y) However, since view and reshape are not implemented for...
https://stackoverflow.com/questions/65703930/
Pytorch's Autograd does not support complex matrix inversion, does anyone have a workaround?
Somewhere in my loss function, I invert a complex matrix of size 64*64. Although complex matrix inversion is supported for torch.tensor, the gradient cannot be computed in the training loop as I get this error: RuntimeError: inverse does not support automatic differentiation for outputs with complex type. Does anyone h...
You can do the inverse yourself using the real-valued components of your complex matrix. Some linear algebra first: a complex matrix C can be written as a sum of two real matrices A and B (j is the sqrt of -1): C = A + jB Finding the inverse of C is basically finding two real valued matrices x and y such that (A + j...
https://stackoverflow.com/questions/65712154/
Zero diagonal of a PyTorch tensor?
Is there a simple way to zero the diagonal of a PyTorch tensor? For example I have: tensor([[2.7183, 0.4005, 2.7183, 0.5236], [0.4005, 2.7183, 0.4004, 1.3469], [2.7183, 0.4004, 2.7183, 0.5239], [0.5236, 1.3469, 0.5239, 2.7183]]) And I want to get: tensor([[0.0000, 0.4005, 2.7183, 0.5236], ...
I believe the simplest would be to use torch.diagonal: z = torch.randn(4,4) torch.diagonal(z, 0).zero_() print(z) >>> tensor([[ 0.0000, -0.6211, 0.1120, 0.8362], [-0.1043, 0.0000, 0.1770, 0.4197], [ 0.7211, 0.1138, 0.0000, -0.7486], [-0.5434, -0.8265, -0.2436, 0.000...
https://stackoverflow.com/questions/65712349/
RuntimeError: Given groups=1, weight of size [16, 1, 3, 3], expected input[16, 3, 1, 28] to have 1 channels, but got 3 channels instead
I know my images have only 1 channel so the first conv layer is (1,16,3,1) , but I have no idea why I got such an error. Here is my code (I post only the related part). org_x = train_csv.drop(['id', 'digit', 'letter'], axis=1).values org_x = org_x.reshape(-1, 28, 28, 1) org_x = org_x/255 org_x = np.ar...
I tried a small demo with your code. and it works fine until your code had x = x.view(-1, 64*14*14) and input shape of torch.Size([1, 1, 28 ,28]) import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self...
https://stackoverflow.com/questions/65719005/
Pytorch CUDA error: no kernel image is available for execution on the device on RTX 3090 with cuda 11.1
If I run the following: import torch import sys print('A', sys.version) print('B', torch.__version__) print('C', torch.cuda.is_available()) print('D', torch.backends.cudnn.enabled) device = torch.device('cuda') print('E', torch.cuda.get_device_properties(device)) print('F', torch.tensor([1.0, 2.0]).cuda()) I get this:...
Found a fix for my problem here: https://github.com/pytorch/pytorch/issues/31285#issuecomment-739139454 pip install --pre torch torchvision -f https://download.pytorch.org/whl/nightly/cu110/torch_nightly.html -U Then my code snippet gives: A 3.7.5 (default, Nov 7 2019, 10:50:52) [GCC 8.3.0] B 1.8.0.dev20210115+cu110...
https://stackoverflow.com/questions/65739700/
Reshaping function in numpy
I am trying to reshape data for image classification purpose. I want to convert shape (32,32,3) to (1,3,32,32). I have used two ways for the reshaping purpose and got different results. The first one is numpy reshape method. The other code is written by me. def res(t): n = np.zeros((3,32,32)) for j in range(3)...
This is what you want to do with np.reshape after transpose - new = original.transpose(2,0,1).reshape(1,3,32,32) #(32,32,3)->(3,32,32)->(1,3,32,32) ##OR## new = original.transpose(2,0,1)[None,...] #(32,32,3)->(3,32,32)->(1,3,32,32) Full code with a comparison of results between your function and the tra...
https://stackoverflow.com/questions/65745440/
How can I create a tensor of batch batch_size of uniformly distributed values between -1 and 1?
The title pretty much sums it, I'm trying to implement a GAN: How can I create a tensor of batch batch_size of uniformly distributed values between -1 and 1 with pytorch? def create_latent_batch_vectors(batch_size, latent_vector_size, device): ''' The function creates a random batch of latent vectors with random values...
Let us first define an uniform distribution with a low-range as -1 and high-range as +1 dist = torch.distributions.uniform.Uniform(-1,1) sample_shape = torch.Size([2]) dist.sample(sample_shape) >tensor([0.7628, 0.3497]) This is a tensor of shape 2 (sample_shape). It doesn't have batch_shape. Let's check: dist.batch...
https://stackoverflow.com/questions/65745441/
Zeroing the diagonal of a matrix by multiplying by (1-I)
I have a tensor, lets say like this: tensor([[2.7183, 0.4005, 2.7183, 0.5236], [0.4005, 2.7183, 0.4004, 1.3469], [2.7183, 0.4004, 2.7183, 0.5239], [0.5236, 1.3469, 0.5239, 2.7183]]) And I want to zero its main diagonal by multiplying it by (1-I), meaning by 1 minus the identity matrix. How can I do this in...
torch.eye will be helpful for generating identity matrix import torch x = torch.tensor([[2.7183, 0.4005, 2.7183, 0.5236], [0.4005, 2.7183, 0.4004, 1.3469], [2.7183, 0.4004, 2.7183, 0.5239], [0.5236, 1.3469, 0.5239, 2.7183]],dtype=torch.float32) y = 1-torch.eye(x.size()[0],dtype=torch.float32) #only if x i...
https://stackoverflow.com/questions/65746836/
ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' on matplotlib import
I'm trying to run a simple testfile on a remote Server. But it throws a numpy error for matplotlib.pyplot. Here is the code import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) x, y = np.random.randn(2, 100) print('x') print(x) print('y') print(y) fig...
According to the site given by the library numpy: to fix the error you need to check couple things that commonly gives this error: 1- Check if you are using the right version of python and the right version of numpy, check the documentation fo further information.(you might also have multiple versions of python that ca...
https://stackoverflow.com/questions/65749606/
PyTorch out of GPU memory in test loop
For the following training program, training and validation are all ok. Once reach to Test method, I have CUDA out of memory. What should I change so that I have enough memory to test as well. import torch from torchvision import datasets, transforms import torch.nn.functional as f class CnnLstm(nn.Module): def __i...
You should call .item() on your loss when appending it to the list of losses: loss = self.criterion(output, target) test_loss.append(loss.item()) This avoids accumulating tensors in a list which are still attached to the computational graph. I would say the same for your accuracy.
https://stackoverflow.com/questions/65757115/
PyTorch GPU memory management
In my code, I want to replace values in the tensor given values of some indices are zero, for example target_mac_out[avail_actions[:, 1:] == 0] = -9999999 But, it returns OOM RuntimeError: CUDA out of memory. Tried to allocate 166.00 MiB (GPU 0; 10.76 GiB total capacity; 9.45 GiB already allocated; 4.75 MiB free; 9.7...
It's hard to guess since we do not even know the sizes if the involved tensors, but your indexing avail_actions[:, 1:] == 0 creates a temporary tensor that does require memory allocation.
https://stackoverflow.com/questions/65757291/
Learning rate finder for CNNLstm model
I have CNNLstm model as follows. class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d( in_channels=3, out_channels=16, kernel_size=5, ...
One possibility is that instead of expanding the dims in the for loop you could pass the tensor into the forward function of the model and just use .unsqueeze(1) there. Like this print(data.shape) print(data.shape) data = torch.FloatTensor(data) just omit the expand dims...
https://stackoverflow.com/questions/65761728/
Pandas Dataframe to tensor
I have a dataframe with 3 columns (a date index, a price and a string symbol). It looks like that: Date Price Symbol 2019-01-02 39.480000 AAPL 2019-01-02 101.120003 MSFT 2019-01-02 62.023998 TSLA 2019-01-03 35.547501 AAPL 2019-01-03 97.400002 MSFT 2019-01-03 60.071999 TSLA I'm looking for some pan...
You can groupby the date column, convert the groups of Price to numpy arrays, and then convert this series to a tensor: import torch import pandas as pd prices = df.groupby(['Date'])['Price'].apply(np.array) my_tensor = torch.tensor(prices)
https://stackoverflow.com/questions/65767833/
2D times 2D equals a 3d pytorch tensor
Given two 2-D pytorch tensors: A = torch.FloatTensor([[1,2],[3,4]]) B = torch.FloatTensor([[0,0],[1,1],[2,2]]) Is there an efficient way to calculate a tensor of shape (6, 2, 2) where each entry is a column of A times each row of B? For example, with A and B above, the 3D tensor should have the following matrices: [[[...
Pytorch tensors implement numpy style broadcast semantics which will work for this problem. It's not clear from the question if you want to perform matrix multiplication or element-wise multiplication. In the length 2 case that you showed the two are equivalent, but this is certainly not true for higher dimensionality!...
https://stackoverflow.com/questions/65784125/
Where to implement pre-processing in PyTorch Lightning (e.g. tokenizing input text)
Is there a convention to implement some kind of predict() method in PyTorch Lightning that does pre-processing before performing the actual prediction using forward()? In my case, I have a text classifier consisting of an embedding layer and a few fully connected layers. The text needs to be tokenized before being pass...
Why do you use a LightningModule if the code should be for production? If the model is finished you only need to load the model from memory and define the preprocess steps. The repository you refer to have implemented the predict, and prepare_sample on top of the LightningModule. In my opinion pytorch-lightning is for ...
https://stackoverflow.com/questions/65785142/
tensorflow autodiff slower than pytorch's counterpart
I am using tensorflow 2.0 and trying to evaluate gradients for backpropagating to a simple feedforward neural network. Here's how my model looks like: def __init__(self, input_size, output_size): inputs = tf.keras.Input(shape=(input_size,)) hidden_layer1 = tf.keras.layers.Dense(30, activation='relu')(in...
def __init__(self,...): ... self.model.call = tf.function(self.model.call) ... you need use tf.function to wrap your model's call function.
https://stackoverflow.com/questions/65785966/
Open3D-ML and pytorch
I’m currently trying to work with open3d ML and Pytorch. I followed the installation guide given in the Open3D-ML github. However when I try to import open3d.ml.torch it sends me the following error : Exception: Open3D was not built with PyTorch support! I’m working with python 3.8 open3d 0.12.0 pytorch 1.6.0 cuda 10.1...
It does not support for Windows at the moment. You can install Ubuntu on WSL (Window Subsystem for Linux) on Windows OS, and install open3d-ml on ubuntu.
https://stackoverflow.com/questions/65794655/
Pytorch model 2D regression given an scalar input
I want to create a model to perform this regression: My dataset looks like: t,x,y 0.0,-,0.5759052335487023 0.01,-,- 0.02,1.1159124144549086,- 0.03,-,- 0.04,1.0054825084650338,0.4775267298487888 0.05,-,- I'm having some troubles with loss, dataset load, batch_size, and Net structure (I add one single layer to simplify...
After the line loss = loss(outputs, labels), loss is now a tensor, not a function anymore. Python does not allow you to have distinct objects with identical names. So after the first call, loss has become a tensor, and as the error says "tensors are not callable", so the second call fails
https://stackoverflow.com/questions/65812727/
How to initialize columns in hybrid sparse tensor
How initialize in pytorch hybrid tensor torch.sparse_coo_tensor (one dimension is sparse and other is not), which have the following dense representation? array([[1, 0, 5, 0], [2, 0, 6, 0], [3, 0, 7, 0], [4, 0, 8, 0]]) What should I put into the indices argument?
How to initialize Something like this: import torch indices = torch.tensor([[0, 0, 1, 1, 2, 2, 3, 3], [0, 2, 0, 2, 0, 2, 0, 2]]) tensor = torch.sparse_coo_tensor( indices, torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]), size=(4, 4) ) Given above: indices - first dimension specifies row, second column, where non-zero val...
https://stackoverflow.com/questions/65813122/
How to select indices according to another tensor in pytorch
The task seems to be simple, but I cannot figure out how to do it. So what I have are two tensors: an indices tensor indices with shape (2, 5, 2), where the last dimensions corresponds to indices in x and y dimension a "value tensor" value with shape (2, 5, 2, 16, 16), where I want the last two dimensions to...
What you could do is flatten the first three axes together and apply torch.gather: >>> grid.flatten(start_dim=0, end_dim=2).shape torch.Size([6, 16, 16]) >>> torch.gather(grid.flatten(0, 2), axis=1, indices) tensor([[[-0.8667, -0.8667], [-0.8667, -0.8667], [-0.8667, -0.8667]]]) As ...
https://stackoverflow.com/questions/65815668/
RuntimeError: Input tensor at index 3 has invalid shape [2, 2, 16, 128, 64] but expected [2, 4, 16, 128, 64]
Runtime error while finetuning a pretrained GPT2-medium model using Huggingface library in SageMaker - ml.p3.8xlarge instance. The finetuning_gpt2_script.py contains the below, Libraries: from transformers import Trainer, TrainingArguments from transformers import EarlyStoppingCallback from transformers import GPT2LMHe...
It could be related to a mismatch in the batch size (expecting a batch size of 4 but receiving a batch size of 2) as suggested here ? Solution provided is to set the parameter drop_last in your DataLoader like this: tain_text = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, drop_last=True)
https://stackoverflow.com/questions/65822014/
Pytorch Global Pruning is not reducing the size of the model
I am trying to Prune my Deep Learning model via Global Pruning. The original UnPruned model is about 77.5 MB. However after pruning, when I am saving the model, the size of the model is the same as the original. Can anyone help me with this issue? Below is the Pruning code:- import torch.nn.utils.prune as prune parame...
Prunning won't change the model size if applied like this. If you have a tensor, say something like: [1., 2., 3., 4., 5., 6., 7., 8.] And you prune 50% of data, so for example this: [1., 2., 0., 4., 0., 6., 0., 0.] You will still have 8 float values and their size will be the same. When prunning reduces model size? ...
https://stackoverflow.com/questions/65827031/
Pytorch/cuda : CPU error and map_location
I write this code to download my model : args = parser.parse_args() use_cuda = torch.cuda.is_available() state_dict = torch.load(args.model) model = Net() model.load_state_dict(state_dict) model.eval() if use_cuda: print('Using GPU') model.cuda() else: print('Using CPU') But my terminal returns the fol...
I'm assuming you saved the model on a computer with a GPU and are now loading it on a computer without one, or maybe you for some reason the GPU is not available. Also, which line is causing the error? The parameter map_location needs to be set inside torch.load. Like this: state_dict = torch.load(args.model, map_locat...
https://stackoverflow.com/questions/65842425/
Implementations and strategies for fast 2D interpolation from irregularly spaced points
Given a large (~10 million) number of irregularly spaced points in two dimensions, where each point has some intensity ("weight") associated with it, what existing python implementations are there for interpolating the value at: a specific point at some random position (i.e. point = (0.5, 0.8)) a large numbe...
Scipy is pretty good and I don't think that there are better solutions in Python, but I can add a couple things that might be helpful to you. First off, your idea of sorting the points is a really good one. The so-called "incremental algorithms" build the Delaunay by inserting vertices one at a time. The fir...
https://stackoverflow.com/questions/65847051/
RuntimeError: stack expects each tensor to be equal size
I apologize in advance in this was asked before. I genuinely did not understand the solution. MAX_LEN = 160 BATCH_SIZE = 16 EPOCHS = 10 class GPReviewDataset(data.Dataset): def __init__(self, review, target, tokenizer, max_len): self.review = review self.target = target self.tokenizer = tok...
try this instead add (padding = 'max_length') in encode_plus
https://stackoverflow.com/questions/65851195/
PyTorch how to do gathers over multiple dimensions
I'm trying to find a way to do this without for loops. Say I have a multi-dimensional tensor t0: bs = 4 seq = 10 v = 16 t0 = torch.rand((bs, seq, v)) This has shape: torch.Size([4, 10, 16]) I have another tensor labels that is a batch of 5 random indices in the seq dimension: labels = torch.randint(0, seq, size=[bs, s...
You can use fancy indexing here to select the desired portion of the tensor. Essentially, if you generate the index arrays conveying your access pattern beforehand, you can directly use them to extract some slice of the tensor. The shape of the index arrays for each dimension should be same as that of the output tensor...
https://stackoverflow.com/questions/65894166/
Is there a way to classify a set of data as a whole via Pytorch?
I'm currently dealing with a classification task on a CT dataset. In CT datasets, multiple slices belong to one single patient, while setting up my dataset, I arrange my data as follows: dataset/0/patient_1/1.png,2.png... dataset/0/patient_2/1.png,2.png... I wonder is there a way to let my network to classify by patien...
Each slice is a 2D image, while for each patient you have a 3D volume of CT voxels. If you want to work per-patient, rather than per-slice, you'll need to organize your data to output batches of 3D information (of shape batchxchannelxdepthxheightxwidth) and make your model process 3D information (e.g., using Conv3D ins...
https://stackoverflow.com/questions/65895418/
PyTorch GPU memory leak during inference
I am trying to encode documents sentence-wise with a huggingface transformer module. I'm using the very small google/bert_uncased_L-2_H-128_A-2 pretrained model with the following code: def pre_encode_wikipedia(model, tokenizer, device, save_path): document_data_list = [] for iteration, document in enumerate(wi...
Can you try replacing sentence[0].to('cpu') with cpu_sentence = sentence[0].to('cpu') See more info here https://pytorch.org/docs/stable/tensors.html#torch.Tensor.to
https://stackoverflow.com/questions/65906965/
ModuleNotFoundError: No module named 'torch.nn'; 'torch' is not a package on Mac OS
I am trying to get pytorch to work but I keep getting this error. ModuleNotFoundError: No module named 'torch.nn'; 'torch' is not a package I am using a Macbook, i've tried looking at the other answers on here but nothing is working. import torch import torchvision import torchvision.transforms as transforms transform...
Maybe you can check conda list to see if there is PyTorch installed. You should be able to run torch if you had installed PyTorch. Download link: https://pytorch.org/get-started/locally/ Just remember to install CUDA additionally if you want to use GPU instead of CPU.
https://stackoverflow.com/questions/65910782/
PyTorch RuntimeError: Tensor for argument #1 'self' is on CPU, but expected them to be on GPU
I'm using PyTorch for my Logistic Regression model but whenever I run the model summary I get an error RuntimeError: Tensor for 'out' is on CPU, Tensor for argument #1 'self' is on CPU, but expected them to be on GPU (while checking arguments for addmm) Code # Convert data to tensors X_train = torch.Tensor(X_train) y...
I had the same error. RuntimeError: Tensor for 'out' is on CPU, Tensor for argument #1 'self' is on CPU, but expected them to be on GPU (while checking arguments for addmm) Ensuring the model and its weights were on the GPU helped: model.to(device) where device is defined: device = "cuda" if torch.cuda.is_...
https://stackoverflow.com/questions/65914706/
Pytorch already installed using Conda but fails when called
I am trying to install pytorch for using BERT but when following the installation instructions found here: https://pytorch.org/get-started/locally/ I am getting an error. When I try and initalise the BERT model I get the following error: ImportError: BertForSequenceClassification requires the PyTorch library but i...
I had the same issue (same error msg), and after using conda list | grep torch I also found it is there. What worked for me is that I restarted the jupyter notebook kernel and the error is gone.
https://stackoverflow.com/questions/65921244/
Torch model forward with a diferent image size
I am testing some well known models for computer vision: UNet, FC-DenseNet103, this implementation I train them with 224x224 randomly cropped patches and do the same on the validation set. Now when I run inference on some videos, I pass it the frames directly (1280x640) and it works. It runs the same operations on diff...
It seems that the models that you are using have no linear layers. Because of this the output of the convolutional layers go straight into the softmax function. The softmax function doesn't take a specific shape for its input so it can take any shape as input. Because of this your model will work with any shape of imag...
https://stackoverflow.com/questions/65933454/
all pairwise dot product pytorch
Is there a built in function to calculate efficiently all pairwaise dot products of two tensors in Pytorch? e.g. input - tensor A (shape NxD) tensor B (shape NxD) output - tensor C (shape NxN) such that C_i,j = torch.dot(A_i, B_j) ?
Isn't it simply C = torch.mm(A, B.T) # same as C = A @ B.T BTW, A very flexible tool for matrix/vector/tensor dot products is torch.einsum: C = torch.einsum('id,jd->ij', A, B)
https://stackoverflow.com/questions/65935952/
Is there a way to figure out whether PyTorch model is on cpu or on the device?
I would like to figure out, whether the PyTorch model is on cpu or cuda in order to initialize some other variable as Torch.Tensor or Torch.cuda.Tensor depending on the model. However, looking at the output of the dir() function I see only .cpu(), .cuda(), to() methods which put the model on device, GPU or other device...
No, there is no such function for nn.Module, I believe this is because parameters could be on multiple devices at the same time. If you're working with a single device, a workaround is to check the first parameter: next(model.parameters()).is_cuda As described here.
https://stackoverflow.com/questions/65941179/
diffrence between a[:,:,0] and a[:][:][0]
Hi I was studying slicing in python and I found something strange and I don't understand import torch a = torch.tensor([ [ [1, 2, 3], [4, 5, 6] ], [ [7, 2, 3], [8, 5, 6] ] ]) >>> a[:][:][0] tensor([[1, 2, 3], [4, 5, 6]]) >>> a[:,:,0] tensor([[...
You can see the first, a[:][:][0], as several, chained calls to __getitem__. That means a[:][:][0] is roughly equivalent to this: b = a[:] c = b[:] d = c[0] Where d is the result. In your case, it returns the same thing as a[0], because a[:] == a. In contrast, a[:,:,0] will only call __getitem__ once with parameters s...
https://stackoverflow.com/questions/65945708/
How can I solve "torch.utils.ffi is deprecated. Please use cpp extensions instead" without downgrade pytorch version?
When I run the code below it shows me the error. ImportError: torch.utils.ffi is deprecated. Please use cpp extensions instead. I have been searching solution on the online. The problem is the code below working in old version of torch (0.4.1). I want to know whether it is possible to modify or replace this code for wo...
I am facing the same problem have just seen some useful information in: https://pytorch.org/tutorials/advanced/cpp_extension.html https://pytorch.org/docs/stable/cpp_extension.html To avoid downgrade the version of PyTorch, you should consider to use the following libraries while finding more details in the above lin...
https://stackoverflow.com/questions/65955378/
FastAi Learner changes the dataloader Why do they do it? How is this the right thing to do?
The code below shows that passing a dataloader to a learner changes it. This seems like a very odd behavior. Why is it done this way, what is the logic for the change and how can I turn it off? More importantly, the dataloader also has the val and test data in it. If the learner goes around changing it then it should b...
The ImageDataLoaders.from_name_func dataloader shuffles the dataset by default. You can pass it shuffle_train=False if you don't want to.
https://stackoverflow.com/questions/65958584/
Get hash value of a pytorch architecture?
I would like to automatically check whether a certain architecture has already been trained on a task. My thought is: If I can get a hash value of the architecture and store this value in a .json file, then I can check whether it has already been trained by checking whether the architecture's hash value is in the .json...
I think hashing the string representation of the model might be a solution to your problem. hash(str(model))
https://stackoverflow.com/questions/65964784/
PyTorch - Creating Federated CIFAR-10 Dataset
I'm training a neural network (doesn't matter which one) on CIFAR-10 dataset. I'm using Federated Learning: I have 10 models, each model having access to its own part of the dataset. At every time step, each model makes a step using its own data, and then the global model is an average of the model (this version is ba...
10% on CIFAR-10 is basically random - your model outputs labels at random and gets 10%. I think the problem lies in your "federated training" strategy: you cannot expect your sub-models to learn anything meaningful when all they see is a single label. This is why training data is shuffled. Think of it: if eac...
https://stackoverflow.com/questions/65976605/
Can I access the inner layer outputs of DeepLab in pytorch?
Using Pytorch, I am trying to implement a network that is using the pre=trained DeepLab ResNet-101. I found two possible methods for using this network: this one or torchvision.models.segmentation.deeplabv3_resnet101( pretrained=False, progress=True, num_classes=21, aux_loss=None, **kwargs) However, I might not ...
You can achieve this without too much trouble using forward hooks. The idea is to loop over the modules of your model, find the layers you're interested in, hook a callback function onto them. When called, those layers will trigger the hook. We will take advantage of this to save the intermediate outputs. For example, ...
https://stackoverflow.com/questions/65984686/
How to strip a pretrained network and add some layers to it using pytorch lightning?
I am trying to use transfer learning for an image segmentation task, and my plan is to use the first few layers of a pretrained model (VGG16 for example) as an encoder and then will add my own decoder. So, I can load the model and see the structure by printing it: model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet...
For 1): Initialize the ResNet in your LightningModule and slice it until the part that you need. Then add your own head after that, and define forward in the order that you need. See this example, based on the transfer learning docs: import torchvision.models as models class ImagenetTransferLearning(LightningModule): ...
https://stackoverflow.com/questions/66000358/
Unable to load weights from pytorch checkpoint after splitting pytorch_model.bin into chunks
I need to transfer a pytorch_model.bin of a pretrained deeppavlov ruBERT model but I have a file size limit. So I split it into chunks using python, transferred and reassembled in the correct order. However, the size of the file increased, and when I tried to load the resulting file using BertModel.from_pretrained(pyto...
Those who are new to this issue I just figured it out and save your time What is this error about? ==> When you run the model for the first time it downloads some files { pytorch_model.bin } and if your internet is broken accidentally between processes it will continue running the pipeline file without completely d...
https://stackoverflow.com/questions/66005027/
BERT embeddings in batches
I am following this post to extract embeddings for sentences and for a single sentence the steps are described as follows: text = "After stealing money from the bank vault, the bank robber was seen " \ "fishing on the Mississippi river bank." # Add the special tokens. ma...
You could do all the work you need using one function ( padding,truncation) encode_plus check the parameters: the docs The same you could do with a list of sequences batch_encode_plus docs
https://stackoverflow.com/questions/66013380/
torch matmul two matrix row by row
I want to find a decent way to write the below function in torch. Appreciate for clean solution to complete this. import torch a=torch.randn(3,100) b=torch.randn(3,100) row_num = a.size()[0] # 3 # Given two matrix with shape (n1,n2) # I want to have the row-wise `matmul` results which will result in a tensor with size...
The operation you are trying to do is essentially the values of a dot product (matmul, a @ b.T) which lie on its diagonal. You can get the same using torch.matmul or @ operator between a and b.T and then get the torch.diagonal - np.diagonal(a @ b.T) You can also use torch.einsum directly to get the same result - torch...
https://stackoverflow.com/questions/66015132/
How pytorch implements back propagation from the output layer to the input layer
I am having difficulty implementing the following functions. Assuming that we have trained a network model, I want to backpropagate from the output layer to the input layer (not the first layer) to obtain a new input data. I want to know if there is a function in pytorch or other existing functions that can achieve thi...
If you want the gradient w.r.t to the input, you can simply get it from the .grad: x.requires_grad_(True) # explicitly ask pytorch to estimate the gradient w.r.t x # forward pass: pred = model(x) # make a prediction loss = criterion(pred, y) # compute the loss # backward pass - compute gradients: loss.bacward() # n...
https://stackoverflow.com/questions/66020252/
How to convert PyTorch tensor to C++ torch::Tensor vice versa?
I want to receive a dictionary includes PyTorch Tensor in C++ module using pybind11, and return the result dictionary with some modification that includes C++ torch::Tensor back. As far as I was looking for, there seems no clear way to convert PyTorch Tensor to C++ Tensor, and C++ Tensor to PyTorch Tensor. For a last t...
PyObject * THPVariable_Wrap(at::Tensor t); at::Tensor& THPVariable_Unpack(PyObject* obj); Those two are what you are looking for i guess.
https://stackoverflow.com/questions/66024389/
NameError: name 'utils' is not defined in Pytorch
I have pytorch 1.7. The following code is same as from Pytorch's tutorial page for Object detection and finetuning. But I have error for the following line data_loader = torch.utils.data.DataLoader(dataset, batch_size=2, shuffle=True, num_workers=4, collate_fn=utils.collate_fn) as NameError: name 'utils' is not define...
I just put def collate_fn(batch): data_list, label_list = [], [] for _data, _label in batch: data_list.append(_data) label_list.append(_label) return torch.Tensor(data_list), torch.LongTensor(label_list) in my code and it works.
https://stackoverflow.com/questions/66028727/
take the output from a specific layer in pytorch
I have implemented an autoencoder in Pytorch and wish to extract the representations (output) from a specified encoding layer. This setup is similar to making predictions using sub-models that we used to have in Keras. However, implementing something similar in Pytorch looks a bit challenging. I tried forward hooks as ...
The simplest way is to explicitly return the activations you need: def forward(self,x): e1 = F.relu(self.enc1(x)) e2 = F.relu(self.enc2(e1)) e3 = F.relu(self.enc3(e2)) e4 = F.relu(self.enc4(e3)) e5 = F.relu(self.enc5(e4)) x = F.relu(self.dec1(e5)) x = F.relu(s...
https://stackoverflow.com/questions/66039520/
How to create a submodel from a pretrained model in pytorch without having to rewrite the whole architecture?
So, I have been working on neural style transfer in Pytorch, but I'm stuck at the point where we have to run the input image through limited number of layers and minimize the style loss. Long story short, I want to find a way in Pytorch to evaluate the input at different layers of the architecture(I'm using vgg16). I h...
Of course you can do that: import torch import torchvision pretrained = torchvision.models.vgg16(pretrained=True) features = pretrained.features # First 4 layers model = torch.nn.Sequential(*[features[i] for i in range(4)]) You can always print your model and see how it's structured. If it is torch.nn.Sequential (or...
https://stackoverflow.com/questions/66051641/
ValueError: Target size (torch.Size([10, 1])) must be the same as input size (torch.Size([10, 2]))
A binary classification problem with Batch Size = 10. Trying to use torch.nn.BCEWithLogitsLoss(). ~\Anaconda3\envs\notebook\lib\site-packages\torch\nn\functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight) 2578 2579 if not (target.size() == input...
Target size (torch.Size([1, 10])) must be the same as input size (torch.Size([10, 2])) Seems to me you have two issues: target size (a.k.a. ground truth tensor) should have the batch on the first axis: (1, 10). From what you've described you are dealing with a binary classification task not a multi-label (2-class) ...
https://stackoverflow.com/questions/66053295/
torch: minimally pad tensor such that num elements divisible by x
Suppose I have a tensor t of arbitrary ndim I want to pad (with zeroes) it such that a) I introduce the fewest possible # elements b) after padding, (t.numel() % x) == 0 Is there a better algorithm for doing this than find the largest dimension and increase it by 1 until condition (b) is satisfied? Maybe working code: ...
First off, simply adding one to the largest dimension until numel is divisible by x doesn't work in all cases. For example if the shape of t is (3, 2) and x = 9 then we would want to pad t to be (3, 3), not (9, 2). Even more concerning is that there's no guarantee that only one dimension needs to be padded. For example...
https://stackoverflow.com/questions/66055262/
compute accuracy of Band RNN
So I am trying to figure out how to compute the accuracy of a BandRNN. BandRnn is a diagonalRNN model with a different number of connections per neuron. For example: here C is the number of connections per neuron. My current model training is as follows: model = ModelLSTM(m, k).to(device) model.train() opt = torch.o...
I believe this line in your code is already attempting to calculate accuracy: acc = sum(logits == batch_y) * 1.0 / len(logits) Though you probably want to argmax the logits before comparing with the labels: preds = logits.argmax(dim=-1) acc = sum(preds == batch_y) * 1.0 / len(logits)
https://stackoverflow.com/questions/66065431/
ValueError: All bounding boxes should have positive height and width
Any help solving this will be highly appreciated. I have an idea why the error is happening, it is because the xmin == xmax and ymin == ymax which should not be. However I seem not to know how this is happening. Here is how I load my custom dataset with pytorch Dataset class. `class CustomDataset(torch.utils.data.Datas...
TLDR;you have to check your ground truth first and reassure that any zero_area boxes are discarded.. Imagine that what you provide as a bounding box is a zero_area box. Considering that the data format is [x1,y1,x2,y2] which actually indicates the [left,top..] and the [..,right,bottom] edge of the ground truth box, in ...
https://stackoverflow.com/questions/66068158/
Supplying weights to nn.functional.conv2d in PyTorch
I am trying to learn the weights of a 3x3 conv2d layer accepting 3 channels and outputting 3 channels. For this discussion consider bias=0 in each case. However, the weights of the conv layer are learned indirectly. I have a 2 layered Multi layer perception having 9 nodes in first layer and 9 in the second. The weights...
A convolution from 3 input channels to 3 output channels with kernel_size=3 has 81 weights (and not 9). You can reduce this number to 27 if you use groups=3. you can do the following: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.hyper = nn.Linear(9, 9) # output the required numb...
https://stackoverflow.com/questions/66088545/
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! when resuming training
I saved a checkpoint while training on gpu. After reloading the checkpoint and continue training I get the following error: Traceback (most recent call last): File "main.py", line 140, in <module> train(model,optimizer,train_loader,val_loader,criteria=args.criterion,epoch=epoch,batch=batch) File...
There might be an issue with the device parameters are on: If you need to move a model to GPU via .cuda() , please do so before constructing optimizers for it. Parameters of a model after .cuda() will be different objects with those before the call. In general, you should make sure that optimized parameters live in co...
https://stackoverflow.com/questions/66091226/
looking for an equivalent of Tensorflow normalization layer in Pytorch
I was using 'tf.keras.layers.experimental.preprocessing.Normalization'. This layer is cool since you can save weights in this layer to normalize any input data to this layer. However, I couldn't find any normalization layer in Pytorch. Is there a layer that functions the same role?
There is no built-in that achieves this is PyTorch. However, you can measure the mean and standard deviation yourself (keeping only the relevant axes), then use torchvision.transform.Normalize with those statistics. For instance in order to measure mean and std over the channels: >>> x = torch.rand(16, 3, 10, ...
https://stackoverflow.com/questions/66092092/
AllenNLP DatasetReader: only loads a single instance, instead of iterating over all instances in the training dataset
I am using AllenNLP to train a hierarchical attention network model. My training dataset consists of a list of JSON objects (eg, each object in the list is a JSON object with keys := ["text", "label"]. The value associated with the text key is a list of lists, eg: [{"text":[["i",...
If you are using allennlp>=v2.0.0, the lazy parameter in the DatasetReader constructor is deprecated. Therefore, your super().__init__(lazy) would be instead interpreted as the new constructor parameter max_instances, i.e. max_instances=True which is equivalent to max_instances=1.
https://stackoverflow.com/questions/66092443/
Storing a dictionary with random indices as keys and simulated values as values in hdf5 possibly using pytorch?
UPDATED QUESTION: Each entry in an nd-array (say Sim_nDArray) correspond to a combination of parameters chosen from 8D search space. I have used Sim_nDArray.ravel() to convert it to 1D equivalent. Since I can not search from ~100 million entries, I decided to choose ~1 million random entries. I have corresponding ~1 mi...
I don't use PyTorch, so can't comment on that (or run the entire code). Observations: I noticed 2 methods for Class Dataset are not indented properly: def __len__(self): and def __getitem__(self, index):. I assume that's an error from cut-n-paste to your SO post...but you should double check. I ran your code (after co...
https://stackoverflow.com/questions/66096415/
How to allow complex inputs, and complex weights to a Pytorch model?
Assume even the simplest model (taken from here) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self,...
As you normally did self.double(), I found self.type(dst_type) from https://pytorch.org/docs/stable/generated/torch.nn.Module.html In my case, self.type(torch.complex64) is working for me.
https://stackoverflow.com/questions/66099139/
Reducing size of pytorch library
I've made a conversation telegram bot with pytorch and I'm trying to host it onto Github. The large pytorch file prevents me from doing so as its too large and I get this error: remote: error: File env/lib/python3.8/site-packages/torch/lib/libtorch_cpu.dylib is 233.61 MB; this exceeds GitHub's file size limit of 100.00...
Do not host that file on github. Make a requirements.txt file and add required versions there, you can even fix version required to run your code. Whoever downloads it can create a virtual environment (venv) or a docker image and install it as pip install -r requirements.txt For example: requirements.txt https://downl...
https://stackoverflow.com/questions/66103345/
How to use a neural network (Pytorch- or Tensorflow-based) in Fortran?
Python is popular and optimal for neural network development and training. However, many scientific codes are written in the Fortran language. How I can call a trained network in my Fortran program?
It would not make sense. You are not training the network in Fortran, you are just trying to run the C++ or Python code from Fortran. You should abstract the training/inference from your Fortran code. You could do the orchestration in Fortran. Create your model in Python Expose your model thru an API that you can acce...
https://stackoverflow.com/questions/66107018/
GPU showing no speed up over CPU
I'm training a neural network with 100*100 hidden nodes, four inputs/one output, and batch size of 32, and I am seeing no speed improvement in using the GPU vs. CPU. I only have a limited data set (1067 samples, copied all to the GPU at the beginning), but I would have thought the 33 batches could have run in parallel,...
Chances are the time required for the data to get to the GPU negates the benefit of the GPU. In this case the size of the network seems so small that the CPU should be efficient enough and the speedup from the GPU shouldn't be that big. Also, GPUs are usually used for matrix computations in parallel, or in this case - ...
https://stackoverflow.com/questions/66112977/
Neural network graph visualization
I would like to generate visualization of my neural network (PyTorch or ONNX model) similar to this using Graphcore Poplar. I have looked in the documentation but I cannot find where this visualization feature is. How can I achieve such a task ? Is there any other existing library ?
that visualization is not part of the Graphcore Poplar software. It is "data art" generated by the team at GraphCore. It is a tough work and requires many hours to get to that fine quality, but if you are decided, I would suggest to start looking at graph visualization tools looking for "graph network vi...
https://stackoverflow.com/questions/66117949/
TypeError: 'NoneType' object cannot be interpreted as an integer
I want to classify cat and dog with pytorch. So I downloaded dataset from Kaggle, and separate train/validate set. I changed the file name from 00001.jpg to cat.00001.jpg.. But when I try to use enumerate(dataset), this error occurs: My dataset code is: class TrainImageFolder(Dataset): def __init__(self, path, tran...
I just had the same error, you forgot to return the length of the data in len function.
https://stackoverflow.com/questions/66122889/
How to detect source of under fitting and vanishing gradients in pytorch?
How to detect source of vanishing gradients in pytorch? By vanishing gradients, I mean then the training loss doesn't go down below some value, even on limited sets of data. I am trying to train some network, and I have the above problem, in which I can't even get the network to over fit, but can't understand the sourc...
You can use tensorboard with Pytorch to visualize the training gradients. Add the gradients to a tensorboard histogram during training. For example... Let: model be your pytorch model model_input be an example input to your model run_name be a string identifier for your training session from torch.utils.tensorboard ...
https://stackoverflow.com/questions/66137298/
Changing config and loading Hugging Face model fine-tuned on a downstream task
I am using HuggingFace models for TokenClassification task. I have the following label2id mapping. I am using version 3.3.0 of the library label2id = { "B-ADD": 4, "B-ARRESTED": 7, "B-CRIME": 2, "B-INCIDENT_DATE": 3, "B-SUSPECT": 9, "B-VICTI...
Once a part of the model is in the saved pre-trained model, you cannot change its hyperparameters. By setting the pre-trained model and the config, you are saying that you want a model that classifies into 15 classes and that you want to initialize with a model that uses 9 classes and that does not work. If I understan...
https://stackoverflow.com/questions/66148641/
PyTorch one of the variables needed for gradient computation has been modified by an inplace operation
I'm doing a policy gradient method in PyTorch. I wanted to move the network update into the loop and it stopped working. I'm still a PyTorch newbie so sorry if the explanation is obvious. Here is the original code that works: self.policy.optimizer.zero_grad() G = T.tensor(G, dtype=T.float).to(self.policy.device) loss...
This line, loss += -g * logprob, is what is wrong in your case. Change it to this: loss = loss + (-g * logprob) And Yes, they are different. They perform the same operations but in different ways.
https://stackoverflow.com/questions/66177532/
What distribution is used when you make a tensor with torch.Tensor constructor in Pytorch?
I typed and ran torch.Tensor(2, 3) in Google Colab. It did work but it returned an weird-valued 2x3 tensor which includes even nan. tensor([[3.8202e-36, 0.0000e+00, 3.9236e-44], [0.0000e+00, nan, 1.8750e+00]]) I searched Pytorch(1.7.1)'s tensor.Tensor Doc to find out what distribution the default constr...
I believe that torch.Tensor is identical to the torch.empty creation operator. It doesn't use a distribution to draw from, it's just a tensor filled with uninitialized values. Essentially used to allocate memory. >>> torch.empty(2, 3) tensor([[5.5699e-35, 0.0000e+00, 1.5975e-43], [1.3873e-43, 1.4574e-4...
https://stackoverflow.com/questions/66194534/
PyTorch installation issues on MacOS through Anaconda
I am trying to install PyTorch on my Macbook Pro. I had no issues installing NumPy or Matplotlib using the following commands: conda install numpy conda install matplotlib When I then import those into Python console, they work correctly. However, when I try to import PyTorch I get the following error: (myenv) $ % pyt...
OP indicates use of Python 3.9 from Anaconda, but the PyTorch installer tool explicitly notes that one must use Python from the Conda Forge channel: I have no issue with the following environment YAML: File: pytorch.yaml channels: - pytorch - conda-forge - defaults dependencies: - python=3.9 - pytorch - to...
https://stackoverflow.com/questions/66211541/
PyTorch - Where are kernels launched?
I need to get information about kernels that PyTorch launches. For example, a callstack information such as "main.py:24 -> ... -> callkernel.py:53" would be beneficial. Is there anyway I can gather this information out out a PyTorch application execution? I also am currently searching through the source...
To get a helpful stack trace, you would most likely need to build pytorch with debug symbols (build instructions are here). I'm not sure if there are any debug builds available to download. But a stack trace might not make very much sense without some background, so here's a general outline of where things are defined ...
https://stackoverflow.com/questions/66214106/
regarding the trick of using 1*1 convolution
I once read the following statement on using 1*1 convolution, which can help connect the input and output with different dimensions: For example, to reduce the activation dimensions (HxW) by a factor of 2, you can use a 1x1 convolution with a stride of 2. How to understand this example?
You can use a stride of 2. However, I wouldn't say this is a trick, not like a magic solution to retain information. You will lose half of the information. I wouldn't qualify this method as a pooling method either. The kernel size is one pixel high and one pixel wide, and will move (stride) two pixels at a time. As a c...
https://stackoverflow.com/questions/66218825/
How to parallelize a training loop ever samples of a batch when CPU is only available in pytorch?
I want to parallelize over single examples or batch of example (in my situation is that I only have cpus, I have up to 112). I tried it but I get a bug that the losses cannot have the gradient out of separate processes (which entirely ruins my attempt). I still want to do it and it essential that after the multiproessi...
Torch will use multiple CPU to parallelize operations, so your serial is maybe using multi-core vectorization. Take this simple example import torch c = 0; for i in range(10000): A = torch.randn(1000, 1000, device='cpu'); B = torch.randn(1000, 1000, device='cpu'); c += torch.sum(A @ B) No code is used to p...
https://stackoverflow.com/questions/66226135/
How to squeeze all but one torch dims?
torch.squeeze can convert the shape of a tensor to not have dimensions of size 1. I want to squeeze my tensor in all dimensions but one (in this example, not squeeze dim=0). All I can see in the doc is dim (int, optional) – if given, the input will be squeezed only in this dimension I want the opposite: t = torch.zer...
Reshape will let you accomplish what you want to do: import torch t = torch.zeros(5, 1, 6, 1, 7, 1) t = t.reshape((5, 6, 1, 7)) >>> torch.Size([5, 6, 1, 7])
https://stackoverflow.com/questions/66226505/
PyTorch, select batches according to label in data column
I have a dataset like such: index tag feature1 feature2 target 1 tag1 1.4342 88.4554 0.5365 2 tag1 2.5656 54.5466 0.1263 3 tag2 5.4561 845.556 0.8613 4 tag3 6.5546 8.52545 0.7864 5 tag3 8.4566 945.456 0.4646 The number of entries in each tag is not always the same. And my objective is to load only t...
A simple dataset that implements roughly the characteristics you're looking for as best as I can tell. class CustomDataset(data.Dataset): def __init__(self,featuresTrain,targetsTrain,tagsTrain,sample_equally = False): # self.tags should be a tensor in k-hot encoding form so a 2D tensor, self.tags = t...
https://stackoverflow.com/questions/66228697/
Vanishing seq_len in attention-based BiLSTM
I'm studying several implementations of self attention-based BiLSTM and I don't understand why in each of them the input and output size are different. In particular I refer to the following codes taken from different implementations: Implementation 1 e 2 def attnetwork(self, encoder_out, final_hidden): # enco...
From my experience, what an attention-based model does is : Calculate some relationships between decoder hidden states and encoder outputs. Take softmax to get the attention distribution. Take a weighted sum of the encoder output to get the attention output. And a Seq2seq model act like: Pass your sequences e.g., an...
https://stackoverflow.com/questions/66233078/
How perform unsupervised clustering on numbers in an Array using PyTorch
I got this array and I want to cluster/group the numbers into similar values. An example of input array: array([ 57, 58, 59, 60, 61, 78, 79, 80, 81, 82, 83, 101, 102, 103, 104, 105, 106] expected result : array([57,58,59,60,61]), ([78,79,80,81,82,83]), ([101,102,103,104,105,106]) I tried to use clustering but I don...
You can perform kind of derivation on this array so that you can track changes better, assume your array is: A = np.array([ 57, 58, 59, 60, 61, 78, 79, 80, 81, 82, 83, 101, 102, 103, 104, 105, 106]) so you can make a derivation vector by simply convolving your vector with [-1 1]: A_ = abs(np.convolve(A, np.array([-1, ...
https://stackoverflow.com/questions/66238110/
Pytorch tensor shape
I have a simple question regarding the shapes of 2 different tensors - tensor_1 and tensor_2. tensor_1.shape outputs torch.Size([784, 1]); tensor_2.shape outputs torch.Size([784]). I understand that the first one is rank-2 tensor, whereas the second is rank-1. What's hard for me is to conceptualize the difference bet...
You cant call tensor_1 as column vector because of its dimension . indexing that particular tensor is done in 2D eg . tensor_1[1,1] Coming to tensor_2 , its a scalar tensor having only one dimension. And of course you can make it have a shape of tensor_1, just do tensor_2 = tensor_2.unsqueeze(1) #This method will mak...
https://stackoverflow.com/questions/66247473/
Testing my CNN on a small set of image but training has no effect
I constructed a CNN to recognize 9 classes of gestures in images of 224x224x3. I try to test its functionality by training it on 16 images and see if it overfits to 100 accuracy. Here is my network import torch.nn as nn class learn_gesture(nn.Module): def __init__(self): super(learn_gesture,...
It seems that you are using a model named overfit_model where you pass over_model.parameters() to the optimizer: optimizer = optim.SGD(over_model.parameters(), lr=0.001, momentum=0.9) Should be replaced with ovrefit_model.parameters(). You are setting your gradients to zeros right after you back propagate, where it ...
https://stackoverflow.com/questions/66286991/
Pytorch how use a linear activation function
In Keras, I can create any network layer with a linear activation function as follows (for example, a fully-connected layer is taken): model.add(keras.layers.Dense(outs, input_shape=(160,), activation='linear')) But I can't find the linear activation function in the PyTorch documentation. ReLU is not suitable, because...
If you take a look at the Keras documentation, you will see tf.keras.layers.Dense's activation='linear' corresponds to the a(x) = x function. Which means no non-linearity. So in PyTorch, you just define the linear function without adding any activation layer: torch.nn.Linear(160, outs)
https://stackoverflow.com/questions/66294119/
Append a tensor vector to tensor matrix
I have a tensor matrix that i simply want to append a tensor vector as another column to it. For example: X = torch.randint(100, (100,5)) x1 = torch.from_numpy(np.array(range(0, 100))) I've tried torch.cat([x1, X) with various numbers for both axis and dim but it always says that the dimensions don't match.
You can also use torch.hstack to combine and unsqueeze for reshape x1 torch.hstack([X, x1.unsqueeze(1)])
https://stackoverflow.com/questions/66299739/
How to build a dataset from a large text file without getting a memory error?
I have a text file with size > 7.02 GB. I have already built a tokenizer based on this text file. I want to build a dataset like so: from transformers import LineByLineTextDataset dataset = LineByLineTextDataset( tokenizer=tokenizer, file_path="data.txt", block_size=128,) Since the size of my da...
You can create a dictionary storing the byte offsets for each line of the .txt file: offset_dict = {} with open(large_file_path, 'rb') as f: f.readline() # move over header for line in range(number_of_lines): offset = f.tell() offset_dict[line] = offset and then implement your own hashed ...
https://stackoverflow.com/questions/66301608/