user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
sai_m | Hi all,Is there any simple way to covert 4 channel images into RGB inside transforms? Any help is appreciated.Thanks | ptrblck | It depends what the 4 channels in the original input represent. E.g. if the 4th channel is the alpha channel and you don’t want to use it, you could transform the image using PIL or just slice the tensor:
transform = transforms.Lambda(lambda x: x[:3])
x = torch.randn(4, 224, 224)
out = transform(x… |
Armin_Dashti | I’m learning Object Detection from thistutorial. But when I try to run this code, I got a AttributeError: toWhy? I’m using CPU.Here is my code:from detection.engine import evaluate, train_one_epoch
from detection import utils
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
num_class... | ptrblck | The code tries to call the .to() method on a tensor while a PIL.Image is used:
~\anaconda3\lib\site-packages\detection\engine.py in <genexpr>(.0)
26
27 for images, targets in metric_logger.log_every(data_loader, print_freq, header):
---> 28 images = list(image.to(device) for … |
deshwal.mahesh | I am trying to learn build aU-NET architecturefrom scratch. I have written this code but the problem is that when I try to run to check the output of the encoder part, I am having issues with it. When you the run the code below , you’ll getimport torch
import torch.nn as nn
batch = 1
channels = 3
width = 512 # same as... | ptrblck | Your forward definition looks wrong, as you are trying to pass the input to each layer:
def forward(self, feature_map_x):
for layer in self.layers:
out = layer(feature_map_x)
return out
This should be working:
def forward(self, feature_map_x):
out = fea… |
PPB | I am trying to implement this following code on my system.GitHubGitHub - dvlab-research/Simple-SR: Include MuCAN, LAPAR, etc.Include MuCAN, LAPAR, etc. Contribute to dvlab-research/Simple-SR development by creating an account on GitHub.In the original code, they used two datasets named “DIV2k” and “Flicker2K” for trai... | ptrblck | I guess import datasets.mix_dataset doesn’t work so check the module name, folder name etc. and make sure you can import the file. |
Fuzhiyuan | I try to run my project with GPU Version in release mode, but my task manager shows that it seems to run on CPU? But this occasion has not occurred in Debug version.企业微信截图_16551027845570894×806 29.4 KBFrom the above picture, we can see that GPU utilization is 0, and most of the tensors appear to be deployed in memory i... | ptrblck | I don’t know any details about your workload but note that the CPU will still be used even if the actual kernel execution is done on the GPU. In this case the CPU would still be at least responsible for the kernel launches and usually also for the data loading and processing.
To properly see the GP… |
jinyuan.feng | use torch.spawndataloader: pin_memory=True.dataloader: num_worker>1.ERROR:RuntimeError: CUDA driver error: initialization error | ptrblck | I guess you are trying to re-initialize the CUDA context in each new process, which will fail. |
602389789 | Suppose I have training dataset with the size of 50 million, I would like to train it with a batch_size and epoch.If I separate the dataset into 5 subset with 10 million each one. and I train my model like this: first I train my model with subset_1 under the same batch_size and epoch as I mentioned before, and get Mode... | ptrblck | Your workflow of splitting the data into non-overlapping parts and then training the model on each part in a sequential manner would be equal to training the model on the entire dataset.
Of course you can’t expect to see bitwise-identical values as the pseudorandom number generator calls would be d… |
Ziyu_Huang | Hi! I am interested in some function in cpp torch, and I think, if I can debug cpp torch, I can understand it better! So can I change some code in cpp version, and then somehow run the code, maybe by compiling it into python?Thank you!!! | ptrblck | Followthese instructionsto build PyTorch from source. |
norhther | Im doing a research project where I want to create a custom loss function depending on the targets. I.e. I want to penalize withBCEWithLogitsLossplus adding a hyperparameterlambda. I only want to add this hyperparameter if the model is not correctly detecting a class.With more detail, I have a pretrained model that I w... | ptrblck | Hereis an example using nn.CrossEntropyLoss showing how the loss weighting is applied on an unreduced loss and normalized afterwards.
The DataLoader returns a batch containing samples in dim0 (the batch dimension) so you can directly access them. |
DRISS_ELALAOUI | please, I have an input of the shape[1, 2, 20, 135]and I have a modelNet = torch.nn.Conv1d(in_channels=2, out_channels=8, kernel_size=(20, 1), stride=1, bias=True)when I execute this lineNet(input)I get the following error:RuntimeError: Expected 2D (unbatched) or 3D (batched) input to conv1d, but got input of size: [1,... | ptrblck | nn.Conv1d expects a 3-dimensional input in the shape [batch_size, channels, seq_len] while you are using a 4-dimensional input.
If your input represents [batch_size, channels, height, width] use nn.Conv2d or manipulate the shape to create a 3-dimensional tensor (e.g. by flattening the spatial dimen… |
Ziyu_Huang | Hi! I am wondering the inner implementation about how nn.linear cope with input like (2, 33, 44), it is different from normal (33, 44). I am developing cuda kernel for matmul now.So I entered my pytorch code, and find this:def linear(input: Tensor, weight: Tensor, bias: Optional[Tensor] = None) -> Tensor:
r"""
... | ptrblck | This threadpoints to the CUDA implementations in case that’s helpful. |
Archit_Srivastava | I am training FFNN for MNIST with a batch size of 32. My first linear layer has 100 neurons, defined as nn.linear(784,100). When I check the shape of the layer using model[0].weight.shape, I get [100,784]. My input is of the shape [32,784]. It was my understanding that there are matrix multiplication Weights with the i... | ptrblck | Yes, the parameters and corresponding gradients are stored in the same shape and layout and thus can be subtracted from each other without any manipulations/transposes etc. |
adywi | Hello Torch users,I’m currently implementing a 3D resnet18 on fMRI data of dimension [27, 75, 93, 81]. I couldn’t do one epoch in 48 hours on two GPUs A100.I have already tried to transform my data directly into NumPy array in order to speed up the process.I already use the following code to run the model on 2 GPUs:if ... | ptrblck | nn.DataParallel is not the recommended approach for data parallelism as it can create an imbalanced memory usage on the devices and is slower than DistributedDataParallel (DDP). Use DDP with a single process per GPU (even on a single node) for a faster performance.
nvidia-smi gives you the GPU ut… |
Fst_Msn | torch version == 1.10.1Given:device = 'cuda:0'If I try:x = torch.Tensor([1.0], device=device)I got the following error:RuntimeError: legacy constructor expects device type: cpu but device type: cuda was passedWhat am I doing wrong ?I solved this by doing:x = torch.Tensor([1.0]).to(device)which works, but I would like t... | ptrblck | Use torch.tensor([1.0], device='cuda') (lowercase t) and it should work.
I would not recommend to use the legacy torch.Tensor, torch.FloatTensor etc. constructors. |
AidanShipperley | Hi, I have a very simple code example that demonstrates that identical implementations of a sequential model in both libtorch and pytorch have inconsistent weights and biases. This is performed on the same computer with the same updated version of libtorch/pytorch:Python:import random
import numpy as np
import torch
r... | ptrblck | I think this is generally correct. If you seed the code and print a simple torch.randn tensor before initializing the model you would see that the Python API as well as libtorch return the same values, which points to the same logic in these calls.
However, I don’t think there is a guarantee of th… |
MauroGentile | Hello,I have a network which is the combination of a CenterTrack network (GitHub - xingyizhou/CenterTrack: Simultaneous object detection and tracking using center points.) and a custom network that is fed with the embedding from the CenterTrack net. Original images goes through CenterTrack and I branch out a couple of ... | ptrblck | The error is raised, since you are most likely using multiprocessing in the DataLoader by specifying num_workers>0, which would then try to re-initialize the CUDA context.
Did you try the suggested workaround using the 'spawn' start method? |
maslenkovas | Hello! I need to pretrain embedding layer of a model in a self-supervised manner and then use this pretrained embedding layer in the other model with a different structure. Both models have embedding layer as the first layer. Is there is a way to transfer weights of this layer from the pretrained model EHR_Embedding() ... | ptrblck | It seems as if the self.embedding attribute isn’t the same layer in both models:
# A
self.embedding = nn.Embedding(self.vocab_size, self.embedding_size)
# B
self.embedding = pretrained_model
so I would guess that assigning the .weight attribute directly from A to B wouldn’t work.
However, if you… |
Qmin-Lee | SmartSelectImage_2022-06-07-14-34-251105×783 69.1 KBName Self CPU % Self CPU CPU total % CPU total CPU time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Callsaten::resize_ 0.10% 69.000us 0.10% 69.000us 8.625us 0 b 0 b 4.74 ... | ptrblck | That sounds strange and I cannot reproduce the issue as I get the expected 2x increase:
x1 = torch.randn(8, 200, 100, 200, device='cuda')
x2 = torch.rand_like(x1)
x3 = torch.rand_like(x1)
print(torch.cuda.memory_allocated() / 1024**3)
# 0.35762786865234375
y = torch.cat((x1, x2, x3), dim=-1)
prin… |
qudrnjs030 | I’ve been stuck here for a while now. Any help.batch_size = 64The error occurs here.( label = label[sorted_idx] )def train(args, data_loader, model):
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
min_loss = np.Inf
for epoch in range... | ptrblck | Yes, the issue is raised as label's shape doesn’t fit the max. index in your code, while it works for text.
Check the shapes of these two tensors (label and text) and check why you are expecting them to be the same and why that’s not the case. |
MagaMakhauri | Hi there!I am a begginer in ML and NN, but currently have to develop one at work.This is something I am interested in pregressed quite a bit, but after being able to predict one value based on one input, I am now facing a wall I cant climb over on my own.I have 7 inputs (year, month, day, class of the plane, departure,... | ptrblck | Yes, this is correct and would work for the first layer,
The previously described error is raised since you are reusing the same layers.
Remove the duplicated usage and it would work:
class Net(nn.Module):
def __init__(self, input_size): #input size (1x7)
super(Net, self).__init__()
… |
theycallmefm | Hi, I want to implement thetorch.gatherfunction, but I am confused about indexing.In my case, I have 4D tensor which has the size of[B, N, K, C]I want to sample S points from N. I have an indices tensor that has size of[B, S]In the end, I want a tensor that has size of[B, S, K, C]How can I achieve this? | ptrblck | This should work:
B, N, K, C, S = 2, 3, 4, 5, 6
x = torch.randn(B, N, K, C)
idx = torch.randint(0, N, (B, S))
out = x[torch.arange(x.size(0)).unsqueeze(1), idx]
print(out.shape)
# torch.Size([2, 6, 4, 5]) = [B, S, K, C] |
Rishabh_Kumar | I tried simulating the Ornstein Uhlenbeck process from torch sde. The SDE model looks like:$ dX_t = \theta (\mu- X_t)dt + \sigma dW_t $Here is my code:class OU(nn.Module):noise_type = "diagonal"
sde_type = "ito"
def __init__(self, theta, mu, sigma):
super().__init__()
self.theta = theta
self.mu = mu
se... | ptrblck | self.sigma seems to be a float while a tensor is expected as .size() is called on this return value.
I don’t know if transforming the float scalar into a tensor would work or if more changes are needed, but it might be worth a try. |
JamesDickens | I have two functions as part of a torch.Module objectdef trace_model(model, sample_input, save_fp=None):
model.eval()
traced_model = torch.jit.trace(model, sample_input)
if save_fp is not None:
traced_model.save(save_fp)
return traced_model
def serialize_model(model, sample_input, save_fp=None... | ptrblck | torch.jit.trace will record the used operations via executing the forward pass with the provided input. Conditional control flow and other data-dependent properties will be captured during this execution and saved into the graph.
torch.jit.script is able to understand loops, conditions, etc. and al… |
JamesDickens | I am trying to port a python PyTorch model to LibTorch.In python the line of code is:nn.Parameter(A) where A is a torch.tensor with requires_grad=True.What would be the equivalent of this for a torch::Tensor in C++ ?The autocomplete in my editor gives options for ParameterDict, ParameterList,ParameterDictImpl, Paramate... | ptrblck | To register a parameter (or tensor which requires gradients) to a module, you could use:
m.register_parameter("weight", torch::ones({20, 1, 5, 5}), false);
in libtorch. I don’t know if there is a proper parameter class and have seen the posted approach used in modules. |
Abir_ELTAIEF | I created a model using the Pytorch Lightning Module, and I have a machine with 8 CPUs and a GPU. Batch size = 8 and num workers = 8 are the values I’ve chosen. The loss function is about dice loss between masks and predictions (it’s about 2D MRI slices with masks (2 classes…)), but the dice loss did not improve at all... | ptrblck | Thanks for the detailed update!
I’m not familiar enough with torchmetrics so don’t know if the warning is related to the issue or not (I would guess it’s unrelated).
In any case, your use case sounds as if the seeding inside each worker might not work properly and thus you might use the same “rand… |
anuzcan | Greetings and thanks for the helpWhat will be the reason that when executing a .py file it fails to import my “torch” module but if I call it directly within the python interpreter, I have no problems.Ubuntu 20.04, and python 3.8.10Captura de pantalla de 2022-06-04 14-02-081366×768 84.2 KB | ptrblck | Your current file is called torch.py which could create these circular imports.
Rename it and it should work. |
sunhaozhepy | I’m currently using a GPT model implemented in PyTorch and I want to make some changes to the attention mechanism. Here’s my code (some parts are removed in order to make the code cleaner):import math
import logging
import torch
import torch.nn as nn
from torch.nn import functional as F
from .attentions import *
class... | ptrblck | self.blocks is defined as an nn.Sequential container via:
if self.attention == 'pos_fus':
self.blocks = nn.Sequential(*[FusionBlock(config) for _ in range(config.n_layer)])
else:
self.blocks = nn.Sequential(*[Block(config) for _ in range(config.n_layer)])
wh… |
matinhabi | Hello everyone,I want to useLSTMfor gesture classification. I wonder if there is any difference between unbatched input and batched input with size set to 1. I think the resulting neural network should be exactly same when we feed it with unbatched input or batched input and batch size = 1. Is this speculation correct?... | ptrblck | Both approaches will yield the same output with a different shape (with and without a batch dimension) as seen e.g. in this small test:
lstm = nn.LSTM(2, 2)
x = torch.randn(2, 1, 2)
out = lstm(x)
print(out)
out2 = lstm(x[:, 0])
print(out2) |
Sam_Lerman | Does atorch.utils.data.Datasetworker initiate fetching when its iterator is called?__iter__?__next__? Once the DataLoader collates the batch, does the worker automatically start pulling the next one or does it wait idly until the iterator is called again?TLDR: At what point does it fetch? What triggers the fetch? | ptrblck | The workers should start loading the data once the iterator is created and preload the prefetch_factor*num_workers batches. Afterwards each next call will consume a batch and let the corresponding worker load the next batch.
Here is a small example showing this behavior:
class MyDataset(Dataset):
… |
Fathima | This is my CM classclass ConfusionMetrics():
def __init__(self, threshold=0.5, apply_sigmoid=False, device='cpu'):
self.threshold=threshold
self.__matrix = torch.zeros(2,2).to(device)#rows are output
self.__apply_sigmoid = apply_sigmoid
def __label(self,y):
"""
convert... | ptrblck | The error is raised in:
---> 69 accumulate = M.accumulate()
TypeError: accumulate() missing 2 required positional arguments: 'targets' and 'outputs'
as accumulate expects to get two input arguments: targets and outputs as the error message claims:
def accumulate(self, targets, outputs):
… |
Ajay_Chawda | class Car_insurance(Dataset):
def __init__(self, encoding = "label_encode", embedding_layer = False, normal = False):
path = '../../data/insurance_claims.csv'
categorical_cols = ['policy_state', 'umbrella_limit', 'insured_sex', 'insured_education_level',
'insured_occupation', 'insured_hobbies',... | ptrblck | I’m not sure I understand the issue correctly.
self.embedding_sizes is currently initialized in __init__ if embedding_layer is set.
If you want to get its value, you should be able to directly access it (once set):
dataset = Car_insurance(...)
dataset.embedding_sizes
Alternatively you could also… |
Shen | Hi, recently my PyTorch ran into an issue:RuntimeError: CUDA error: unspecified launch failure
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.After this, the GPU got lost. Typingnvidia-smigaveUnable to determine the device handle for GPU 0000:02.00... | ptrblck | Thank you! Yes, the Xid 79 is helpful as it explains that the “GPU has fallen off the bus”, which can be a HW error, driver error, system memory corruption or thermal issue.
I think a few weeks ago I’ve seen the same issue where the power plug wasn’t fully connected to the GPU and caused the same i… |
sourav | am using Yolov3 by Ultralytics (PyTorch) to detect the behavior of cows in a video. The Yolov3 was trained to detect each individual cow in the video. Each image of the cow is cropped using the X and Y coordinates of the bounding box. Each image then goes through another model to determine whether they are sitting or s... | ptrblck | 7.50 MiB free; 448.00 MiB reserved in total by PyTorch
This indicates that the other application (TensorFlow in this case) is grabbing the entire device memory and doesn’t allow PyTorch to allocate it anymore.
If I’m not mistaken, this is the default behavior in TensorFlow, so you might want to ch… |
JWLee89 | Hello,I am trying to dynamically analyze the forward pass / operations performed on an input tensor X. Suppose we have the following code:import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super().__init__()
# These can all be found using named_modules() or children()
... | ptrblck | I don’t know what exactly you are trying to do, but maybetorch.fxcould help? |
111357 | torch version: 1.9.1+cpuWhen I run the demo intorch.nn.quantized.Conv1dm = nn.quantized.Conv1d(16, 33, 3, stride=2)
input = torch.randn(20, 16, 100)
# quantize input to quint8
q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0,dtype=torch.quint8)
output = m(q_input)I got the following error, do you have... | ptrblck | Could you update to the latest stable or nightly release, please, as the code works fine in 1.12.0.dev20220425? |
FreedomSlow | Hi, I was trying to integrate pretrained BERT model into my own custom model. Here is my custom class:class BERTClassifier(torch.nn.Module):
def __init__(self, bert_model, n_classes):
super(BERTClassifier, self).__init__()
self.bert_model = bert_model
self.max_len = 512
if isinstance... | ptrblck | torch.argmax is not differentiable and will thus break the computation graph.
Also, nn.BCELoss expects probabilities as the model output and is used for binary or multi-label classification use cases so you should use a sigmoid in this case. |
jayz | Hi,in the performance guide (Performance Tuning Guide — PyTorch Tutorials 2.1.1+cu121 documentation), it says:To use Tensor Cores: set sizes to multiples of 8 (to map onto dimensions of Tensor Cores)Does this mean when I have a tensor BCHW with (32,15,10,256), operations on this tensor within the autocast() context man... | ptrblck | Not necessarily as e.g. cuDNN could pad your inputs and use TensorCores internally.
Yes, the channels-last usage looks correct. |
jloomis | After installing a handful of versions of pytorch with CUDA (11.7 nightly,11.6 nightly,11.3), I can’t gettorch.version.cudato be anything but10.2[me@legion imagen-test]$ sudo pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
Looking in indexes: https://pypi.org/simple, h... | ptrblck | You are installing the default CUDA 10.2 wheel, as --extra-index-url https://download.pytorch.org/whl/cu117 is not a thing yet (check the URL and it will show an error) so pip install pulls the default wheel. Use the provided install commands from thewebsiteor verify the existence of internal whee… |
Omnia_Al-wazzan | HiI’m trying to combine the features of two MLP models.I have two tabular datasets of the same class that I want to fuse to improve accuracy. The straightforward approach is currently considering concatenation.Here is a summary of my two models; both models are identical except for the input features.MulticlassClassifi... | ptrblck | Since you want to pass both inputs to the model, I guess your forward method should be:
def forward(self, x1, x2):
x1 = self.model_EHR(x1)
x1 = x1.view(x1.size(0), -1)
x2 = self.model_G(x2)
x2 = x2.view(x2.size(0), -1)
x = torch.cat((x1, x2), dim=1)
x = self.classifier… |
Mickey_Han | Thank you very much for reading my question . A newbie here sorry if my question isnt asked quite rightcircle1746×856 1.64 KBfor example I have this image and want to convert it to binary tensor that only has 1s and 0s, I was just usingimport torch
import numpy as np
from PIL import Image
from torchvision import trans... | ptrblck | You could certainly reimplement these drawing functions, but if you don’t need to differentiate through them I would recommend to use already available and tested libraries such as OpenCV.
Here is a small example of drawing a circle and a line into a numpy array using OpenCV and then transforming t… |
zfzhang | Hi,I am defining a custom activation function, which inherits from Function class and has static methods forward() & backward(). If I call F.relu() inside forward(), will it incur autograd (which is undesirable)?Thank you! | ptrblck | @eqy’s suggestion would also work, but by default gradient calculation is disabled in custom autograd.Functions and you could check it via print(torch.is_grad_enabled()) which will return False inside the forward and backward methods. |
Trishna_Barman | In config file, VGG layer weights are initialized using this way:from easydict import EasyDict as edictMODEL = edict()MODEL.VGG_LAYER_WEIGHTS = dict(conv3_4=1/8, conv4_4=1/4, conv5_4=1/2)But how to initialize it using a parser? I have tried to do this the following way:parser.add_argument(‘–VGG_LAYER_WEIGHTS’,type=dict... | ptrblck | Try to load the file directly via torch.load and then model.load_state_dict as seen in my code snippet. |
sebquet | Hi,I am wondering what would be the best way to save the loss of every batch inside a training loop without creating a synchronisation point between GPU and CPU. Because the way I was doing it was to create a list on the CPU and adding every batch loss as a tensor to this list during the training loop (without calling ... | ptrblck | Appending a CPUTensor to a list doesn’t create the synchronization point, but moving a CUDATensor to the CPU will.
You might want to update PyTorch to be able to use this debug utility.
Your current approach should not create a synchronization point as you are not moving the data to the CPU as … |
peterbaile | I followed thedocumentationhere to use pytorch in C++. I was able to compile everything until the building stage where I bumped into an issue ofld: library not found for -lmkl_intel_ilp64. I’m wondering what’s the solution to it, thanks!I’m using Mac (OS is Catalina) and installed 1.11.0 libtorchScreen Shot 2022-05-26 ... | ptrblck | You might want to add the folder containing libmkl_core.so etc. to LIBRARY_PATH so that the build stage find these libraries. |
Jeet | After trying out several workaround to this problem , I am still stuck with this error message. I have a very basic Neural network called “Neuralnetwork”.class Neuralnetwork(nn.Module):
def __init__(self, in_features):
super().__init__()
self.disc = nn.Sequential(
nn.Linear(in_featur... | ptrblck | Your model expects a floating point input (a few layers are exceptions such as e.g. nn.Embedding which expects integer types) so transform your input to a FloatTensor via:
out = disc(sample.to(torch.float32)) |
wayne1226 | I do an element-wise multiplication as:a = a.unfold(1, val*2, 1).unfold(2, val*2, 1)
b=b.unsqueeze(dim=0).unfold(1, val*2, 1).unfold(2, val*2, 1)
a=((a*(a>c)).sum((3,4)))/((a>c).sum((3,4)))here, a is a [3,256,256,256,256] matrix, b is [1,256,256,256,256], and I got an OOM when I run this code, I also try the in... | ptrblck | If you don’t care about the timing, then the nested loop should work as it should use the least necessary memory. |
mesllo | I was wondering whether due to the high-resolution images in this large dataset it would affect my performance if I’m performing a resize step every time in the DataLoader, compared to just resizing it entirely from before. | ptrblck | Yes, assuming you would also resize the samples to a static shape during training and would not use a random transformation before.
I would recommend to profile both use cases to check if you would see a speed up. E.g. if your data loading pipeline is fast enough and would completely hide the lat… |
Mona_Jalal | I have already finetuned an Inception V3 model on my dataset which was already pretrained on ImageNet.Now, I need to load the save pt model and run it on test patches and extract the 2048 feature vector from Inception V3.I am not sure what code snippet I should use for extracting feature vectors of size 2048 on an ince... | ptrblck | Yes it looks correct and also works fine:
activation = {}
def get_activation(name):
def hook(model, input, output):
activation[name] = output.detach()
return hook
model = models.inception_v3()
model.avgpool.register_forward_hook(get_activation("avgpool"))
x = torch.randn(2, 3, 299… |
agu | I am trying to build thepytorch/masterbranch from source on an AWS instance. The default CUDAnvccversion is 10.0, found in/usr/local/cuda/bin/nvcc, and is incompatible with PyTorch version 1.9+ (since version 10.2 or above is required).On the instance, I also have newer versions of CUDA (e.g. in/usr/local/cuda-11.0/). ... | ptrblck | Try to use CUDA_HOME=/usr/local/cuda-11.0/ python setup.py install . |
RH_Jung | Hello, I am training a CLIP (ViT) model.I would like to skip a mini-batch when I find NANs in the output of the model.So this is a simplified pseudo code example.for data in dataloaders:output = model(data[0])if torch.isnan(output):continueloss = loss_fn(output, data[1])loss.backward()
optimizer.zero_grad()
loss.ba... | ptrblck | Yes I think you are right and since you are not calling backward() if the batch is skipped, the forward activations would be kept alive until the reference is deleted.
You could try to del output in this case and see, if this would free the intermediates. |
tanvir_14 | I have an input graph and its adjacency. After performing graph convolution my output shape is a 3D tensor (ex. 256,17,3). Now, for passing this output to Conv2d, I’m reshaping the output to a 4D tensor (ex. 256,1,17,3). So does it affect the output if I reshape or permute a tensor after convolution or graph convolutio... | ptrblck | In your example you are adding a channel dimension and the conv layer would thus use the last two dimensions as the spatial size.
Generally yes. Reshaping or permuting a tensor will affect the next operations as the layer(s) could use the input in different ways. E.g. in your previous example you … |
zelvet-velvet | Hi.Recently, I want to show tello stream with image detection. My question is how to convert the output to data type that cv2.imshow() can work. Is this possible? My first thought is to save model’s output to my local with save() method, and show it by cv2.imshow() method. It works but the stream with objects detecte... | ptrblck | cv2.imshow expects numpy arrays and you can transform PyTorch tensors to an np.array via tensor.numpy(). Depending on your use case you might need to push the tensor to the CPU first and maybe detach it additionally:
arr = tensor.detach().cpu().numpy()
Once this is done, make sure the expected dty… |
giaminhbk | Hello everyone.I try training my model however I met an OOM problem, I tried to reduce the batch and I want to add empty_cache() after each batch. Here is my question:If i addtorch.cuda.empty_cache()function after each batches, will it affect to ability to evaluate model?Will model weights, loss keep updated if I add ... | ptrblck | Calling empty_cache() will free the unused memory from the internal caching allocator and make is usable for other processes. You will not avoid OOM issues besides slowing down your code as the memory would have to be re-allocated with synchronizing cudaMalloc calls in the next iteration.
Besides t… |
Tianqi_Li | Good morning everyone,I am using LSTM to build the model of WGAN with gradient penalty, however, during the loss backward propagation for the critic, I have got the error ‘Double backwards is not supported for CuDNN RNNs’. So I wonder whether it is possible to solve this problem? Due to the fact that this is the model ... | ptrblck | You could either disable cuDNN globally via torch.backends.cudnn.enabled = False, which would most likely slow down your entire code or disable it for the RNN layer only via with torch.backends.cudnn.flags(enabled=False):. |
ikharitonov | Hi,I am trying to recreate a UNet-type architecture in PyTorch which has been originally written in TensorFlow.Here is the TF implementation:def tensorflow_unet_1024(input_img):
# encoder
conv1 = Conv2D(64, (3, 3), activation="relu", padding="same")(input_img)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
... | ptrblck | It seems you are seeing a relative error of ~1e-7 which is expected for float32.
Due to a potential different order of operations you cannot assume to see bitwise-identical values between different operations and algorithms. |
davidw82 | Hi all,What is the last PyTorch version to support CUDA10.1 when compiling from source?The way I understand it is that the latest few versions of PyTorch do require CUDA10.2, even when compiling from source. I’m building a software plugin that needs to work with the host software which is compiled against CUDA10.1 and ... | ptrblck | Yes, I guess so as this is the first commit I can find removing this CUDA requirement. |
ALMOUDI | Hello, I am applying segmentation on a dataset with 4 semantic labels and 1 null label 255 which is included in ignore index in loss function. When I test my model and visualize the prediction models seems to be giving values of one of the 4 semantic labels to the ignore index pixels. My questions is, is this random a... | ptrblck | The model will process all inputs using its trained parameters.
So e.g. in case you are using a CNN-like model, the conv kernels will also be applied to the pixels which would be later ignored in the loss calculation.
from this point of view the predictions will thus not be random and the model w… |
Lohith_Kumaar | Hey Guys,I am working on image classification problem with my custom dataset of plant disease and I want to deploy it a web application but unable to find a proper website or video.I am unable to know how to deploy a saved model onto the web.Can anyone help me deploy my trained model to the web?I have the model from mo... | ptrblck | You could check outthis tutorialbut I’m unsure how useful this would be for your use case. Also,torchservemight be interesting for your use case. |
Lohith_Kumaar | I was trying to do Inference from my saved model i got this error can anyone help me with it.import torch
import torch.nn as nn
from torchvision.transforms import transforms
import numpy as np
from torch.autograd import Variable
import torch.functional as F
from io import open
import os
from PIL import Image
import pat... | ptrblck | This won’t work:
if torch.cuda.is_available():
image_tensor.cuda()
as you need to re-assign the tensor:
if torch.cuda.is_available():
image_tensor = image_tensor.cuda() |
KoenTanghe | Context: I inherited a project using Python3 and PyTorch 1.11.0, and I was running this on Ubuntu 20.04 on an (old) desktop machine.When I run the code, I’m seeing this message (it’s not clear actually if this is an error or a warning):[W NNPACK.cpp:51] Could not initialize NNPACK! Reason: Unsupported hardware.I checke... | ptrblck | PyTorch should use a fallback if NNPACK cannot be initialized.
The warning is raised frominit_nnpack, which is called by _nnpack_available() and used inuse_nnpackto select the backendhereas ConvBackend::NnpackSpatial or ConvBackend::Slow2d. |
tarekiraki | I have the issue, that I use batchnorm in a multi layer case. For debug I initialized both frameworks with the same weights and bias. This works for the linear layers, I‘m not sure if it works for all the batchnorm parameters.(1) So, how can I use batchnorm to get the same results in pytorch as in tensorflow? Because I... | ptrblck | Most likely because the momentum definition is different, as PyTorch uses:
Mathematically, the update rule for running statistics here is x^new=(1−momentum)×x^+momentum×xt, where x^ is the estimated statistic and xt is the new observed value.
and a default value of 0.1 while TF uses:
moving_m… |
Maxwell_Albert | Hi I am using roberta-base models from huggingface finetuning RTE dataset with fp16.I am using torch.cuda.amp.autocast() but the output of the model is stilltorch.float32and there is no memory saving at all.Here is the codemodel = AutoModelForSequenceClassification.from_pretrained("roberta-base")
model = model.to(rank)... | ptrblck | I cannot reproduce the issue and get a memory saving using amp and this code:
import torch
from transformers import AutoModelForSequenceClassification
from transformers import RobertaTokenizer
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
model = AutoModelForSequenceClassification… |
Xuansheng_Wu | I am trying to develop a model which takes a sequence of word embedding(ts, dim)as input and return several groups of word embeddings(max_size, dim), wheretsis the numbers of words,dimis the dimension of word embedding, andmax_sizeis the max number of groups.To achieve this, we simply apply a linear layer to the word e... | ptrblck | It seems you want to use the floating point outputs of self.fc as an index, which won’t be differentiable. I’m not familiar enough with your use case to completely understand what you are trying to achieve. |
mk6 | Hi,I’m implementing the multi-process data loading logic for my ownIterabledataset. However I observed a strange behavior while playing with thesecondexample in the dochere, with implementingworker_init_fn.The following is a code snippet to reproduce.MyIterableDatasetandworker_init_fnare copied from the doc without any... | ptrblck | Based on the code snippet the shapes seem to be expected.
If you print the start and end indices from each worker you would see:
# num_workers=2
worker 0, start 0, end 250
worker 1, start 250, end 500
# num_workers=3
worker 0, start 0, end 167
worker 1, start 167, end 334
worker 2, start 334, end… |
Maxwell_Albert | Hi, I am using roberta-base to train RTE dataset. When I use torch.half() to change my models parameters, I find that after first backward, the loss of model will be nan.Is there any way to solve it? | ptrblck | FP16 has a limited range of ~+/-65k, so you should either use the automatic mixed-precision util. via torch.cuda.amp (which will use FP16 where it’s considered to be save and FP32 where needed) or you would have to transform the data and parameters to FP32 for numerically sensitive operations manual… |
Matthew_Wang | Hi, I want to overwrite the classifier layer of Distilbert as a pass through layer that does not do any calculation as I need to extract the pre-classification embeddings…I did this but it doesn’t work:model.classifier = torch.nn.Linear(768, 768)Can anyone help please? Thanks | ptrblck | You could replace it with nn.Identity which will return the input without any modifications. |
S_M | Hi, I want to convert the grayscale of MNIST images to RGB as its values are between 0 and 255. How is it possible for PyTorch? | ptrblck | To create the RGB channels, you could either repeat the gray channel manually or use transforms.Grayscale(num_output_channels=3). I’m not sure if you want to yield tensors in the range [0, 255], but if so you could use transforms.Normalize(mean=0., std=(1/255., 1/255., 1/255.)) after applying transf… |
jhp | Hi I have a question about saving the model.I currently doing some project regard to knowledge distillation, so I load the pretrained teacher model in the student model.When I finish the training, only thing that I want to save is the parameters of student model, but it seems that teacher model also included in the mod... | ptrblck | It depends on your currently used workflow and I assume you are storing the state_dict of a model containing both submodels. If so you might want to store the state_dict of the student model only by accessing it. If this description doesn’t fit your use case could you describe it a bit more? |
NearsightedCV | HiI am training a model using the UNET++ architecture… I have large images that I crop down to make this more manageable but I feel I should be able to handle more data using the dataparallel setup.Per the title I am running on eight 8GB gpus on a cluster. I am trying to run a model with an image size of 1024x1024 and ... | ptrblck | I don’t quite understand this statement as it seems you claim to be using these 8 GPUs as “one”?
Data parallel will execute the same model on each device so the memory limitations would still be the same, but you could increase the “global” batch size. |
Ziyu_Huang | Hi! I am writing cuda kernel for matmul, for research reason, (I have some ideas…so really need to write kernel by myself) I compared this kernel with cublas, the cublas is about 2 times faster than my kernel.Later I packaged my kernel into python package(follow pytorch’s official method!!Custom C++ and CUDA Extensions... | ptrblck | Note that CUDA operations are executed asynchronously so you would have to synchronize the code before starting and stopping the timers. Alternatively, use torch.utils.benchmark to profile the workloads which would add warmup iterations as well as synchronizations. |
Andre_Amaral_IST | I am trying to run the code in the same way i did previously n times and it worked but now it is giving me the following error: | ptrblck | The screenshot is a bit hard to read (you can post code snippets by wrapping them into three backticks ```), but it seems you are trying to allocate 11714362584 / 1024**3 ~= 10.9GB of data while your RAM is already full.
Check the memory usage via e.g. htop and make sure you have enough free RAM.
… |
vin | Hello,I have difficulties calculating the covariance matrix of a loop of signals of size 54 (the 54 denotes the total set of stored signals). However, when the calculation starts, only the first signal is executed. It seems that the current covariance script does only an operation on the first signal after no signal is... | ptrblck | Check if you are overriding a method name with a tensor variable name somewhere as it seems that sequential iterations fail. |
dbsx | I am using C++ torchlib, but I don’t know what to do it in c++ like that in pytorch:min_real = torch.finfo(self.logits.dtype).min
# or
min_real = torch.finfo(self.logits.dtype).tiny | ptrblck | I don’t think finfo is exposed in libtorch, but you should be able to use e.g.:
const auto int_min = std::numeric_limits<int>::min();
const auto int_max = std::numeric_limits<int>::max(); |
Otis_Chang | According toPyTorch documents, it seems we have to define the model structure before wemodel.load_state_dict(model_state_dict).If we save entire model to pth file and load pth bymodel = torch.load(PATH), the directory structure should not be changed.Actually, it seems we have to know model structure if we want to retra... | ptrblck | Scripting a model via torch.jit.script and storing it via torch.jit.save should create a model file which you could directly load via torch.jit.load and execute the model. |
natgolovach | Hi All!For some reason I can not read the logs from logs files as they look like that:ahparams"`u∑œŸ‹2 ≥jÍ∏ÕúÿA*
val_lossêéí>3¯°ıe
û ≠lÍ∏ÕúÿA*
epochzÙçwŸ‹2 ÿ
fªÕúÿA*
val_loss‰ÇÃ=ˆefi4e
û ÛfªÕúÿA*Why is that happening? this is “…lightning_logs/version_X/events.out.tfevents.1650580020.run-625dc32b6711b8302f650b5a-s5w9h... | ptrblck | If I’m not mistaken, tfevent files are stored as protobuf files so you might be able to read them via a protobuf library. |
SofiaCP | Dear all,I wanted to use automatic mixed precision to train my model.The output of my model is a weighted average of the output of several components,Y= w1y1 + w2y2 + ... + wkyk,wherey1,...ykis the output of each componentafter applying the sigmoid function(like a weighted averaged ensemble).For this reason, I cannot u... | ptrblck | From the docs:
The backward passes oftorch.nn.functional.binary_cross_entropy()(andtorch.nn.BCELoss, which wraps it) can produce gradients that aren’t representable in float16 . In autocast-enabled regions, the forward input may be float16 , which means the backward gradient must be representab… |
Mukesh1729 | I get this error after installing the latest version of torch .module ‘torch’ has no attribute ‘Module’. i did re-install it. Not sure how to go about it | ptrblck | Module is defined in the torch.nn namespace, so torch.nn.Module should work. |
Stapo | About half of the elements in the dataset have certain features, which need to go through a separate layer first. These are not missing features, but they simply don’t exist for all elements. Everything is part of the same problem/objective, therefore a separate model should not be used. My best guess for a solution i... | ptrblck | I don’t think this would be needed. As long as the self.fc_optional module is not used, it won’t get any gradients etc.
This might work, but I would also recommend to check an alternative of returning the same number of outputs from both branches without concatenating the zeros to it. E.g. you co… |
jiansong_zhang1 | I set up my PyTorch environment following the ’ [environment_gpu.yml’ file from this Github Projecthttps://github.com/graphdeeplearning/graphtransformer, which goes like this:name: graph_transformerchannels:pytorchdglteamconda-forgefragcoloranacondadefaultsdependencies:cudatoolkit=10.2cudnn=7.6.5python=3.7.4python-date... | ptrblck | Your Ampere GPU needs CUDA11+ while your current installation uses cudatoolkit=10.2 and will thus not work. The CUDA10.2 binaries are also not shipping sm_86 for the same reason.
Install the CUDA11.3 binary and it should work. If you are hitting conflicts, create a new conda environment and install… |
Ged | Hello,I have installed cuda 11.6, and realize now that 11.3 is required. Would you recommend to uninstall cuda 11.6 and re-install cuda 11.3?Thanks in advance! | ptrblck | Yes, I was referring to the pip wheels mentioned in your second step as the “binaries”.
The pip wheels do not require a matching local CUDA toolkit (installed in your first step), as they will use their own CUDA runtime (CUDA 11.3 in your selection), so you can keep your local CUDA toolkit (11.6U2)… |
chinmay5 | Sorry for the naive question but I am confused about the integration of distributed training in a slurm cluster. Do we need to explicitly call thedistributed.launchwhen invoking the python script or is this taken care of automatically?In other words, is this script correct?#!/bin/bash
#SBATCH -p <dummy_name>
#SBATCH --... | ptrblck | The script looks fine, but you might want to replace the launch command with torchrun as the former is (or will be) deprecated. Are you able to check the GPU utilization on this node and could you check if all devices are used? |
itaymr | Greetings,My data consists of time-series samples with 100 steps, each containing 2 features. In other words, my data is shaped as(samples, steps, features).The model I’m currently implementing works in TensorFlow, but I’m having trouble properly implementing it in PyTorch.class KnownDetector(Model):
def __init__(s... | ptrblck | You can pick between these approaches:
model output as raw logits + nn.CrossEntropyLoss
model output as log probabilities (via nn.LogSoftmax or F.log_sotmax) + nn.NLLLoss
numerically unstable approach by applying torch.log on probabilities (via torch.log(F.softmax(output, dim=1)))
Here is a code… |
Dazitu616 | Currently I want to train my model using FP16. However, I have a model which utilizes some CUDA ops borrowed from others’ repo. Those ops only accept FP32 input. Since I’m not familiar with CUDA, I don’t want to modify them. A workaround I’ve came up with is to always apply FP32 in the forward function of these ops, bu... | ptrblck | Yes, you can disable autocast for custom method as described in thisexample. |
Alexandra182 | Hello,I’m trying to implement automatic mixed precision for a DCGAN model, but after profiling the model using DLProf, it still says that AMP is not enabled.I read everything in the documentation about Automatic Mixed Precision, but can’t figure out what I did wrong. Can anyone help with this?Thanks a lot.from os impor... | ptrblck | Did you see where the bottleneck is coming from in the profile or were you able to compare the different kernel times? If so, were you seeing any change in the kernels and their runtime?
Also, could you rerun the profile with a static random input tensor to check if the data loading might create a … |
Qwwq | This is regarding saving and loading of models that are wrapped with DataParallel. Let’s say I wrap a model with DataParallel during training and save the checkpoints at some intervals. After that when I load the saved checkpoints in some other project that does not use DP, I get the error that the state_dict cannot be... | ptrblck | You could save the state_dict via torch.save(model.module.state_dict(), path) as describedhere. |
DVangelis | Hi to all,My first message here and brand new to pytorch and AI.I have trained a model and now I want to load unseen images to my model so I can segmentate them.To do that I self defined a dataset class ‘Mydataset’ that gets the directory of images and read the files by using the library tifffile and make some transfor... | ptrblck | Split this line:
prediction_tensors=model_trained(unseen_tensor.to(DEVICE))
into a loop and iterate the data:
model_trained.eval()
preds = []
with torch.no_grad():
for input in unseen_tensor: # you can use another logic here to create mini batches etc.
pred = model(input)
pred… |
Rasmus_Hoier | Hi,I would like to read the source code forcudnn.benchmark, but there is no link to it in the docs, and I couldn’t find it by googling. Where can I find it? | ptrblck | The benchmark flag will be passed eventually toalgorithm_searchwhere either cudnnGet or cudnnFind will be called in the v7 API. A similar approach is used for the experimental v8 API. |
Qwwq | I am using a register_hook on a tensor to print the gradients on stdout while using GradScaler in mixed precision mode during training. Do the prints on stdout reflect the scaled gradients or the unscaled ones?Thanks. | ptrblck | If you are using a torch.cuda.amp.GradScaler and print the gradients during the backward pass, the scaled gradients are shown. |
unofficial-Jona | I want to perform image augmentations lazily (during model training). This however affects only the images itself, not the bounding box (defined by 2 coordinates). Imgaug could do just that, but it only works preemptively and therefore needs massive amounts of memory. Any idea how to integrate the bounding box augmenta... | ptrblck | The detection models in torchvision use the resize_keypoints and resize_boxes method as seenhereso you might be able to reuse these (and potentially other detection transformations). |
John_M | I am trying a new training method (semi supervise GAN) but there is some result I don’t understand. The problem seems to be some Pytorch feature I don’t understand, but not in semi supervise GAN.The classifier is the EfficientNet_b0.for epoch in range(1, epochs + 1):print (’\nEpoch: {} '.format(epoch))for idx, dataLabe... | ptrblck | Some layer, such as batchnorm layers, will perform updates of stats during the forward pass.
In the example of batchnorm layers (which are used in EfficientNet_b0), the running stats will be updated using the current batch statistics and will thus change the validation results. |
PhysicsIsFun | Hi everyone!What is the current most efficient way to overwrite model parameters?For example, I have a trained network with a given weight parameter W, and I have another parameter W_new (generated by external code, i.e. not part of the network), and I want to replace W with W_new.W_new is already an nn.Parameter.Cheer... | ptrblck | You could .copy_ the new parameter into the old one via:
with torch.no_grad():
model.layer.weight.copy_(new_param) |
duspic | Greetings!I’m part of a newly-opened AI educational center in Croatia. In our educational program we focus on PyTorch for various DL tasks, as we wish for our students to really learn the right tools for the job (I’m a PyTorch man myself…)Our AI incubator is in its finishing stages, and I started to visualise the inter... | ptrblck | CC@jspisakwho might know more about these licensing issues |
angelognazzo | Hi everybody. I’m trying to do gaussian process regression to do noisy function approximation. I’ve defined my model but I get an error when computing the gradient of the loss function:“RuntimeError: grad can be implicitly created only for scalar outputs”In fact the shape of the loss that my model computes is the follo... | ptrblck | As the error suggests you would either have to reduce the loss first, e.g. via loss.mean().backward(), or you would need to pass the gradient explicitly to the non-scalar loss tensor, e.g. via loss.backward(torch.ones_like(loss)). |
Soothysay | Hi,So I have a Pytorch Tensor of size [4055, 4, 80]. Now I would like to get a resultant Pytorch tensor of size [4055, (4*80)] or [4055, 320]. How can I do that? | ptrblck | You can flatten the last two dimensions via:
x = torch.randn(4055, 4, 80)
print(x.size())
# torch.Size([4055, 4, 80])
y = x.view(x.size(0), -1) # keep dim0, flatten last dimensions
print(y.size())
# torch.Size([4055, 320])
z = torch.flatten(input=x, start_dim=1, end_dim=-1)
print(z.size())
# torc… |
vin | While running my script below, I get the error message, indicating a mismatch in the spatial structure of my CNN network during training. Mentioning an incoherence of the MaxPool at the activation function of the second CNN (conv2). Here is the shape of my tensor (torch.Size([157056, 40, 2])), which indicates the shape... | ptrblck | Check why labels is a tuple and try to pass it as a tensor to the criterion instead.
I don’t know why it’s a tuple currently, so cannot suggest a proper solution. |
A_Shamsadini | Hi, please help meimage1366×768 106 KB | ptrblck | You are setting the bias to None in a few layers, but expect this parameter to be available in kaiming_init:
if hasattr(module, 'bias'):
nn.init.constant_(module.bias, bias)
Make sure to check, if this parameter is available before using it.
Also, you can post code snippets by wrapping them i… |
deutschgraf | Hi all.I tried to create PyTorch wheel with cuda 11.6, but faced OOM error.I was following instructions from here:GitHub - pytorch/pytorch: Tensors and Dynamic neural networks in Python with strong GPU accelerationAfter necessary dependencies was installed I tried to build pytorch with command:python3 setup.py bdist_wh... | ptrblck | You could limit the number of processes via MAX_JOBS=nb_jobs to avoid running out of memory. |
Z_Huang | Hi community,I have created 2 CNN models. The first model is my baseline model and the second model is an improvement on top of the first model.I have observed one weird scenario. These two models always produce different results (difference between +0.05% and -0.05%). Sometimes model one produces a better result and s... | ptrblck | I don’t think using a single seed (or the same parameters) would give you a good signal, since this seed (or parameter set) could stil be beneficial for one of the models.
To properly check the model accuracy, you could rerun each training script using different seeds and calculate the mean +/- std… |
111242 | I am trying to usesklearn.metrics.average_precision_scoreas the loss function as follows:optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for i, (region, labels) in tqdm.tqdm(enumerate(train_loader)):
region = region.to(device)
labels = labels.to(device)
# Forward pass
... | ptrblck | The error message points to a detached computation graph and while calling .requires_grad_() on the loss tensor would get rid of this error message, it would not fix the underlying problem.
You are currently breaking the computation graph in various places:
calling .detach() on a tensor detaches… |
Skyler_Huang | Code is:time1 = time.time()unique, inv = torch.unique(src, ,sorted=False, return_inverse=True)time2 = time.time()src2 = src.clone()time2 = time.time()unique, inv = torch.unique(src2, sorted=True, return_inverse=True)time3 = time.time()print(time2- time1, time3-time2)get the time: 0.015712261199951172 0.0005769729614... | ptrblck | In case you are using the GPU, you would have to synchronize the code before starting and stopping the timers since CUDA operations are executed asynchronously. The better way to profile such workloads would be to use torch.utils.benchmark. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.