instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
How to use a Huggingface BERT model from to feed a binary classifier CNN?
I am a bit confused about how to consume huggingface transformers outputs to train a simple language binary classifier model that predicts if Albert Einstein said a sentence or not. from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") model = AutoMo...
In pytorch you don't need to have a fixed input dim for a CNN. The only requirement is that your kernel_size must not be smaller than the input_size. Generally, the best way of putting a classifier (sequence classifier) on top of a Transformer model is to add a pooling layer + FC layer. You can use global pooling, an ...
https://stackoverflow.com/questions/68945422/
Changing pre-trained model's parameters
I need to change parameters of a pre-trained model, not in any particular way. I'm trying this: ids = [int(p.sum().item()) for p in model.parameters()] print(ids[0]) for i in model.parameters(): x = i.data x = x/100 break; ids = [int(p.sum().item()) for p in model.parameters()] print(ids[0]) but it outp...
This is simple: you need to perform an in-place operation, otherwise you'll operate on a new object: for i in model.parameters(): x = i.data x /= 100 break Here's a minimal reproducible example: import torch torch.manual_seed(2021) m = torch.nn.Linear(1, 1) # show current value of the weight print(next(...
https://stackoverflow.com/questions/68946757/
Why don't O3 less than O1 in gpu memory?
i'm training EfficientDet-D7(head_only=True) in 2080TI * 1. And i'm using NVIDIA/APEX:amp. When i use opt_level=O1, although the memory is definitely reduced compared to when apex is not used. But, when I use opt_level=O2orO3, more memory is consumed. I am experimenting with the same 2080 Ti, each with a separate GPU b...
You're optimizing for speed. Some speed optimizations will reduce memory usage. Other will increase them. An example of when speed optimization reduces memory usage is when unnecessary variables and function calls are removed. An example of the opposite is loop unrolling. There's no reason to expect optimization to...
https://stackoverflow.com/questions/68949428/
How can I convert onnx format to ptl format?
Here I already got my .onnx format file: retinaface.onnx, I want to convert it to PyTorch mobile supported format: .ptl or .pt, then I can do inference in Android platform. But I failed to convert or to find relevant issues. // I want to load directly but failed mRetinafaceDector = LiteModuleLoader.load(mModelPath + &...
You can't load onnx model directly to pytorch as it's not supported yet. Fortunately you can use onnx2pytorch tool to convert onnx to pytorch Firstly install it: https://github.com/ToriML/onnx2pytorch Then you can easily convert it using this code: onnx_model = onnx.load(path_to_onnx_model) pytorch_model = ConvertModel...
https://stackoverflow.com/questions/68962511/
Getting Error too many indices for tensor of dimension 3
I am trying to Read an Image using GeneralizedRCNN, Input shape is given as a comment with code. The problem is I am getting an error while tracing the model with input shape. The error is : > trace = torch.jit.trace(model, input_batch) line Providing the error > "/usr/local/lib/python3.7/dist-packages/torch...
This error occurred because input_batch.size = torch.Size([1, 3, 519, 1038]) has 4 dimensions and trace = torch.jit.trace(model, input_batch) expected to get a 3 dimensions as input. you don't need input_batch = input_tensor.unsqueeze(0). delete or comment this line.
https://stackoverflow.com/questions/68967277/
Poorer performance when change optimizer from Adam to Nesterov
I am running an image segmentation code on Pytorch, based on the architecture of Linknet. The optimizer is initially set as: self.optimizer = torch.optim.Adam(params=self.net.parameters(), lr=lr) Then I change it to Nesterov to improve the performance, like: self.optimizer = torch.optim.SGD(params=self.net.parameters(...
Seems like your question relies on the assumption that SGD with Nesterov would definitely perform better than Adam. However, there is no learning algorithm that is better than another no matter what. You always have to check it given your model (layers, activation functions, loss, etc.) and dataset. Are you increasing ...
https://stackoverflow.com/questions/68978614/
Loading Dating without a separate TRAIN/TEST Directory : Pytorch (ImageFolder)
My data is not distributed in train and test directories but only in classes. I mean: image-folders/ β”œβ”€β”€ class_0/ | β”œβ”€β”€ 001.jpg | β”œβ”€β”€ 002.jpg └── class_1/ | β”œβ”€β”€ 001.jpg | └── 002.jpg └── class_2/ β”œβ”€β”€ 001.jpg └── 002.jpg Is it the right way to approach the problem (What this d...
This seems ok to me. Alternatively you can create three separate datasets from data, using torch.utils.data.random_split. This has the benefit of not having to worry about implementing the samplers for your dataloaders: from torch.utils.data import DataLoader, random_split dl_args = dict(batch_size=batch_size, num_wor...
https://stackoverflow.com/questions/68982798/
data loader is not defined but I have imported it
This is a baseline model from github; I try to produce its result dataloader.py, models.py have been put in the same direction with this scripts from __future__ import print_function import sys import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as...
If you are importing this file in another one, the condition __name__ == '__main__' won't be True, as such both dataloader and models won't be imported into your file. if __name__ == '__main__': import dataloader as dataloader import models as models Instead, you could import both straight away as: import data...
https://stackoverflow.com/questions/68984251/
Why does order of function calls impact runtime
I'm using pyTorch to run calculations on my GPU (RTX 3000, CUDA 11.1). One step involves calculating the distance between one point and an array of points. For kicks I tested 2 functions to determine which is faster as follows: import datetime as dt import functools import timeit import torch import numpy as np devi...
you just can add torch.cuda.empty_cache() All code: import datetime as dt import functools import timeit import torch import numpy as np device = torch.device("cuda:0") # define functions for calculating distance def dist_geom(a, b): dist = (a - b)**2 dist = dist.sum(axis=1)**0.5 return dist ...
https://stackoverflow.com/questions/68985444/
Pytorch: Custom thresholding activation function - gradient
I created an activation function class Threshold that should operate on one-hot-encoded image tensors. The function performs min-max feature scaling on each channel followed by thresholding. class Threshold(nn.Module): def __init__(self, threshold=.5): super().__init__() if threshold < 0.0 or threshold > ...
The issue is you are manipulating and overwriting elements, this time of operation can't be tracked by autograd. Instead, you should stick with built-in functions. You example is not that tricky to tackle: you are looking to retrieve the minimum and maximum values along input.shape[0] x input.shape[1]. Then you will sc...
https://stackoverflow.com/questions/68985501/
PyTorch vs Tensorflow gives different results
I am implementing the "perceptual loss" function. But, PyTorch vs Tensorflow gives different results. I used the same images. Please, let me know why. TensorFlow class FeatureExtractor(tf.keras.Model): def __init__(self, n_layers): super(FeatureExtractor, self).__init__() extractor...
Although they are the same models, the parameters of final model may be different because of different initialization parameters. For different frameworks like keras and pytorch, it's different to preprocess the input images before training. So the tenor value is different after processing even if they are same images...
https://stackoverflow.com/questions/69007027/
TypeError: unsupported format string passed to Tensor.__format__
When trying to convert a code written for old PyTorch to 1.9 I get this error: (fashcomp) [jalal@goku fashion-compatibility]$ python main.py --name test_baseline --learned --l2_embed --datadir ../../../data/fashion/ /scratch3/venv/fashcomp/lib/python3.8/site-packages/torchvision/transforms/transforms.py:310: UserWarnin...
This error is reproducible if you try to format a torch.Tensor in a specific way: >>> print('{:.2f}'.format(torch.rand(1))) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-ece663be5b5c&gt...
https://stackoverflow.com/questions/69021335/
Python execution hangs when attempting to add a pytorch module to a sequential module in loop
I am designing a neural network that has a sequential module that is composed of a variable number of linear layers depending on the initial size of the feature space. The problem is that on the first module that I append to my sequential module, the code stops executing and my runtime is crashed. Here is my code: self...
As mentioned in this PyTorch Forums thread, you can create a list of nn.Modules and feed them to an nn.Sequential constructor. For example: import torch.nn as nn modules = [] modules.append(nn.Linear(10, 10)) modules.append(nn.Linear(10, 10)) sequential = nn.Sequential(*modules) Also, as mentioned in PyTorch Documen...
https://stackoverflow.com/questions/69024252/
Multiply 2D tensor with 3D tensor in pytorch
Suppose I have a matrix such as P = [[0,1],[1,0]] and a vector v = [a,b]. If I multiply them I have: Pv = [b,a] The matrix P is simply a permutation matrix, which changes the order of each element. Now suppose that I have the same P, but I have the matrices M1 = [[1,2],[3,4]] and M2=[[5,6],[7,8]]. Now let me combine th...
An alternative solution to @mlucy's answer, is to use torch.einsum. This has the benefit of defining the operation yourself, without worrying about torch.matmul's requirements: >>> torch.einsum('ij,jkl->ikl', P, T) tensor([[[5, 6], [7, 8]], [[1, 2], [3, 4]]]) Or with torch.matmu...
https://stackoverflow.com/questions/69033199/
Creating 1D vectors over 3D tensors in pytorch
I have the following tensor with dimensions (2, 3, 2, 2) where the dimensions represent (batch_size, channels, height, width): tensor([[[[ 1., 2.], [ 3., 4.]], [[ 5., 6.], [ 7., 8.]], [[ 9., 10.], [11., 12.]]], [[[13., 14.], [15., 16.]], ...
You can do it this way: import torch x = torch.Tensor( [ [ [[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]]], [ [[13,14],[15,16]], [[17,18],[19,20]], [[21,22],[23,24]]] ] ) result = x.swapaxes(0, 1).reshape(3, -1).T print(result) # > tensor([[ 1., 5., 9.], # > [ ...
https://stackoverflow.com/questions/69035771/
Concatenate two tensors of different shape from two different input modalities
I have two tensors: a = torch.randn((1, 30, 1220)) # represents text embedding vector (30 spans, each with embedding size of 1220) b = torch.randn((1, 128, 256)) # represents image features obtained from a pretrained CNN (object detection) How do I concatenate everything in b to each one of the 30 spans of a? How to...
Since these representations are from two different modalities (i.e., text and image) and they contain valuable features that are of great importance to the final goal, I would suggest to fuse them in a "learnable" manner instead of a mere concatenation or addition. Furthermore, such a learnable weighting (bet...
https://stackoverflow.com/questions/69036172/
How to update models / vectors on runtime, on daily basis?
I have a simple web app which uses sklearn transformed vectors (tfidf / count / normalizer) & other pytorch (transformer models). I usually dump these models via joblib. This app calls these models via fastapi based apis. Until now everything is fine. But the above listed vectors and models are updated on daily ba...
It sounds like what you want to do is load the model once, use the model in memory, and then every so often check whether a new model is available on disk and reload it if an updated version is available.
https://stackoverflow.com/questions/69042371/
Why by changing tensor using detach method make backpropagation not always unable to work in pytorch?
After constructing a graph, when using the detach method to change some tensor value, it is expected that an error pops up when computing the back propagation. However, this is not always the case. In the following two blocks of code: the first one raises an error, while the second one does not. Why does this happen? x...
TLDR; In the former example z = y**2, so dz/dy = 2*y, i.e. it's a function of y and requires its values to be unchanged to properly compute the backpropagation, hence the error message when applying the in-place operation. In the latter z = 3*y1 + 4*y2, so dz/dy2 = 4, i.e. y2 values are not needed to compute the gradie...
https://stackoverflow.com/questions/69042447/
Input image size of Faster-RCNN model in Pytorch
I'm Trying to implement of Faster-RCNN model with Pytorch. In the structure, First element of model is Transform. from torchvision.models.detection import fasterrcnn_resnet50_fpn model = fasterrcnn_resnet50_fpn(pretrained=True) print(model.transform) GeneralizedRCNNTransform( Normalize(mean=[0.485, 0.456, 0.406],...
GeneralizedRCNN data transform: https://github.com/pytorch/vision/blob/922db3086e654871c35cd80c2c01eabb65d78475/torchvision/models/detection/generalized_rcnn.py#L15 performs the data transformation on the inputs to feed into the model min_size: minimum size of the image to be rescaled before feeding it to the backbone....
https://stackoverflow.com/questions/69053420/
How do I fix Pytorch-Forecasting model fit ValueError about sequence element
I am new with Pytorch_Forecasting. I followed exactly same as described in 'Demand forecasting with the Temporal Fusion Transformer' (https://pytorch-forecasting.readthedocs.io/en/latest/tutorials/stallion.html). Everything went find until the last model fitting step (trainer.fit(...)). I keep getting the error, "...
I faced the same issue. Pytorch_lightning, recently launched a new version, and pytorch-forecasting is built on top of it. I changed the version of torchmetrics to 0.5.0. pip install torchmetrics==0.5.0
https://stackoverflow.com/questions/69056300/
Have Euclidean distance between two inputs populate a matrix within one loop
I'm taking two tensors of dimensions (batch size, D1, D2, D3) and flattening them to (batch size, D1). I'm then trying to take the Euclidean distance between every row of one (train) tensor with every row of the second tensor (test). I'm having trouble understanding how to populate the distance combinations between ten...
Okay, I was missing a very important parameter in torch.sum() that I did not know about that solves this issue. adding a 1, so that it looks like torch.sqrt(torch.sum(torch.square(train-test[i]), 1)) outputs to what I want.
https://stackoverflow.com/questions/69059279/
How to Load Fastai model and predict it on single image
I have trained a fastai model using Kaggle notebook, it has saved the model but how to load the model is the problem, i have tried different methods like the method given below. Even it does load the model it doesn't have any predict function only thing I can see is model.eval(). The second problem is when the model wa...
How to load pytorch models: loc = torch.load('/content/gdrive/MyDrive/Data Exports/35k data/stage-1.pth') model = ... # build your model model.load_state_dict(loc) model.eval() Now you should be able to simply use the forward pass to generate your predictions: input = ... # your input image pred = model(input) # your ...
https://stackoverflow.com/questions/69066970/
how to get max value by the indices return by torch.max?
The interface torch.max will return value and indices, how can i use the indices to get the according elements from another tensor? for example: a = torch.rand(2,3,4) b = torch.rand(2,3,4) # indices shape is [2, 4] indices = torch.max(a, 1)[1] # how to get elements by indices ? b_max = ????
keepdim=True when calling torch.max() and torch.take_along_dim() should do the trick. >>> import torch >>> a=torch.rand(2,3,4) >>> b=torch.rand(2,3,4) >>> indices=torch.max(a,1,keepdim=True)[1] >>> b_max = torch.take_along_dim(b,indices,dim=1) 2D example: >>> a=tor...
https://stackoverflow.com/questions/69068583/
LibTorch and OpenCV Libs not working in same cmakelist file
cmake_minimum_required(VERSION 3.1 FATAL_ERROR) project(Detect) #set(Torch "/home/somnath/libtorch/share/cmake/Torch") find_package(Torch REQUIRED) find_package(OpenCV REQUIRED) message(STATUS "CVINCLUDE: ${OpenCV_INCLUDE_DIRS}") include_directories(${OpenCV_INCLUDE_DIRS}) add_executable(Detect main...
Try to change the libTorch from Pre-cxx11 ABI to cxx11 ABI https://pytorch.org/get-started/locally/ All thanks to Jacob HM from https://stackoverflow.com/a/61459156/13045595
https://stackoverflow.com/questions/69088354/
Pytorch Geometric sparse adjacency matrix to edge index tensor
My data object has the data.adj_t parameter, giving me the sparse adjacency matrix. How can I get the edge_index tensor of size [2, num_edges] from this?
As you can see in the docs: Since this feature is still experimental, some operations, e.g., graph pooling methods, may still require you to input the edge_index format. You can convert adj_t back to (edge_index, edge_attr) via: row, col, edge_attr = adj_t.t().coo() edge_index = torch.stack([row, col], dim=0)
https://stackoverflow.com/questions/69091074/
Having Issues Loading the CelebA dataset on Google Colab Using Pytorch
I need to load the CelebA dataset for a Python (Pytorch) implementation of the following paper: https://arxiv.org/pdf/1908.10578.pdf The original code for loading the CelebA dataset was written in MATLAB using MatConvNet with autonn (source 15 paper). I have the source code but I'm not sure if I can share it. It's my f...
Since we do not know the syntax error in your case, I cannot comment on it. Below I will share one possible way to do it. You can download the celebA dataset from Kaggle using this link. Alternatively, you can also create a Kaggle kernel using this data (no need to download data then) If you are using google colab, u...
https://stackoverflow.com/questions/69096548/
Which loss function to use for training sparse multi-label text classification problem and class skewness/imbalance
I am training a sparse multi-label text classification problem using Hugging Face models which is one part of SMART REPLY System. The task which I am doing is mentioned below: I classify Customer Utterances as input to the model and classify to which Agent Response clusters it belongs to. I have 60 clusters and Custome...
You can use a weighted cross entropy applied to each index of the output. You'd have to go through the training set to calculate the weights of each cluster. criterion = nn.BCEWithLogitsLoss(reduction='none') loss = criterion(output, target) loss = (loss * weights).mean() loss.backward() By doing so the losses for dif...
https://stackoverflow.com/questions/69098628/
Not able to save model to gs bucket using torch.save()
I am trying to save a PyTorch model to my google cloud bucket but it is always showing a "FileNotFoundError error". I already have a gs bucket and the file path I am providing is also correct. My code is running on a GCP notebook instance. path = "gs://bucket_name/model/model.pt" torch.save(model,pa...
try this: import gcsfs fs = gcsfs.GCSFileSystem(project = '<enter your gc project>') with fs.open("gs://bucket_name/"+f'model/model.pt', 'wb') as f: torch.save(model, f)
https://stackoverflow.com/questions/69100496/
How to solve issue : grad_fn = None
Could anyone advise why grad_fn = None for this pytorch coding ?
Parameter weights are leaf nodes, i.e. those tensor are not the result of an operation, in other words, there is no other tensor node preceding them. You can check using the is_leaf attribute: >>> nn.Linear(1,1).weight.is_leaf True The grad_fn attribute essentially holds the callback function to backpropagate...
https://stackoverflow.com/questions/69101872/
tflite quantized mobilenet v2 classifier not working
My goal is to convert a PyTorch Model into a quantized tflite model that can be used for inference on the Edge TPU. I was able to convert a fairly complex depth estimation model from PyTorch to tflite and I successfully ran it on the Edge TPU. But because not all operations were supported, inference was pretty slow (&g...
EdgeTPU mapping of PReLU (LeakyReLU) is now supported in openvino2tensorflow v1.20.4. However, due to the large size of the model, it is not possible to map all operations to the EdgeTPU. Therefore, the part of the EdgeTPU that does not fit in RAM is offloaded to the CPU for inference, which is very slow. In this case,...
https://stackoverflow.com/questions/69105473/
How do I use separate types of gpus (e.g. 1080Ti vs 2080Ti) on the same docker image without needing to re-run `python setup.py develop`?
I'm using a pytorch-based repository where the installation step specifies to run python setup.py develop with this setup.py file. I have been running the repository fine with 1080Ti and 1080 GPUs using a docker image which clones the repo and runs the setup.py script in the build process. The following are files copie...
The problem was solved by building the docker image with the following: RUN git clone https://github.com/CVMI-Lab/ST3D.git WORKDIR /ST3D RUN nvidia-smi RUN pip install -r requirements.txt RUN TORCH_CUDA_ARCH_LIST="6.1 7.5" python setup.py develop Where the TORCH_CUDA_ARCH_LIST="6.1 7.5" where it's ...
https://stackoverflow.com/questions/69111302/
understanding pytorch conv2d internally
I'm trying to understand what does the nn.conv2d do internally. so lets assume we are applying Conv2d to a 32*32 RGB image. torch.nn.Conv2d(3, 49, 4, bias=True) so : when we initialize the conv layer how many weights and in which shapes would it have, please tell this for biases apart? before applying it the conv the...
I understand how a kernel would act but I don't understand how many kernels would be created by the nn.Conv2d(3, 49, 4, bias=True) and which of them would be applying on R, G, and B channels. Calling nn.Conv2d(3, 49, 4, bias=True) will initialize 49 4x4-kernels, each having a total of three channels and a single bias...
https://stackoverflow.com/questions/69118656/
estimator.fit hangs on sagemaker on local mode
I am trying to train a pytorch model using Sagemaker on local mode, but whenever I call estimator.fit the code hangs indefinitely and I have to interrupt the notebook kernel. This happens both in my local machine and in Sagemaker Studio. But when I use EC2, the training runs normally. Here the call to the estimator, an...
SageMaker Studio does not natively support local mode. Studio Apps are themselves docker containers and therefore they require privileged access if they were to be able to build and run docker containers. As an alternative solution, you can create a remote docker host on an EC2 instance and setup docker on your Studio ...
https://stackoverflow.com/questions/69119171/
PyTorch | getting "RuntimeError: Found dtype Long but expected Float" with dataset Omniglot
Im a real newbie on PyTorch and Neural Networks. I have started to work on these suubjects this week and my mentor has gave me a code and with some tasks to work on the code. But the code that he gave me is not working. I have tried to fix this all day but got no result. Because i do not know the background of the NN's...
Your dataset is returning integers for your labels, you should cast them to floating points. One way of solving it is to do: loss = loss_fun(y_pred, y_train.float())
https://stackoverflow.com/questions/69124057/
How to optimize cudaHostAlloc and cudaLaunchKernel times in pytorch training
I am trying to profile my model with pytorch profiler. I used the below code to profile with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True) as prof: with record_function("model_inference"): output_batch = self.model(input_batch) print(prof.key_averages().tabl...
I am not an expert but I think cudaLaunchKernel is called at every operation done with cuda. So I think you cannot optimize it. If you plot a detailed tracing https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html#using-tracing-functionality, you see that it is called everytime you do a cuda operation like ...
https://stackoverflow.com/questions/69127080/
Weights & Biases with Transformers and PyTorch?
I'm training an NLP model at work (e-commerce SEO) applying a BERT variation for portuguese language (BERTimbau) through Transformers by Hugging Face. I didn't used the Trainer from Transformers API. I used PyTorch to set all parameters through DataLoader.utils and adamW. I trained my model using run_glue.py. I'm train...
Scott from W&B here. Although you're not using the HuggingFace WandbCallback, you can still take advantage of wandb easily using our Python API. All you need to do is call wandb.log({'val_loss': val_loss, 'train_loss': train_avg}) with whatever you want to log after you call wandb.init before training. Here's an ex...
https://stackoverflow.com/questions/69147788/
Sequential batch processing vs parallel batch processing?
In deep learning based model training, in general batch of inputs are passed. For example for training a deep learning model with [512] dimensional input feature vector, say for batch size= 4, we mainly pass [4,512] dimenional input. I am curious what are the logical significance of passing the same input after flatten...
In supervised learning, you would usually be working with data points (e.g. a feature vector or a multi-dimensional input such as an image) paired with some kind of ground-truth (a label for classifications tasks, or another multi-dimensional object altogether). Feeding to your model a flattened tensor containing multi...
https://stackoverflow.com/questions/69162442/
How to make Python libraries accessible in PYTHONPATH?
I am trying to implement StyleGAN2-ADA PyTorch: https://github.com/NVlabs/stylegan2-ada-pytorch. On the GitHub repo, it states the following: The above code requires torch_utils and dnnlib to be accessible via PYTHONPATH. It does not need source code for the networks themselves β€” their class definitions are loaded fro...
Let's say you have the source code of this repo cloned to /somepath/stylegan2-ada-pytorch which means that the directories you quoted are at /somepath/stylegan2-ada-pytorch/torch_utils and /somepath/stylegan2-ada-pytorch/dnnlib, respectively. Now let's say you have a python script that you want to access this code. It ...
https://stackoverflow.com/questions/69169145/
Pytorch customized dataloader
I am trying to train a classifier with MNIST dataset using pytorch-lightening. import pytorch_lightning as pl from torchvision import transforms from torchvision.datasets import MNIST, SVHN from torch.utils.data import DataLoader, random_split class MNISTData(pl.LightningDataModule): def __init__(self, data_dir=...
As I told in the comments, and Ivan posted in his answer, there was missing return statement: def test_dataloader(self): mnist_test = DataLoader(self.mnist_test, batch_size=self.batch_size) return mnist_test # <<< missing return As per your comment, if we try: a = MNISTData() # skip download, assumin...
https://stackoverflow.com/questions/69170854/
Is it possible to retrain a trained model on fewer classes?
I am working on image detection where I am detecting and classifying an image into one of 14 different thoric diseases (multi-label classification problem). The model is trained on NIH dataset with which I get 80% AUC. Now I want to improve the model by training on a second dataset. But the main problem is both dataset...
Based on discussion in the comments: Yes, if the classes overlap (with different data points from a different dataset) you can train the same classifier layer with two datasets. This would mean in one of the datasets, 4 out of 14 classes are simply not trained. What this means is that you are basically making your exi...
https://stackoverflow.com/questions/69175045/
DropPath in TIMM seems like a Dropout?
The code below (taken from here) seems to implement only a simple Dropout, neither the DropPath nor DropConnect. Is that true? def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the s...
No, it is different from Dropout: import torch from torch.nn.functional import dropout torch.manual_seed(2021) def drop_path(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) ran...
https://stackoverflow.com/questions/69175642/
Can't install GPU-enabled Pytorch in Conda environment from environment.yml
I'm on Ubuntu 20.04 LTS with CUDA 11.1 installed (and working, with PATH and LD_LIBRARY_PATH configured correctly), and I'm trying to define a reusable conda environment (i.e., in an environment.yml file) that successfully installs PyTorch with CUDA support. However, when I use the environment file, I get a message tha...
Just a few minutes after posting this question, I was able to figure out the solution. It turns out that it has to do with prioritizing Conda channels. The solution (which isn't well-documented by Anaconda) is to specify the correct channel for cudatoolkit and pytorch in environment.yml: name: foo channels: - conda-f...
https://stackoverflow.com/questions/69180740/
Pytorch DataLoder Is Very Slow
I have a problem with the DataLoader form Pytorch, because is very slow. I did a test to show this, here is the code: data = np.load('slices.npy') data = np.reshape(data, (-1, 1225)) data = torch.FloatTensor(data).to('cuda') print(data.shape) # ==> torch.Size([273468, 1225]) class UnlabeledTensorDataset(TensorDatas...
The time difference seems logical to me: On one end you're looping over test_loader and doing 1225 inferences. On the other, you are doing a single inference.
https://stackoverflow.com/questions/69185093/
How to convert a tensor into a list of tensors
How can I convert a tensor into a list of tensors. For instance: P1 is a torch.Tensor with 60 values in it and I want a list of tensors with 60 tensors in it.
You can coerce the torch.Tensor to a list with list: >>> P1 = torch.rand(60) >>> list(P1) [tensor(0.5987), tensor(0.5321), tensor(0.6590), ... tensor(0.1381)] This works with multi-dimensional tensors too: >>> P1 = torch.rand(60, 2) >>> list(P1) [tensor([0.4675, 0.0430]), tenso...
https://stackoverflow.com/questions/69186799/
PyTorch's nn.Conv2d with half-precision (fp16) is slower than fp32
I have found that a single 2D convolution operation with float16 is slower than with float32. I am working with a Gtx 1660 Ti with torch.1.8.0+cu111 and cuda-11.1 (also tried with torch.1.9.0) Dtype in=1,out=64 in=1,out=128 in=64,out=128 Fp16 3532 it/s 632 it/s 599it/s Fp32 2160 it/s 1311 it/s 925it/s I a...
Well, the problem lays on the fact that Mixed/Half precision tensor calculations are accelerated via Tensor Cores. Theoretically (and practically) Tensor Cores are designed to handle lower precision matrix calculations, where, for instance you add the fp32 multiplication product of 2 fp16 matrix calculation to the accu...
https://stackoverflow.com/questions/69188051/
LSTM.weight_ih_l[k] dimensions with proj_size
According to Pytorch LSTM documentation :- ~LSTM.weight_ih_l[k] – the learnable input-hidden weights of the kth layer (W_ii|W_if|W_ig|W_io), of shape (4*hidden_size, input_size) for k = 0. Otherwise, the shape is (4 * hidden_size, num_directions * hidden_size) My doubt is, why for k > 0 the shape for each weight ...
This is now fixed. The OP opened the Issue #65053 that was fixed by PR #65102 (commit 83878e1). It just happens that the documentation isn't providing all the details in this case, and you're correct. In fact, you can check in the source code that the shape of W_ih is (4*hidden_size, num_directions * proj_size) when p...
https://stackoverflow.com/questions/69190587/
Mismatched size on BertForSequenceClassification from Transformers and multiclass problem
I just trained a BERT model on a Dataset composed by products and labels (departments) for an e-commerce website. It's a multiclass problem. I used BertForSequenceClassification to predict the department for each product. I split it in train and evaluation, I used dataloader from pytorch, and I've got a good score with...
Your new dataset has 105 classes while your model was trained for 59 classes. As you have already mentioned, you can use ignore_mismatched_sizes to load your model. This parameter will load the the embedding and encoding layers of your model, but will randomly initialize the classification head: model = BertForSequenc...
https://stackoverflow.com/questions/69194640/
Unable to access batch items in iterator - Torchtext Attribute Error: 'Field' object has no attribute 'vocab'
I am unable to access batch items from the Iterator object in Torchtext. Following is the error AttributeError: 'Field' object has no attribute 'vocab' Code to Recreate Problem #Access to Drive from google.colab import drive drive.mount ('/content/gdrive') import numpy as np import spacy spacy_en = spacy.load("...
After you set your device, you are redefining TEXT and LABEL. That isn't necessary, and could cause issues. Also, you are setting use_vocab=False for your LabelField, and then building a vocab for it. From the torchtext 0.8 docs: use_vocab: Whether to use a Vocab object. If False, the data in this field should already...
https://stackoverflow.com/questions/69205178/
How do I split an iterable dataset into training and test datasets?
I have an iterable dataset object with all of my data files. How can I split it into train and validation set. I have seen a few solutions for custom datasets but iterable does not support len() operator. torch.utils.random_sample() and torch.utils.SubsetRandomSample() don't work. def __init__(self): bla bla def __...
Technically you can just set a goal ratio, and start collecting items into two lists randomly using that ratio. The result won't be perfect, but asymptotically it will keep the ratio. The example is JavaScript, as it can be run here: { let a = [], b = []; function addsample(x) { if (Math.random() <...
https://stackoverflow.com/questions/69206153/
RuntimeError Pytoch Unable to find a valid cuDNN algorithm to run convolution
I want to test a github for my work: https://github.com/tufts-ml/GAN-Ensemble-for-Anomaly-Detection so I did a git clone https://github.com/tufts-ml/GAN-Ensemble-for-Anomaly-Detection Unfortunately, I have an error when I do the command sh experiments/run_mnist_en_fanogan.sh (from the github README) sh experiments/ru...
@Berriel You right, I was focus on the error. To solve my problem, I did pip uninstall torch torchvision torchaudio Then pip3 install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html According to https://pytorch.org/get-started/locally/ (this link i...
https://stackoverflow.com/questions/69209100/
what is the difference of torch.nn.Softmax, torch.nn.funtional.softmax, torch.softmax and torch.nn.functional.log_softmax
I tried to find documents but cannot find anything about torch.softmax. What is the difference among torch.nn.Softmax, torch.nn.funtional.softmax, torch.softmax and torch.nn.functional.log_softmax? Examples are appreciated.
import torch x = torch.rand(5) x1 = torch.nn.Softmax()(x) x2 = torch.nn.functional.softmax(x) x3 = torch.nn.functional.log_softmax(x) print(x1) print(x2) print(torch.log(x1)) print(x3) tensor([0.2740, 0.1955, 0.1519, 0.1758, 0.2029]) tensor([0.2740, 0.1955, 0.1519, 0.1758, 0.2029]) tensor([-1.2946, -1.6323, -1.8847...
https://stackoverflow.com/questions/69217305/
Use of torch.stack()
t1 = torch.tensor([1,2,3]) t2 = torch.tensor([4,5,6]) t3 = torch.tensor([7,8,9]) torch.stack((t1,t2,t3),dim=1) When implementing the torch.stack(), I can't understand how stacking is done for different dim. Here stacking is done for columns but I can't understand the details as to how it is done. It becomes more comp...
Imagine have n tensors. If we stay in 3D, those correspond to volumes, namely rectangular cuboids. Stacking corresponds to combining those n volumes on an additional dimension: here a 4th dimension is added to host the n 3D volumes. This operation is in clear contrast with concatenation, where the volumes would be comb...
https://stackoverflow.com/questions/69220221/
Pytorch Tensor - How to get the index of a tensor given a multidimensional tensor
I have a the following tensor lets call it lookup_table: tensor([266, 103, 84, 12, 32, 34, 1, 523, 22, 136, 268, 432, 53, 63, 201, 51, 164, 69, 31, 42, 122, 131, 119, 36, 245, 60, 28, 81, 9, 114, 105, 3, 41, 86, 150, 79, 104, 120, 74, 420, 39, 427, 40, 59, 24, 126, 2...
Using searchsorted: Scanning the whole lookup_table array for each input element is quite inefficient. How about sorting the lookup table first (this only needs to be done once) sorted_lookup_table, indexes = torch.sort(lookup_table) and then using searchsorted index_into_sorted = torch.searchsorted(sorted_lookup_tabl...
https://stackoverflow.com/questions/69225949/
Why can't torchtext find a symbol _ZN2at6detail10noopDeleteEPv?
Why can't torchtext find this symbol? (synthesis) miranda9~/ultimate-utils $ python ~/type-parametric-synthesis/src/main.py --reproduce_10K --serial --debug --num_workers 0 Traceback (most recent call last): File "/home/miranda9/type-parametric-synthesis/src/main.py", line 32, in <module> from ...
Reinstall torchtext with the current version of pytorch: e.g. conda install -y torchtext -c pytorch or for older versions of pytorch torchtext ImportError in colab conda install -y torchtext==0.8.0 -c pytorch Though in general it seems in my experience that torchtext install the right version of pytorch on its own......
https://stackoverflow.com/questions/69229397/
Installing pyTorch / Torch
I am trying to install PyTorch / torch on pyCharm Community edition. It gave the following error: ERROR: Command errored out with exit status 1: command: 'c:\users\joshu\uiuc\research\ai sound-20210814t005717z-001\ai sound\venv\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'...
torch is the name of the package, not pytorch. Type the following in your terminal. pip install torch
https://stackoverflow.com/questions/69230786/
How to sample from a distribution with constraints in PyTorch?
I got a simple situation like: Generate samples and log_prob from an uniform distribution for 2-dim variables (m1, m2) which is satisfying m1~U(5, 80), m2~U(5, 80) with constraint m1+m2 < 100. from torch import distributions prior = distributions.Uniform(torch.tensor([5.0, 5.0]), torc...
This can be achieved using rejection sampling: d = torch.distributions.Uniform(5, 80) m1 = 80 m2 = 80 while m1 + m2 >= 100: m1 = d.sample() m2 = d.sample() print(m1, m2) Example output: tensor(52.3322) tensor(67.8245) tensor(68.3232) tensor(40.0983) tensor(44.7374) tensor(9.9690)
https://stackoverflow.com/questions/69249740/
How do I match samples with their predictions when doing inference with PyTorch's DistributedSampler?
I have trained a torch model for NLP tasks and would like to perform some inference using a multi GPU machine (in this case with two GPUs). Inside the processing code, I use this dataset = TensorDataset(encoded_dict['input_ids'], encoded_dict['attention_mask']) sampler = DistributedSampler( dataset, num_replicas=ar...
As I understand it, basically your dataset returns for an index idx [data,label] during training and [data] during inference. The issue with this is that the idx is not preserved by the dataloader object, so there is no way to obtain the idx values for the minibatch after the fact. One way to handle this issue is to de...
https://stackoverflow.com/questions/69253183/
Importing torchsparse (PyTorch) on Windows 10 not working
On Windows 10. I am testing someone's code which has the following imports: import torch.nn as nn import torchsparse.nn as spnn from torchsparse.point_tensor import PointTensor So on my machine I successfully installed via pip install torch-scatter torch-sparse -f https://data.pyg.org/whl/torch-1.9.0+cu111.html As I ...
It appears the package you are trying to import comes from this Github repo, which is different to the package you installed: torch-sparse you tried using. You should try with this instead: pip install --upgrade git+https://github.com/mit-han-lab/torchsparse.git@v1.4.0 Also, you can uninstall the other one with: pip u...
https://stackoverflow.com/questions/69258565/
What is different between The MaxPool1D API in tensorflow 2.X and MaxPool1d in pytorch
I'm trying to re-implement code generated in tensorflow into pytroch, but I came across maxpooling, looked into the documentation of the two frameworks, and found that their behavior is not the same. Can someone please explain to me why they are different, and which one is more efficient (I ask this because they give a...
MaxPool vs GlobalMaxPool torch.nn.MaxPool1d pools every N adjacent values by performing max operation. For these values: [1, 2, 3, 4, 5, 6, 7, 8] with kernel_size=2 as you've specified, you would get the following values: [2, 4, 6, 8] which means a sliding window of size 2 gets the maximum value and moves on to the n...
https://stackoverflow.com/questions/69275133/
Unfreeze model Layer by Layer in PyTorch
I'm working with a PyTorch model from here (T2T_ViT_7). I'm trying to freeze all layers except the last (head) layer and train it on my dataset. I want to evaluate its performance, and then unfreeze layers one by one and train it each time and see how it performs. To initially freeze all the layers and and just unfreez...
If by layers you mean each block inside of model.blocks, then you can use nn.Module.children (// nn.Module.named_children). This will return all direct submodules, while the nn.Module.modules returns all submodules recursively. Since model.blocks is a nn.ModuleList, you can slice the blocks to only select the last n la...
https://stackoverflow.com/questions/69278507/
Pytorch: Building 3D Dense Network run into error adaptive_avg_pool3d: output_size must be 3
I ran into such an error when trying to train my 3D Dense Network. There is an average pooling layer at the end of convolution blocks. As can be seen in the message below, it says that my code out = F.adaptive_avg_pool3d(input=out, output_size=[1,1,1]) does not give the right-sized output. I have tried with output_size...
I have at least found one temporary solution to this by comparing my script with other 3D densenet models on GitHub. I used the code: out = F.adaptive_avg_pool3d(input=out, output_size=(1, 1, 1)).view(features.size(0), -1) In place of the following, from the original script: out = F.adaptive_avg_pool3d(input=out, outp...
https://stackoverflow.com/questions/69279485/
How to Change the torchtext LabelField value
I'm using PyTorch to create several models which each one is run in a separate notebook. When using torch text Field to create vocab it is assigning a number for each class that is correct and my original class labels also are numbers. But the assigned label for each class is not the same as the original class label. I...
I don't think this is going to give you what you want. build_vocab iterates over a dataset and maps an item to an index if it appears in the dataset above some min_freq (default of min_freq=1). I think what you are giving it in your last example will tell build_vocab that the item '0' appears 0 times, so it won't be in...
https://stackoverflow.com/questions/69285712/
how is stacked rnn (num layers > 1) implemented on pytorch?
The GRU layer in pytorch takes in a parameter called num_layers, where you can stack RNNs. However, it is unclear how exactly the subsequent RNNs use the outputs of the previous layer. According to the documentation: Number of recurrent layers. E.g., setting num_layers=2 would mean stacking two GRUs together to form a ...
Does this mean that the output of the final cell of the first layer of the GRU is fed as input to the next layer? Or does it mean the outputs of each cell (at each timestep) is fed as an input to the cell at the same timestep of the next layer? The latter. Each time step's output from the first layer is used as input...
https://stackoverflow.com/questions/69294045/
Could not find the pytorch 1.9.1 in conda's current channels
I create a new conda virtual environment and try to install the pytorch 1.9.1 by using conda install pytorch=1.9.1. But, conda reports the PackageNotFoundError as follows. PackagesNotFoundError: The following packages are not available from current channels: pytorch==1.9.1 Current channels: https://conda.anaconda.or...
The right commands are listed on the pytorch web site. They should use the pytorch channel, e.g. with cuda: conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia
https://stackoverflow.com/questions/69296000/
How does one pip install torch 1.9.x with cuda 11.1 when errors related with memory issue arise?
I was trying to install torch 1.9.x with pip3 but I get this error: (metalearning_gpu) miranda9~/automl-meta-learning $ pip3 install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html Looking in links: https://download.pytorch.org/whl/torch_stable.html...
Not sure why this is the case but it seems once I got a node to run the installs (with a gpu) the install worked...is that normal?! (synthesis) miranda9~/automl-meta-learning $ condor_submit -i interactive.sub Submitting job(s). 1 job(s) submitted to cluster 17192. Could not find conda environment: metalearning_...
https://stackoverflow.com/questions/69302569/
How to visualize a graph from DGL's datasets?
The following snippet comes from the tutorial https://cnvrg.io/graph-neural-networks/. How can I visualize a graph from the dataset? Using something like matplotlib if possible. import dgl import torch import torch.nn as nn import torch.nn.functional as F import dgl.data dataset = dgl.data.CoraGraphDataset() g = datase...
import dgl.data import matplotlib.pyplot as plt import networkx as nx dataset = dgl.data.CoraGraphDataset() g = dataset[0] options = { 'node_color': 'black', 'node_size': 20, 'width': 1, } G = dgl.to_networkx(g) plt.figure(figsize=[15,7]) nx.draw(G, **options) It is a huge graph so you might have to play ...
https://stackoverflow.com/questions/69308451/
Unble to install requirements for summarization
I am following this huggingface github(https://github.com/huggingface/transformers/tree/master/examples/pytorch/summarization) for summarization but not able to install packages from requirements. Command used: pip install -r requirements.txt For your information I am trying this Intel oneapi devcloud.Please find the...
Try installing pkg-config and sentencepiece separately. sudo apt-get install pkg-config pip3 install sentencepiece== 0.19.2 Related source: Link Also, follow the steps which @Abhijeet has mentioned below. That's kinda obvious so not reiterating it.
https://stackoverflow.com/questions/69315011/
How to find input layers names for intermediate layer in PyTorch model?
I have some complicated model on PyTorch. How can I print names of layers (or IDs) which connected to layer's input. For start I want to find it for Concat layer. See example code below: class Concat(nn.Module): def __init__(self, dimension=1): super().__init__() self.d = dimension def forward(...
You can use type(module).__name__ to get the nn.Module class name: >>> model = SomeModel() >>> y = model(torch.randn(1, 3, 32, 32)) >>> for name, m in model.named_modules(): ... if 'Concat' == type(m).__name__: ... print(name, m) conc Concat() Edit: You can actually manage to ge...
https://stackoverflow.com/questions/69318398/
Large, exploding loss in Pytorch transformer model
I am trying to solve a sequence to sequence problem with a transformer model. The data is derived from a set of crossword puzzles. The positional encoding and transformer classes are as follows: class PositionalEncoding(nn.Module): def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 3000...
You are only adding things to your loss, so naturally it can only increase. loss_value += float(loss) You're supposed to set it to zero after every epoch. Now you set it to zero once, in the beginning of the training process. There is a training loop template here if you're interested (https://pytorch.org/tutorials/be...
https://stackoverflow.com/questions/69323932/
Are PyTorch-trained models transferable between GPUs and TPUs?
After using a GPU for some to train a PyTorch model, can I use the saved weights to continue training my model on a TPU?
After using GPU for some time can I use the saved weights to train my model using TPU? Yes, if you saved your GPU-trained model with, say torch.save(model.save_dict(), 'model.pt') you can load it again for use on a TPU (using https://github.com/pytorch/xla) in a separate program run with import torch_xla.ut...
https://stackoverflow.com/questions/69328983/
Getting pytorch backward's RuntimeError: Trying to backward through the graph a second time... when slicing a tensor
Upon running the code snippet (PyTorch 1.7.1; Python 3.8), import numpy as np import torch def batch_matrix(vector_pairs, factor=2): baselen = len(vector_pairs[0]) // factor split_batch = [] for j in range(factor): for i in range(factor): start_j = j * baselen end_j = (j+1)...
After backpropagation, the leaf nodes' gradients are stored in their Tensor.grad attributes. The gradients of non-leaf nodes (i.e. the intermediate results to which the error refers) are freed by default, as PyTorch assumes you won't need them. In your example, your leaf nodes are those in vector_list created from torc...
https://stackoverflow.com/questions/69339143/
How can I fit a curve to a 3d point cloud?
My goal is to fit a line through a point cloud. The point cloud is approximately cylindrical but can be curved, which is why the fitted line should not be straight. I’ve tried several things, but this is my current approach : I use PyTorch to optimise on a surface equation and compute the loss for each point. However, ...
You can use Delaunay/Voronoi methods to get an approximation of the medial axis of the point cloud and pass a spline curve through it. See my previous answer here, which does exactly that for points sampled on a cylindrical surface. The figure below was taken from that answer. If your point cloud also has points from i...
https://stackoverflow.com/questions/69351109/
Exponential moving covariance matrix
I have time series data of a specific dimensionality (e.g. [T, 32]). I filter the data in an online fashion using an exponential moving average and variance (according to Wikipedia and this paper): mean_n = alpha * mean_{n-1} + (1-alpha) * sample var_n = alpha * (var_{n-1} + (1-alpha) * (sample - mean_{n-1}) * (sample ...
I have found the answer myself. It seemed to be a numerical problem. Since the eigenvalues of a positive definite matrix must be positive, I could solve it by applying an eigenvalue decomposition to every sample's covariance matrix and ensure that its eigenvalues are larger than zero: diff = sample - last_mean sample_c...
https://stackoverflow.com/questions/69351441/
Pytorch nn.parallel.DistributedDataParallel model load
Model saved with: torch.distributed.init_process_group(backend="nccl") local_rank = torch.distributed.get_rank() torch.cuda.set_device(local_rank) device = torch.device("cuda", local_rank) save_model = f'./model' Path(save_model).mkdir(parents=True, exist_ok=True) net = Net(args) # .to(device) mode...
In general, with PyTorch’s DistributedDataParallel, same model is kept across all nodes (as it’s β€˜synchronised’ during backpropagation). Best way to save it is to just save the model instead of the whole DistributedDataParallel (usually on main node or multiple if possible node failure is a concern): # or not only loca...
https://stackoverflow.com/questions/69356717/
How to remove the model of transformers in GPU memory
from transformers import CTRLTokenizer, TFCTRLLMHeadModel tokenizer_ctrl = CTRLTokenizer.from_pretrained('ctrl', cache_dir='./cache', local_files_only=True) model_ctrl = TFCTRLLMHeadModel.from_pretrained('ctrl', cache_dir='./cache', local_files_only=True) print(tokenizer_ctrl) gen_nlp = pipeline("text-generation&...
You can simply del tokenizer_ctrl and then use torch.cuda.empty_cache(). See this thread from pytorch forum discussing it.
https://stackoverflow.com/questions/69357881/
The output of my neural network is negative even if i am using ReLU on every layer
I am a beginner at deep learning.I am using PyTorch to implement a neural network to train some chemical data. the input range between (0 to 1 ) with no negative values and I am using the ReLu activation function on every layer so I didn't expect to see a negative value in the output my input size: 9 features the outp...
You are using a linear layer after relu, you can rewrite your last layer as: out = self.relu(self.linear5(out)) and your model definition from: self.relu1 = nn.ReLU() self.relu2 = nn.ReLU() self.relu3 = nn.ReLU() to a single definition: self.relu = nn.ReLU() and reuse this self.relu, as it is just a function without...
https://stackoverflow.com/questions/69361678/
How to downgrade from CUDA 11.4 to 10.2 & add sm_35 - CUDA error: no kernel image is available for execution on the device
I'm trying to run a piece of code on Pytorch, but I get the error: RuntimeError: CUDA error: no kernel image is available for execution on the device I've narrowed down the issue to be a missmatch of CUDA versions. My machine has 2 GPUs: a GeForce GTX 650 (compute capability 3.0) and a Tesla K40c (compute capability 3...
I've solved my problem. As stated in the comments, I required a version of PyTorch that supports sm_35 compute capability. It had little to do with the current CUDA version. In the end, I found these binaries: https://blog.nelsonliu.me/2020/10/13/newer-pytorch-binaries-for-older-gpus/ I finally fixed the issue by creat...
https://stackoverflow.com/questions/69364529/
Correct use of Cross-entropy as a loss function for sequence of elements
I have a sequece labeling task. So as input, I have a sequence of elements with shape [batch_size, sequence_length] and where each element of this sequence should be assigned with some class. And as a loss function during training a neural net, I use a Cross-entropy. How should I correctly use it? My variable target_pr...
Using CE Loss will give you loss instead of labels. By default mean will be taken which is what you are probably after and the snippet with permute will be fine (using this loss you can train your nn via backward). To get predicted class just take argmax across appropriate dimension, in the case without permutation it ...
https://stackoverflow.com/questions/69367671/
Understanding backpropagation in PyTorch
I am exploring PyTorch, and I do not understand the output of the following example: # Initialize x, y and z to values 4, -3 and 5 x = torch.tensor(4., requires_grad = True) y = torch.tensor(-3., requires_grad = True) z = torch.tensor(5., requires_grad = True) # Set q to sum of x and y, set f to product of q with z q...
I hope you understand that When you do f.backward(), what you get in x.grad is . In your case . So, simply (with preliminary calculus) If you put your values for x, y and z, that explains the outputs. But, this isn't really "Backpropagation" algorithm. This is just partial derivatives (which is all you asked...
https://stackoverflow.com/questions/69367939/
How to get outputs in the same order as inputs with multiple spawned processes running on multiple GPUs and batches of data processed by each?
I am using Pytorch Distributed Data Parallel approach and spawning multiple processes, each running on separate GPU.I am using Pytorch Distributed Data Sampler along with Data Loader for loading batches of input data to each process. My questions: Under the hood, how does Pytorch Distributed Data Sampler, Data Loader ...
The PyTorch documentation on DistributedSampler doesn't provide any guarantees regarding how data is distributed across processes and devices, other than the fact that it is, in fact, distributed across processes and devices. You shouldn't design your application to be dependent on an implementation detail of an exter...
https://stackoverflow.com/questions/69368042/
Is there any option at Pytorch autograd function for these problem?
Sorry for the vague title because I don't know exactly how to ask the question. I'm using pytorch's autograd function right now and I'm struggling with the results I don't understand. In common sense, the grad calculated by the loss is how far each parameter should go in the direction where the loss is minimized. Becau...
Your code screenshot shows that the two tensors are different due to floating point truncation error. Do not compare them with == sign, use isclose() function instead torch.isclose(grads[-1], grads_02[-1] * 5)
https://stackoverflow.com/questions/69368150/
what is model.training in pytorch?
hi i'm going through pytorch tutorial about transfer learning. (https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html) what is model.training for?? enter def visualize_model(model,num_images=6): was_training=model.training model.eval() images_so_far=0 fig=plt.figure() with torch.no_grad(): for i, ...
I think this will help (link) All nn.Modules have an internal training attribute, which is changed by calling model.train() and model.eval() to switch the behavior of the model. The was_training variable stores the current training state of the model, calls model.eval(), and resets the state at the end using model.trai...
https://stackoverflow.com/questions/69371652/
I cannot draw bounding box correctly
I can't draw the bounding box correctly. img = Image.open("/content/drive/MyDrive/58125_000893_Sideline_frame298.jpg").convert('RGB') convert_tensor = torchvision.transforms.ToTensor() img=convert_tensor(img) width=15 top=456 height=16 left=1099 img=img*255 boxs=[left,top,top+width,left+height] print(boxs) b...
You are using a top-left coordinate system while PyTorch uses x: horizontal left->right and y: vertical bottom->top. The bonding box provided to torchvision.utils.draw_bounding_boxes is defined as (xmin, ymin, xmax, ymax). Your mapping should therefore be: xmin = left ymin = top + height xmax = left + width ymax ...
https://stackoverflow.com/questions/69403235/
How to enable Intel Extension for Pytorch(IPEX) in my python code?
I would like to use Intel Extension for Pytorch in my code to increase overall performance. Referred this GitHub(https://github.com/intel/intel-extension-for-pytorch) for installation. Currently, I am trying out a hugging face summarization PyTorch sample(https://github.com/huggingface/transformers/blob/master/examples...
The key changes that are required to enable IPEX are: #Import the library: import intel_extension_for_pytorch as ipex #Apply the optimizations to the model for its datatype: model = ipex.optimize(model) #torch.channels_last should be applied to both of the model object and data to raise CPU resource...
https://stackoverflow.com/questions/69404795/
How to enable mixed precision training while using Intel Extension for PyTorch (IPEX)?
I am working on Dog-Cat classifier using Intel extension for Pytorch (Ref - https://github.com/amitrajitbose/cat-v-dog-classifier-pytorch). I want to reduce the training time for my model. How do I enable mixed precision in my code? Referred this github(https://github.com/intel/intel-extension-for-pytorch) for training...
Mixed precision for Intel Extension for PyTorch can be enabled using below commands, # For Float32 model, optimizer = ipex.optimize(model, optimizer=optimizer) # For BFloat16 model, optimizer = ipex.optimize(model, optimizer=optimizer, dtype=torch.bfloat16) Please check out the link, https://intel.git...
https://stackoverflow.com/questions/69405997/
Summing over product of tensor elements and vector
I'm trying to write a python code for a higher order (d=4) factorization machine that returns the scalar result y of Where x is a vector of some length n, v is a vector of length n, w is an upper triangular matrix of size n by n, and t is a rank 4 tensor of size n by n by n by n. The easiest implementation is just fo...
This seems like a perfect fit for torch.einsum: >>> torch.einsum('ijkl,i,j,k,l->', t, *(x,)*4) In expanded form, this looks like torch.einsum('ijkl,i,j,k,l->', t, x, x, x, x) and computes the value defined by your four for loops: for i, j, k, l in cartesian_prod: y += t[i,j,k,l] * x[i] * x[j] * x[k]...
https://stackoverflow.com/questions/69410396/
How to iterate over Dataloader until a number of samples is seen?
I'm learning pytorch, and I'm trying to implement a paper about the progressive growing of GANs. The authors train the networks on the given number of images, instead of for a given number of epochs. My question is: is there a way to do this in pytorch, using default DataLoaders? I'd like to do something like: loader =...
You can use torch.utils.data.RandomSampler and sample from your dataset. Here is a minimal setup example: class DS(Dataset): def __len__(self): return 5 def __getitem__(self, index): return torch.empty(1).fill_(index) >>> ds = DS() Initialize a random sampler providing num_samples and...
https://stackoverflow.com/questions/69427073/
How to solve this Issue "ModuleNotFoundError: No module named 'torch.tensor'"
How to solve this issue Traceback (most recent call last): File "C:/Users/arulsuju/Desktop/OfflineSignatureVerification-master/OfflineSignatureVerification-master/main.py", line 4, in from Preprocessing import convert_to_image_tensor, invert_image File "C:\Users\arulsuju\Desktop\OfflineSignatureVerifica...
In line 4, change this from torch.tensor import Tensor TO from torch import Tensor
https://stackoverflow.com/questions/69429076/
torch.cuda.is_available() is False only in Jupyter Lab/Notebook
I tried to install CUDA on my computer. After doing so I checked in my Anaconda Prompt and is appeared to work out fine. However, when I started Jupyter Lab from the same environment, torch.cuda.is_available() returns False. I managed to find and follow this solution, but the problem still persisted for me. Does anyb...
Seems to be a problem with similar causes: Not able to import Tensorflow in Jupyter Notebook You are probably using other environment than the one you are using outside jupyter. Try open Anaconda Navigator, navigate to Environments and active your env, navigate to Home and install jupyter notebook, then lunch jupyter n...
https://stackoverflow.com/questions/69438417/
Indexing a multi-dimensional tensor using only one dimension
I have a PyTorch tensor b with the shape: torch.Size([10, 10, 51]). I want to select one element between the 10 possible elements in the dimension d=1 (middle one) using a numpy array: a = np.array([0,1,2,3,4,5,6,7,8,9]). this is just a random example. I wanted to do: b[:,a,:] but that isn't working
Your solution is likely torch.index_select (docs) You'll have to turn a into a tensor first, though. a_torch = torch.from_numpy(a) answer = torch.index_select(b, 1, a_torch)
https://stackoverflow.com/questions/69439465/
Retrieve only the last hidden state from lstm layer in pytorch sequential
I have a pytorch model: model = torch.nn.Sequential( torch.nn.LSTM(40, 256, 3, batch_first=True), torch.nn.Linear(256, 256), torch.nn.ReLU() ) And for the LSTM layer, I want to retrieve only the last hidden state from the batch to pass through the rest of the layers. Ex: _, (hidden, _) = lstm(d...
You could split up your sequential but only doing so in the forward definition of your model on inference. Once defined: model = nn.Sequential(nn.LSTM(40, 256, 3, batch_first=True), nn.Linear(256, 256), nn.ReLU()) You can split it: >>> lstm, fc = model[0], model[1:]...
https://stackoverflow.com/questions/69443940/
How should I replace the sentence torch.Assert from pytorch-1.7.1 to some other sentence in pytorch-1.5.0
The thing is I need to reimplement a GAN model using torch1.5.0 but the previous torch1.7.1 version codes contains a torch.Assert sentence to do symbolic assert. What sentence should I use to do the same thing?
Just use python's native assert. That's what it does under the hood. torch._assert(x == y, 'assertion message') to be replaced with assert x == y, 'assertion message'
https://stackoverflow.com/questions/69447704/
the usage of @ operator in an implementation of extending nn.Module
I saw the following code segment for extending nn.Mudule. What I do not understand is the input_ @ self.weight in forward function. I can understand that it is try to use the weight information of input_. But @ is always used as decorator, why it can be used this way? class Linear(nn.Module): def __init__(self, in_...
The @ is a shorthand for the __matmul__ function: the matrix multiplication operator.
https://stackoverflow.com/questions/69451996/
Inverse operation to padding in Jax
I'm trying to learn how to use Jax and I stumbled upon the problem of converting the torch.nn.functionnal.pad function into Jax. There is a function to perform padding but I would like in the same way as in PyTorch use negative numbers in the padding (e.g F.pad(array, [-1,-1])). Does anyone have an idea or had the same...
The jax.lax.pad function accepts negative padding indices, although the API is a bit different than that of torch.nn.functional.pad. For example: from jax import lax import jax.numpy as jnp x = jnp.ones((2, 3)) y = lax.pad(x, padding_config=[(0, 0, 0), (1, 1, 0)], padding_value=0.0) print(y) # [[0. 1. 1. 1. 0.] # [0....
https://stackoverflow.com/questions/69453600/
Is there an actual minimum input image size for popular computer vision models? (E.g., vgg, resnet, etc.)
According to the documentation on pre-trained computer vision models for transfer learning (e.g., here), input images should come in "mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224". However, when running transfer learning experiments on 3-channel imag...
There is a limitation on your input size which corresponds to the receptive field of the last convolution layer of your network. Intuitively, you can observe the spatial dimensionality decreasing as you progress through the network. At least this is the case for feature extractor CNNs which aim at extracting feature em...
https://stackoverflow.com/questions/69471729/
How to multiply a set of masks over an array of n matrices or tensors in python without using loops?
I have N binary masks, along with N x M matrices. I wish to apply the ith mask onto the M matrices at the ith index of the matrix array. Their data types can be either torch tensors or numpy arrays. To illustrate, If I have an array arr: arr = torch.rand((2, 3, 3, 3)) or arr = tensor([[[[0.2336, 0.4841, 0.4121], ...
By using an integer indexing, you removed one of the dimension from arr (2nd axis), and you can't broadcast an array with shape (2, 3, 3) with (2, 3, 3, 3). To make them compatible again, you can add the dimension back by reshaping: mask.reshape((2, 1, 3, 3)) * arr Or keep the dimension from the first place by using s...
https://stackoverflow.com/questions/69474841/
Problem with Graph Neural Network in PyTorch Geometric
I'm trying to understand what is wrong with the following GNN model implemented in PyTorch class Net(torch.nn.Module): def __init__(self): super().__init__() self.conv = SAGEConv(dataset.num_features, dataset.num_classes, aggr="...
Function torch.nn.Module.forward should have at minimum one argument: self. In your case, you have two: self and your input data. def forward(self, data): # <- x = self.conv(data.x, data.edge_index) return F.log_softmax(x, dim=1)
https://stackoverflow.com/questions/69478259/
NLLLoss is just a normal negative function?
I'm having trouble understanding nn.NLLLoss(). Since the code below always prints True then what's the difference between the nn.NLLLoss() and using the negative sign (-)? import torch while 1: b = torch.randn(1) print(torch.nn.NLLLoss()(b, torch.tensor([0])) == -b[0])
In your case you only have a single output value per batch element and the target is 0. The nn.NLLLoss loss will pick the value of the predicted tensor corresponding to the index contained in the target tensor. Here is a more general example where you have a total of five batch elements each having three logit values: ...
https://stackoverflow.com/questions/69495926/
Is there a way to overide the backward operation on nn.Module
I am looking for a nice way of overriding the backward operation in nn.Module for example: class LayerWithCustomGrad(nn.Module): def __init__(self): super(LayerWithCustomGrad, self).__init__() self.weights = nn.Parameter(torch.randn(200)) def forward(self,x): return x * self.weights ...
The way PyTorch is built you should first implement a custom torch.autograd.Function which will contain the forward and backward pass for your layer. Then you can create a nn.Module to wrap this function with the necessary parameters. In this tutorial page you can see the ReLU being implemented. I will show here are to...
https://stackoverflow.com/questions/69500995/
Continue training with torch.save and torch.load - key error messages
I am new to Torch and using a code template for a masked-cnn model. In order to be prepared if the training is interrupted, I have used torch.save and torch.load in my code, but I think I cannot use this alone for continuing training sessions? I start training by: model = train_mask_net(64) This calls the function tra...
torch.save(model.state_dict(), PATH) only saves the model weights. To also save optimizer, loss, epoch, etc., change it to: torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'loss': loss, 'epoch': epoch, # ... }, PATH) To load them...
https://stackoverflow.com/questions/69508602/