user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
JamesDickens | Is it possible to print the version of CUDA and cuDNN that a given build of LibTorch was compiled against in C++? | ptrblck | This postshows the corresponding calls. |
HfCloud | I’m working with C++ extension for pytorch, and I have such a question: pytorch asynchronously launch CUDA kernels, suppose we have these codes:__global__ XXXKernel(float *a, float *b) {
//some computational workload with a, b
}
at::Tensor XXX(at::Tensor a, at::Tensor b) {
XXXKernel<<<...>>>(a.data_pt... | ptrblck | The kernel launches aren’t asynchronous but the kernel execution. The launches themselves are executed by the host and in stream-order.
Yes, the host can return and continue its execution before the GPU work is done.
No, this shouldn’t be possible as the reference count should be increased whil… |
bing | Hi,I am trying to install current pytorch 2.0. Is it stable, on running the python version, I am getting the below version-2.1.0.dev20230415Is this the stable one,which everyone is talking about?Thanks. | ptrblck | On theGet Startedpage you will find the install matrix showing “Stable (2.0.0)” and “Preview (Nightly)”.
You have installed a nightly release based on the version number which contains the date of the build (April 15, 2023, so today). |
rgbarriada | Hi there,I’m trying to implement a very simple model (multi layer perceptron) to tackle a binary classification problem but the loss function does not decrease and is saw-shaped.I do have very few labelled samples: (train (60) | test (15)). The input data is tabular from 7 different data types, which is then normalized... | ptrblck | Your model is able to overfit random samples:
class CustomModel(nn.Module):
def __init__(self, ):
torch.manual_seed(3)
super(CustomModel, self).__init__()
self.fc1 = nn.Linear(7, 60)
self.fc2 = nn.Linear(60, 100)
self.fc3 = nn.Linear(100, 30)
self… |
setsailforfail | Hi there!I am trying to build some PyTorch functions, like convolution 2D, from scratch using numpy.To achieve this, I need to check if my current implementations are correct, before I move on to the next implementation. I got the forward pass correct, however, for the backward pass it is not so simple to compare the o... | ptrblck | This line of code:
explicitly detaches the outpute tensor and recreates a new deprecated Variable.
I would assume you want to check the weight and data gradients as seen here:
conv = nn.Conv2d(3, 3, 3)
x = torch.randn(1, 3, 24, 24, requires_grad=True)
out = conv(x)
# grad w.r.t. weight
wgrad = … |
anghel | Hello! I would like to implement a FIR Filter using pytorch nn.Conv1d. i have computed the filter’s weights and I just want to compute the convolution using nn.Conv1d but I get some problems. Can anyone help me?I got an error like: RuntimeError: Input type (CPUComplexFloatType) and weight type (CPUComplexDoubleType) sh... | ptrblck | The error message points to a dtype mismatch of your input and weight tensor. Make sure both are using the same dtype by transforming one of them. |
vdw | To get a bit more familiar with hooks (just forward hooks for now), I’ve created a very simple LSTM model:class SimpleLSTM(nn.Module):
def __init__(self, vocab_size, out_size):
super().__init__()
self.embed = nn.Embedding(vocab_size, 5)
self.lstm = nn.LSTM(5, 4, bidirectional=T... | ptrblck | I’m not sure how your forward hook looks like, but I would guess you might be indexing into input and output in a way which might drop the batch dimension.
I’m using a small and naive helper util. to flatten the potentially nested input/output tuples and get this output using your code:
class Simp… |
Erfan_Dejband | Hi,I define a layer ininitfunction but I don’t use it in forward function. why it still cause the number of trainable parameter change?and what it mean? (dose it mean this layer is not in forward path but in backpropagation path exist?)and what if I want use a layer conditionally (i.e. each 20 epoch, or if error is les... | ptrblck | model.parameters() will return all properly registered parameters of the model and all of its children regardless if these parameters/modules are used in the forward or not.
No, the computation graph will be created during the forward pass, not during the initialization.
You can use conditions … |
samarendra109 | I am trying to do a pytorch implementation of the following paper,OpenReviewBeyond neural scaling laws: beating power law scaling via data pruningWe show in theory and practice that power law scaling of error with respect to dataset size can be improved via intelligent data pruning.This paper uses various metrics to pr... | ptrblck | In section B I see:
CIFAR-10 and SVHN. CIFAR-10 and SVHN model training was performed using a standard
ResNet-18 through the PyTorch library. Each model was trained …
Data pruning for transfer learning. To assess the effect of pruning downstream finetuning data
on transfer learning performanc… |
Charlie0257 | For example, I have a tensora = tensor([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])indices matrixes areb = torch.LongTensor([0, 2, 3])andc = torch.LongTensor([2, 4])I can get the d = a[b,:][:,c], but how can I assign the-dtoa[b,:][:,c]?Furthermore, ho... | ptrblck | I assume a[b,:][:,c] represents the working reference and you would like to assign a new value to these indexed values?
If so, this would work:
a = torch.tensor([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18,… |
droid | I am training an inpainting GAN model. I get the errorRuntimeError: Could not infer dtype of slicewhen trying to utilize array slices for selecting parts of an image. I don’t understand why this error occurs.My batch data is composed of 4 items: a tensor of images, a tensor of masked images, a tensor of mask patches, a... | ptrblck | It seems tuples or lists of slice objects are unsupported and the error is raisedhere.
The same seems to apply for numpy, too:
ideal_discrim_output = torch.ones(1, 1, 256, 256)
mask_slice = (slice(None, None, None), slice(31, 47, None), slice(31, 47, None))
ideal_discrim_output[0, [slice(None, No… |
ado_sar | I am experimenting with Pytorch and I want to build a 3D CNN. My input is a tensor of size25x25x25and the output is a binary[0, 1]. I have defined the following architecture:# Architecture of CNN
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv3d(in_channels=1, o... | ptrblck | Your model works fine for me:
model = Net()
x = torch.randn(2, 1, 25, 25, 25)
out = model(x)
print(out.shape)
# torch.Size([2, 2])
x = torch.randn(64, 1, 25, 25, 25)
out = model(x)
print(out.shape)
# torch.Size([64, 2]) |
danish_nazir | Hi All,I want to skip training iteration for a single GPU when training loss is greater than 10,000 (for example). The naive way of doing it is as follows.for x in train_dataloader:
optimizer.zero_grad()
out = model(x)
out_criterion = criterion(out, x)
... | ptrblck | Maybe you could allreduce the losses, check its value, and skip the step() on all ranks instead of checking it on each rank separately which would diverge the runs. |
Sam-gege | As stated, in theExtending Pytorchdoc, the example:import torch
from torch.autograd import Function
# Inherit from Function
class LinearFunction(Function):
# Note that forward, setup_context, and backward are @staticmethods
@staticmethod
def forward(input, weight, bias):
output = input.mm(weight.t(... | ptrblck | The example works for me:
# Option 1: alias
linear = LinearFunction.apply
x = torch.randn(10, 10)
lin = nn.Linear(10, 10)
out = linear(x, lin.weight, lin.bias)
out.mean().backward()
print(lin.weight.grad.abs().sum())
and you might want to check theCombined or separate forward() and setup_context… |
cneyang | Shuffling the input before feeding it into the model and shuffling the output the model output produces different outputs.I think it has something to do with GPU and batch norm since the problem only happens in train mode only on CUDA not CPU.Does anyone know why this is happening?import torch
import torchvision.models... | ptrblck | nn.BatchNorm2d layers will take the stats from dims [0, 2, 3] and indeed shuffling the samples should not change the applied function. However, you are changing the order of operations (or rather samples in this case), which might show small errors due to the limited floating point precision order.
… |
hubert233 | I am using torch2.0 with cuda12.0. The env is installed bypip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118. However, I found the distributed training stucks with no output. The GPU usage is normal, as I increase the batch size , the GPU usage will also rise. However, the mode... | ptrblck | The PyTorch binaries ship with their own CUDA libs as already mentioned and I doubt your locally installed CUDA toolkit is related to the mentioned issue, as it won’t even be used unless you build PyTorch from source or a custom CUDA extension.
Good to hear DDP is working as it’s the recommended wa… |
chenpirate | Hello, I have some problems, can anyone help me?I am using my trained Resnet34 network, and my attempt to convert the trained network to ONNX model fails, and the error is as follows.Traceback (most recent call last):
File "/home/private/hrrp/NanHu/resnetV2/model.py", line 216, in <module>
torch.onnx.export(model... | ptrblck | I cannot reproduce the issue using torch==2.0.0+cu118 and onnx==1.13.1 and get:
dummy_input = torch.randn(10, 3, 224, 224, device="cuda")
model = torchvision.models.alexnet(pretrained=True).cuda()
input_names = [ "actual_input_1" ] + [ "learned_%d" % i for i in range(16) ]
output_names = [ "output… |
Sourabh | I am doing the following :A model is used as an encoder.The model predicts some outputs which I then take and convert into a numpy array. (so I also detach them first from the tensor.)During the course of subsequent calculations on this numpy array , I use aargmax()to finally return me something ( for example something... | ptrblck | A non-differentiable operation will break the computation graph and will thus not allow you to calculate the gradients for any parameter previously used in the forward pass. Setting the requires_grad attribute of the detached tensor to true won’t help and somehow attach this tensor back to the comp… |
PedroA | I’ve been trying to reproduce to results found on this paper, but i can’t get to code to work.https://github.com/Tangsenghenshou/Detecting-Generated-Images-by-Real-ImagesUses code from:https://github.com/PeterWang512/CNNDetectionI need to copy the weights of a pre-trained ResNet50, and put them into a modified ResNet50... | ptrblck | Yes, I would recommend to check the parameters of both models and to clarify why these differ and if it’s expected.
Based on the posted error message it seems you are mixing the weight parameters with the bias parameters which causes the shape mismatches.
I would also recommend to use strict=True … |
BenediktAlkin | Hi!I’m encountering an issue where the backward pass oftorch.nn.functional.scaled_dot_product_attentionfails on a H100 GPU but doesn’t on an A100 GPU.I’ve tested this with the following scriptimport logging
import sys
import torch
import torch.nn.functional as F
def main():
# setup
logger = logging.getLogger... | ptrblck | Thanks for reporting the issue!
I can reproduce an illegal instruction using torch==2.0.0+cu118:
========= Illegal instruction
========= at 0x48f0 in void attention_kernel_backward_batched<AttentionBackwardKernel<cutlass::arch::Sm80, cutlass::bfloat16_t, (bool)1, (int)64>>(T1::Params)
========… |
prsm | (Full disclosure: I’ve asked this question at StackOverflow as well. Whomever answers it here my wish to answer it there too:How do I use pinned memory with multiple workers in a PyTorch DataLoader? - Stack Overflow)I’m learning about methods to accelerate the training of deep-learning models using PyTorch. FromPin_mem... | ptrblck | It seems you want to re-implement a simple custom collate_fn including the ability to pin memory which is then failing due to a re-initialization of the CUDA context.
The easier approach would be to just use the pin_memory argument in the DataLoader and I’m unsure why you want to create multiple po… |
Mialee | First, let’s clarify what a name combiner is. A name combiner is a tool or feature that allows you to combine two or more names into a single name. This can be useful in many situations, such as when you need to create a mailing list or a database of people’s names.Excel is a powerful spreadsheet software that allows y... | ptrblck | I guessthis Microsoft Excel forummight be a good place. |
jgscott | The context here is a scientific machine learning problem in which training data (which happens to be sequences) is simulated from an underlying ground-truth scientific model. A key wrinkle is that it’s important that the model sees simulations of different sizes during training. So a minibatch of data has shape [bat... | ptrblck | The issue is expected since each worker is a separate process working on a copy of the Dataset.
You could try to share a data structure between all workers and manipulate it from the main thread e.g. via:
class TestDataset(Dataset):
def __init__(self, n_sims, gen_sample, num_workers=0):
… |
Ustinian_W | import torchimport torchvisionfrom torch import nnfrom torchsummary import summarymodel = torchvision.models.resnet18(pretrained=False)model.avgpool = nn.Identity()model.fc = nn.Identity()x = torch.randn(size=(2,3,128,128))y = model(x)print(x.shape)print(y.shape)the output istorch.Size([2, 3, 128, 128])torch.Size([2, 8... | ptrblck | The nn.Identity layer is not flattening the activation, butthis torch.flattencall defined in the forward method via the functional API. |
JuyiLin | I have a tensor , input size = (3,4)I have to change the second row with new size = (1,4)How can I change it while keeps the gradient?When I used these codes, it showsx.masked_fill_(mask, 0) # set the values of cached nodes in x to 0
x += emb # add the embeddings of the cached nodes to x
return xRunt... | ptrblck | Cloning the tensor might be the right approach and I don’t understand the last claim:
This small code snippet works fine for me:
x = torch.randn(3, 4, requires_grad=True)
mask = torch.randint(0, 2, (3, 4)).bool()
emb = torch.randn(1, 4, requires_grad=True)
out = x.clone()
out.masked_fill_(mask, … |
dirkcremers | Hi,I am trying to get a summary of the pre-trained model by using the following code:import torchvisionfrom torchsummary import summarymodel = torchvision.models.vit_b_16(weights=‘IMAGENET1K_SWAG_E2E_V1’)summary(model,input_size= (3, 384, 384))However, I do not understand the error output which is provided. Can somebod... | ptrblck | torchsummary is deprecated as it wasn’t updated in a couple of years as seen intheir repository. Use torchinfo instead which works for me after adding the missing batch dimension:
import torchvision
from torchinfo import summary
model = torchvision.models.vit_b_16(weights='IMAGENET1K_SWAG_E2E_V1'… |
pvtien96 | Hi,I make a custom layer that has the parameterweightof size(Cin, Cout, rank).In theforwardmethod, I need to permute weight as follows:weight_col = self.weight.permute(1, 0, 2).reshape(self.in_channels, self.out_channels * self.rank)During the training of the model, it yields some odd errors withnanvalue.From my [readi... | ptrblck | No, this should not be the case as only the metadata of the tensor is changed.
Yes, this might work but I would still recommend trying to narrow down where the NaN values come from. |
JungHwang | Hi,I was implementing logging snippets in Ultralytics YOLOv8, and I realized that they way it calculates loss in training is the following# Forward
with torch.cuda.amp.autocast(self.amp):
# a couple of lines of code
self.loss, self.loss_items = self.criterion(preds, batch)
if RANK != -1:
self.loss *... | ptrblck | No, DDP would not aggregate the losses from different ranks as each rank gets an independent input and calculates “its own” gradients. The gradients are allreduced during the backward pass and eventually all .grad attributes contain the same gradients before the corresponding parameters are updated. … |
gursi26 | I am working on an image classification model that classifies emotion of the face in the image. I found that the model produces near identical outputs for different training examples when set to eval() mode, but this does not occur for the train() mode. Why does this happen?Specifications :MacOStorch version 2.0.0torch... | ptrblck | I’ve seen this effect sometimes when the model was “saturating” the outputs (and sometimes only returned the last bias term as the penultimate activation was zeroed out by a relu).
In these runs it helped to use a smaller model but I also guess that e.g. different parameter initialization could hel… |
D_Kab | Running on Windows 11, installed using the pip command on the website.CUDA 1.8I am able to run using the CPU but when I set device=‘0’ it crashes giving me the following error:Could not run 'torchvision::nms' with arguments from the 'CUDA' backend. This could be because the operator doesn't exist for this backend, or w... | ptrblck | Your install command should work and also installs the proper libraries in my setup:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
Looking in indexes: https://download.pytorch.org/whl/cu118
Collecting torch
Downloading https://download.pytorch.org/whl… |
bdabykov | I am trying to finetune a ProtGPT-2 model using the following libraries and packages:I am running my scripts in a cluster with SLURM as workload manager and Lmod as environment modul systerm, I also have created a conda environment, installed all the dependencies that I need from Transformers HuggingFace. The cluster a... | ptrblck | Yes, you have installed the CPU-only conda binary:
pytorch 1.12.1 cpu_py38hb1f1ab4_1
as already speculated.
You can select the desired CUDA version from the install matrixhere, copy/paste the command, and it should install the right binaries. |
SimonBet | Hello !I’m trying to use a ResNet18 model to process Sentinel-2 satellite imagery for a regression problem. I have weights that were pre-trained on 13 channels, but I’d like to add channels for additional information (temperature, sea depth etc.). As I have a very limited amount of data, I can’t afford to re-train the ... | ptrblck | I think your concern is valid and I would also expect that at least finetuning of the first layer is needed. I don’t know if retraining the already pretrained layers is needed or helps.
As an alternative you could also consider using a new “mapping” layer, which would transform your inputs channels… |
JuyiLin | I want to know how my GPU is used for my gradients and optimizer state;which function should I use?And I wonder where I should place this function. Is there any good demo? | ptrblck | max_memory_allocated will show the peak memory usage for allocated memory since the beginning of the script execution or since you have explicitly reset the peak via reset_peak_memory_stats().
This can be useful to check e.g. how high the peak usage is during the backward pass, as it might be trick… |
setsailforfail | Hi there!I am currently trying to train a cGAN model from scratch. It works fine, however, the training seems very slow for the hardware I use (4090). To learn the most from this issue, I would like to spot an error in my code first. I am not sure if I can just copy paste the whole model (200 lines of code), so maybe s... | ptrblck | Using multiprocessing to load and process the data is a good approach and would avoid using the main process for this task (which is also responsible to launch the CUDA kernels etc.).
I’m not sure what concern you have regarding this change.
I would recommend checking ourPerformance Tuning Guid… |
Kore_ana | Hello! Is it possible to load an 8 bit unsigned integer as a 8 bit float between 0~1(?)(if it exists).I have a data that is inherently an 8bit unsigned integer (0~255), but I want to normalize it to 0~1 before performing the forward pass. I guess there would be two ways to do this :since torch tensor seems to support 8... | ptrblck | The second approach is the common one and an uint8 image tensor will be normalized to a float32 tensor in the range [0, 1] using torchvision.transforms.ToTensor() as seen in this example:
# load uint8 image
img = PIL.Image.open(PATH)
# or generate random image
img = transforms.ToPILImage()(torch.ra… |
dragonHyeon | When we try to implement GAN training code, we should do backward for discriminator twice for real image case and fake image case. However we don’t use retain_graph=True for discriminator backward. As I know we should use retain_graph=True to prevent removing the computational graph but my code (also pytorch official d... | ptrblck | Using retain_graph=True will keep the computation graph alive and would allow you to call backward and thus calculate the gradients multiple times.
The discriminator is trained with different inputs, in thefirst stepnetD will get the real_cpu inputs and the corresponding gradients will be compute… |
jwillette | I am wondering if there is anything special about the forward method which DDP must use. Sometimes it is convenient to have a model call different methods during training for different tasks to avoid bundling everything up in the forward method with more complicated logic. For example, say I have the following module,c... | ptrblck | I would not use custom forward methods, as these would skip hooks (the same would happen if you manually call model.forward(x) instead of model(x)).
E.g.this codeuses forward_pre_hooks to copy to lower precision and could easily break.
Also,herethe self.module is called, which will internally … |
octadion | Traceback (most recent call last):File “train.py”, line 531, inmain() # pylint: disable=no-value-for-parameterFile “/home/octa/anaconda3/envs/venvdiffgan/lib/python3.7/site-packages/click/core.py”, line 1130, incallreturn self.main(*args, **kwargs)File “/home/octa/anaconda3/envs/venvdiffgan/lib/python3.7/site-packages/... | ptrblck | The issue seems to be specific to Diffusion-GAN and solvedhere. |
tanay_mehta | I am working on a problem where I need to have my entire dataset as one big.ptfile on the disk. But since that file might exceed the size of either my GPU or RAM, I want a possible way to load it in chunks usingtorch.load.Is there a way to do that? If not, is it a good potential feature request? | ptrblck | You could store the tensor as a numpy array and use numpy.memmap to access chunks of the array. |
Bersk | Hi all,I am considering that similar or related topics have been asked before (such as inweights-of-cross-entropy-loss-for-validation-dev-setandapply-weightedrandomsampler-to-validation-test-splits-makes-sense). However, I still have some confusion as those and previous post include different code snipets for me to und... | ptrblck | Yes, the weighted loss can be reused to get a signal about overfitting as@KFrankexplains inthis post.
Both datasets should come from the same domain and have the same or similar distributions as also explained in the linked post.
For the final run on the test data you should calculate the metric… |
Sanjit_Sarda | Hi all,I am a bit new to torch and have only used it on VMs before. I am now trying to use it on my computer and it doesn’t seem to be working.When Iprint(pycuda.driver.Device.count())I get1, however when Iprint(torch.cuda.is_available())I getNone.I tried reinstalling both torch and cuda and I still get this issue. Can... | ptrblck | Thanks for the update as it confirms you’ve installed the CPU-only binary.
Refer thethese install instructions, select the desired CUDA runtime (11.7 or 11.8), copy/paste the install command, and make sure the PyTorch binary indicates the CUDA version in its name.
Also, I would recommend installi… |
MartinZhang | what’s theaten::index?Where can I find documentation to explain this?thx. | ptrblck | You won’t be able to find a proper documentation as the libtorch docs are quite lacking. The function signature is definedhere, which at least shows the expected input arguments. |
moreblue | Hi, I’m trying to get the output from an intermediate layer from resnet50 using two different methods:create_feature_extractorand the forward hook followinghere.Here’s the full code that I minimally changed fromhere:import torch
from torchvision.models.feature_extraction import create_feature_extractor
model = torch.hu... | ptrblck | There are a few issues in your code:
You are registering the forward hook on another module (model_layer points to model.layer1 while the feature_extractor points to model.layer1[0].bn3).
After fixing this issue in your forward hook approach you are storing a reference of the batchnorm layer outpu… |
ays | I have a pretrained model (I’ll use a sample of an MLP shown below). I’m trying to load this pretrained model but use only layers 2 to 6 (i.e from max_pool to fc3). how can I go about that please?pretrained_mlp = mlp.load_state_dict(torch.load(model_path))
new_model = #only layers 2 to 6 go pretrained_mlpMLP(
(conv2d... | ptrblck | Assuming you want to use these layers from the pre-trained model:
(max_pool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
(fc1): Linear(in_features=29344, out_features=64, bias=True)
(relu): ReLU()
(fc2): Linear(in_features=64, out_features=64, bias=True)
(f… |
mdatres | Dear all,I’m writing because I have noticed a strange behaviour of the gradient computation in presence of a nn.Sequential module. I’m interested in computing the output’s gradient of a nn.Module. For my application, I had to rewrite a custom module which construct an equivalent representation of the original PyTorch m... | ptrblck | You are reusing the same net1 model and are thus accumulating the gradients in the .grad attribute of net1.
Delete the gradients and the result should match:
x = np.ones(54)
net1 = net5410210257(54,7)
smodel = ClassicalNeuralNetwork(net1)
model = NoSClassicalNeuralNetwork(net1)
out,_ = model(x)
o… |
Zowie_Tay | I’m experimenting with federated learning and i need non-iid data but using torch.utils.data.random_split() splits my mnist dataset into subsets with uniformed label distributionServer Label Distribution0 : 2930 | 1 : 3371 | 2 : 3004 | 3 : 3079 | 4 : 2866 | 5 : 2695 | 6 : 2962 | 7 : 3150 | 8 : 2966 | 9 : 2977 |Clients ... | ptrblck | You would need to access or load the internal targets from the desired dataset and pass it to train_test_split and stratify. If your dataset is preloading the data, check its internal attribute for e.g. .targets, else iterate the dataset once to load the targets and use them afterwards. |
lkm9983 | import torch
import numpy as np
import torch
torch.manual_seed(42)
from torch import nn
from tqdm import tqdm
class Practice_1_3(nn.Module):
def __init__(self):
super().__init__()
self.first_linear = torch.nn.Linear(2,2)
self.second_linear = torch.nn.Linear(2,1)
# torch.nn.init.cons... | ptrblck | Your learning rate might be too small as I’m able to overfit the dataset using a few different seeds:
import torch
import numpy as np
import torch
from torch import nn
from tqdm import tqdm
import random
class Practice_1_3(nn.Module):
def __init__(self):
super().__init__()
self… |
jstrm | I conduct experiments that rely on sampling data from a probability distribution that changes each epoch. Therefore, I use a custom DataSampler.Based on what I found online, the only way to change the probability distribution each epoch is to create a new Dataloader each epoch as well.However, while working as expected... | ptrblck | You could try to implement a custom sampler, which could use an internal epoch counter to change the distribution. This example shows a very simple approach:
class MySampler(torch.utils.data.Sampler):
def __init__(self, num_samples):
self._num_samples = num_samples
self.epoch =… |
p.servus | If i check if torch can see my gpu, it returnsFALSEand aWarning:>>> torch.cuda.is_available()
D:\servus\stable-diffusion-webui\venv\lib\site-packages\torch\cuda\__init__.py:107: UserWarning: CUDA initialization: The NVIDIA driver on your system is too old (found version 9010). Please update your GPU driver by downloadi... | ptrblck | Your NVIDIA driver might be too old, which is displayed in the output of nvidia-smi.
However, even updating it won’t help, since your GeForce GT 540M uses the Fermi architecture with compute capability 2.1 and is not supported anymore.
PyTorch supports compute capabilities between 3.7 to 9.0 in it… |
Csaba_Botos | I have attempted at least 10x to put up with the bad habit of usingpretrained=Truein the past but every time I tried to pass the stringweights="IMAGENET1K_V2"I get thereturn cls._member_map_[name]
KeyError: 'IMAGENET1K_V2'I must be missing something, should I expectthis syntaxto work? | ptrblck | resnet50(weights="IMAGENET1K_V2") works for me using torchvision==0.15.1+cu118. |
0x97 | Hi, I’ve just switched to a cluster with an A100 GPU, but I’m seeing worse performances than what I had on the previous card I was using (i.e. V100). By looking at other discussions, I believe it could be a cudnn version related issue.I’m working with an installation of pytorch in a conda environment, with the followin... | ptrblck | I guess you didn’t enable TF32 for cuBLAS operations as previously mentioned.
With pure FP32 I get ~GPU: 5977.826972784215iters/s, 0.00016728486865758897s/iter as this kernel is used:
Time (%) Total Time (ns) Instances Avg (ns) Med (ns) Min (ns) Max (ns) StdDev (ns) … |
eatcah | Hi there,I am facing issue with my code. Here are the explanations:Output from anaconda prompt:Traceback (most recent call last):File “C:\Users\User\anaconda3\envs\pytorch-gpu\lib\multiprocessing\queues.py”, line 244, in _feedobj = _ForkingPickler.dumps(obj)File “C:\Users\User\anaconda3\envs\pytorch-gpu\lib\multiproces... | ptrblck | Try to remove the usage of multiple processes, e.g. by setting num_workers=0, and also make sure the if-clause guard is used as explainedhere. |
Mehran_Ziadloo | Continuing my journey reading the PyTorch tutorials, I’m at “AUDIO FEATURE EXTRACTIONS” page.At the bottom of the page, there’s a section titled “Kaldi Pitch (beta)”. The code accompanying this section shows how to generate two new features, “pitch” and “nfcc”. This was my first time hearing the term “nfcc” so I had to... | ptrblck | I think it is a typo as thedocsshow that torchaudio.functional.compute_kaldi_pitch returns:
Pitch feature. Shape: (batch, frames 2) where the last dimension corresponds to pitch and NCCF.
However, I don’t know why the values are apparently not normalized to [-1, 1]. |
yiftach | Hi,According to linear algebra, the result of multiplying a matrix by a matrix can be computed separately by rows (or by columns). Why are then the two following result not exactly equivalent? Do I need to enable any other flag/choose a different backend?import random
import os
import numpy as np
import torch
seed = 4... | ptrblck | But this is also not what you are comparing.
In your example you are executing a large workload, slicing it afterwards, and a small workload by slicing the inputs:
a = (inputs @ model)[0]
b = inputs[0] @ model
Both approaches could take different algorithms, which can use a different order of op… |
sanbuphy | Hello, I have been studying the actions (CI) of various open source projects on Github recently.I noticed that PyTorch has a well-established CI, so I would like to further understand its composition and structure. Do you have any relevant materials that I can study and refer to?Thank you very much. | ptrblck | This Wiki pagemight be helpful. |
Ramansh_Sharma | Hello,I am trying to make a custom C++ CUDA kernel to use in my PyTorch code. This is my setup.py file. The problem is, by default, the compilation command the setup.py invokes does not have-rdc=Truein the command, which I need to add for my C++ code. Is there a way I can add this somewhere in the setup.py file?Thank y... | ptrblck | Relocatable device code linking was added inthis PRand is explained inthis doc. |
akshayk07 | From@ptrblck's answerhere, I know that intermediate outputs can be used to compute a loss. However, if I swap the simple model there with a ResNet (which has more complicated operations like skip connections) then there is an autograd error sayingRuntimeError: one of the variables needed for gradient computation has be... | ptrblck | I don’t believe this issue is related to the usage of intermediate activations as your code will also fail when the output is used:
x = torch.randn(1, 3, 32, 32)
model = ResNet18(return_feat=True)
output, aux = model(x)
loss = (output**2).mean()
#loss = (aux.clone()**2).mean()
loss.backward()
whic… |
songyuc | Hi, guys!I want to know why there are two different Compute Platform installation options for “CUDA 11.7” and “CUDA 11.8” on the PyTorch official website.As “CUDA 11.7” is known to be compatible with “CUDA 11.8”, what is the reason for releasing these two different versions of PyTorch?Your answer and guidance will be a... | ptrblck | Our current workflow is to release one “stable” binary package with a CUDA runtime (+ their corresponding libs) which were tested for a period of time in the nightly release and add another “experimental” binary with a newer CUDA runtime, which users can start using and should report any issues.
On… |
torchwang | I would like to know how _fft_c2c_mkl is implemented?SpectralOps.cpp has only the interface but not the implementation inside, I want to know how it is generated. | ptrblck | Based onSpectralOps.cppthis call redirects toMKL methodssuch asDftiComputeForwardorpocketfftdepending on the CPU architecture and how PyTorch was built.
At least MKL is closed source so you won’t be able to check its source code. PocketFFT seems to be a modification of FFTPack so you might … |
Mehran_Ziadloo | Following the examples provided in thetutorials, I’m trying to make sense of the low-pass and high-pass filters. I mean, they are very simple filters. And I wasn’t expecting to ask such questions myself, But looking at the results, it makes me wonder if I’m missing something.The provided example filter is like this:fil... | ptrblck | Your desired result would correspond to an “ideal” box filter, which has a sinc impulse response in the time domain. I don’t know which filters are used in your application, but note that each one has a different response. E.g. take a look at thebutterworth filter response:[image]which shows t… |
Puneeth_Naik | I am studying a pytorch model. I am running it on a CPU/GPU heterogeneous system. So whenever there is a dynamic control flow; i.e., an if statement whose predicate depends on the value of a tensor on the GPU), the CPU synchronized with the GPU waiting for the data value to be computed by the GPU(This happens if the GP... | ptrblck | I don’t think it’s currently possible to change this flag in PyTorch and an older feature request was discussedhere. However, I don’t know the status of it. |
axnet | I’m working to develop a face detection in Jetson AGX Orin using PyTorch but when runningimport torchprint(torch.cuda.device_count())only one GPU is detected.The FPS using the GPU approximately matches with the CPU detection. | ptrblck | Yes, it has one GPU with multiple cores. Also yes, PyTorch will launch CUDA kernels to fully utilize the device. |
aleemsidra | I am new to Pytorch and I am working with 3D dataset. In the custom class I want to read a 3D image and return it as one 3D image and not as 2D slices. Now in dataloader I want to make sure that if batch size is set to two, then two 3D images are being passed. How can I do that with custom dataset class.I am able to ... | ptrblck | Yes, loading the entire volume in the __getitem__ method is the right approach and I assumed self.data contained all volumes. |
alexmm | Hi, I was able to implement a class for Jn to have arbitrary derivatives as shown below:import numpy as np
from scipy.special import jv
import torch
class besselJv(torch.autograd.Function):
@staticmethod
def forward(ctx, x, v):
ctx.save_for_backward(x, v)
return jv(v, x)
@staticmethod
... | ptrblck | I’m not sure what you are looking exactly for, but I assume you want to save v in ctx._v?
If so, then your second code snippet contains a few slight issues and this should work:
class besselJv(torch.autograd.Function):
@staticmethod
def forward(ctx, x, v):
ctx.save_for_backward(x)
… |
lkm9983 | I think I’m confused between the cross-entropy loss and the implementation of nn.CrossEntropyLoss. As far as I know, the general formula for cross-entropy loss looks like this.L(y,s) = - sigma(i=1 to c) {yi * log(si)} (where si is the output of softmax)However, when I see the documentation for nn.CrossEntropyLoss, it... | ptrblck | This example codemight be helpful which shows how the target is used to index the logits. |
Messiah | When training an RNN model for seq2seq tasks, we can incorporate a decision to use either the predicted model output or the ground-truth target as input for the current batch or timestep. Should we.detach()the predicted model output in the former case?The source of my confusion arises from an apparent discrepency in tw... | ptrblck | Both approaches will create a detached tensor since rewrapping a tensor also does not keep the gradient history alive.
If you are not detaching the input you will keep the gradient history alive, which will allow you to calculate the gradients w.r.t. all used parameters of all iterations, but will … |
vtandra | I have a multiple input and multiple output (MIMO) regression problem. When I use the MSE loss function I see only one MSE. How is Pytorch calculating it ? Does it take the mean of MSE of all the outputs ? | ptrblck | Thanks for the code. The loss will be computes elementwise as seen here:
criterion = nn.MSELoss()
pred_output1 = torch.randn(6, 3)
target = torch.randn(6, 3)
loss = criterion(pred_output1, target)
print(loss)
# tensor(1.5746)
loss_manual = ((pred_output1 - target)**2).mean()
print(loss_manual)
#… |
Ricu | Hello, I am using the following versions:PyTorch Version: 1.13.1+cu116Torchvision Version: 0.14.1+cu116I am trying to insert a backward pre hook into a nn.Linear layer:class Insert_Hook():
def __init__(self, module, new_grad_output):
self.new_grad_output = new_grad_output
# use prepend=True so that this is ... | ptrblck | You are linking to the docs of the current 2.0.0 release, while you are using 1.13.1 which doesn’t seem to provide this method as seenhere.
Update PyTorch and you should be able to use register_full_backward_pre_hook. |
hello-fri-end | According to the documentation for batch_norm, running_mean and running_var are updated according to the following equation:running_mean = momentum * batch_mean + (1 - momentum) * running_mean
running_var = momentum * batch_var + (1 - momentum) * running_varConsider the following input:a = torch.tensor([[-1., -1.],
... | ptrblck | The running_var is updated via the unbiased variance as seen in mymanual implementationand this code snippet:
a = torch.tensor([[-1., -1.],
[-1., -1.],
[-1., 1.]])
mean = torch.ones((2))
var = torch.zeros(2)
out = torch.nn.functional.batch_norm(a, mean, var, … |
qianlifanyue | In cmd, I printed “import torch” then “torch.cuda.is_isavailable()”, it returned true;but at python console in pycharm I got false.I have set the right python interpreter, and there is ‘pytorch’ under the package menu. Are there any possible causes? Thanks in advance. | ptrblck | No, I meant different virtual Python environments which allow you to isolate installed packages.
“CPU-only” binary refers to the pip wheel or conda binary shipping with CPU kernels only without any CUDA kernels or CUDA libraries. |
ecolss | Is it possible to use dict as input to traced model, and the dict key-value has different value types?For example, the following dummy example failed with an errorclass A(th.nn.Module):
def __init__(self):
super().__init__()
self.lin = th.nn.Linear(3,2)
def forward(self, data): # data is a d... | ptrblck | Based onthis issue and workaroundit seems nested dicts are not allowed and you might need to flatten/unflatten the input. |
sujeongEOM | Hi.I’m trying to train Deep Ensembles using PyTorch.My model is has this structure.class ResNetDeepEnsembles1d(nn.Module):
def __init__(self, input_dim, blocks_dim, resblock_repeat, num_models, n_classes, kernel_size=17, dropout_rate=0.8):
super(ResNetDeepEnsembles1d, self).__init__()
self.num_model... | ptrblck | Yes, you are registering the same module using different approaches. The registered modules are the same and use “parameter sharing”, i.e. you should not see more memory usage etc.
PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier |
Goldname | I am trying to use torchvision.models.vit_b_32(). However, when I pass in some arbitrary data I get all zeros in the outputimport torch
import torchvision
import torchvision.transforms as transforms
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
transform = transforms.Compose(
[transforms... | ptrblck | By default it seems the VisionTransformer model will initialize its head.weight and head.bias to zeros as seenhere.
If you use a pretrained model, the outputs would show different values. |
miraodasilva | Hi, I’m currently trying torch.compile in Pytorch 2.0 and it works well but absolutely floods my terminal with logs such as[2023-03-17 20:04:31,840] torch._dynamo.output_graph: [INFO] Step 2: done compiler function debug_wrapperI was wondering if there is a way to suppress these logs? Warnings are okay but for me the I... | ptrblck | This issue seems to be related tothis discussionandthis feature request. |
hsfzxjy | Our GPU cluster is shipped with nvidia driver version 460.67 and CUDA 11.2 now and, for some reasons, we are not able to upgrade the underlying driver version.I want to try out PyTorch 2.0 in such a condition, but saw that the PyTorch 2.0 docker imageghcr.io/pytorch/pytorch:2.0.0-develwas built with CUDA 11.7. I’ve tri... | ptrblck | Driver 460.67 will allow you to run CUDA 11.x applications in “Minor Version Compatibility” mode as explainedhere.
I don’t know which user-mode driver the PyTorch 2.0.0 docker image uses, but would guess a newer one. |
Mert_Arda_Asar | Hello, I am trying to implement a simple attention module to classify images. But when I implemented that module I am getting batch size error. How can I solve that?Here how I load my dataset:X_train, X_test = train_test_split(dataset ,test_size=0.4, random_state=42)
train_loader = DataLoader(X_train)
test_loader = Da... | ptrblck | Replace:
x = x.view(-1, 64 * 32 * 32)
with:
x = x.view(x.size(0), -1)
to keep the batch size equal and fix shape mismatch errors in the next layers, if needed. |
spabho | Hello,I have a network with 2 parallel heads and each head predicts a different entity and hence they have different losses. I want the backbone to get updated by gradients coming from one head but not the other. How can I do this?(Attaching a figure explaining the same)grad_flow1280×720 10.5 KBThanks! | ptrblck | You could .detach() for output of backbone before sending it to Head2, which would cut the computation graph there. |
daniil | I consider AlexNet fromGitHub - bhiziroglu/Image-Classification-with-Deep-Convolutional-Neural-Networks: C++ / LibTorch implementation of AlexNetand want to replace Conv2d with the custom convolution, where the modification of input tensor occurs before applying Conv2d. To this end, I created the module:struct MyConv :... | ptrblck | If I understand your code correctly you are replacing the conv layer (using e.g. a cuDNN kernel) with a manual implementation uses a nested for loop to iterate each pixel location launching ~17 operations (and thus kernels).
You might need to rewrite your custom operation into a custom C++/CUDA ext… |
takis17 | Hello everyone,Hope you are all doing well.I got interested in investigating random bit-flips on the weights of a model.I have managed to extract the weights but still haven’t figured out how to induce these bit flips on the weights for a example of a convolutional layerLooking forward to hear some ideas you might have... | ptrblck | The loop only prints the data in its binary form, the actual type is still int32.
The bit manipulation is performed by shifting a single 1 bit via:
bit = 1 << 24
which would move it 24 positions to the left and then flipping the bit in the int32 via:
data ^= bit
No, don’t try to interpret the … |
takis17 | Hello everyone,Hope you are doing well.So I have modified the weights of a given pre-trained model.Passing though my evaluation dataset, I cannot detect any changed from before I have change the weights and after with the error induced, even when I changed the weights to extreme cases causing some weights to appear as ... | ptrblck | I think it depends on your actual use case if a re-training is desired or not.
The main issue I saw from your original post was that it seemed as if the weight changes were not used at all, which should not be the case as seen in my code snippet. Also setting a single value would already reflect th… |
miraodasilva | Hi, I tried using Adam(…,fused=True) and it does yield a 10-15% speedup on 1 GPU, as expected. However, when I try to use it with ddp (via lightning) with 2 GPUs, it yields no speedup at all. Is this expected behavior? I realize that this may be an issue with lightning and not torch, in which case this would not be the... | ptrblck | You might need to profile the actual DDP workload in your Lightning setup and check the kernel execution, where the bottleneck of your training is etc. Based on your observation, the speedup from Adam(... fused=True) might be wiped out by another slowdown.@crcrparhas implemented fused AdamW int… |
Theo | I’m running the following code:!pip install tokenizers
!pip install torchdata
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchtext.datasets import Multi30kAnd I get the following error:ERROR: pip's dependency resolver does not currently take into account all the... | ptrblck | Are you still running into the issue?
I just tried to install torchtext in the latest version and I get 0.15.1 as seen here:
>>> import torch
>>> import torchtext
>>> torch.__version__
'2.0.0+cu118'
>>> torchtext.__version__
'0.15.1+cpu' |
tcl | Hello, I’ve been trying to install Pytorch CUDA on Windows 10 but I’ve had some problems.I have an NVIDIA GeForce 920m with 425.31 Controller Version and CUDA 10.1.131 Drivers and therefore I installed CUDA 10.1 ToolkitUsing Python 3.7.9, I runned this line:pip install torch==1.8.1+cu101 torchaudio==0.8.1 torchvision==... | ptrblck | Your 920m should be a Kepler GPU with a compute capability of 3.5, which was dropped a few releases ago (I don’t know which one exactly, but it seems 1.8.1 already did not support it).
You could either downgrade to an even older PyTorch release, or try to build from source and add compute capabilit… |
martimpassos | I saved a model’s state dict and am trying to load it back to perform inference on random images that weren’t in the training/validation dataset. Here’s my code:VERSION = 1
ROOT = "some/path"
STATE_DICT_PATH = ROOT + 'state_dict.pth'
num_classes = 2
device = torch.device('cuda') if torch.cuda.is_available() else torch... | ptrblck | I’m not sure if your model is able to detect the objects using a different input resolution or if it needs more training on these. Generally I would expect to see differences in CNNs as the kernels were trained to extract features from the inputs used during training while these features might be di… |
woon | I want to my pretrained resnet32.pth to resnet32.wts for quantizationresnet50.pth provided by torchvisionnet = torch.load(‘resnet50.pth’)net = net.to(‘cuda:0’)…is working but resnet32.pth that i trained by me isn’t workingnet = torch.load(‘resnet32.pth’)net = net.to(‘cuda:0’)…AttributeError: ‘collections.OrderedDict’ o... | ptrblck | resnet32.pth seems to be a state_dict so you would need to either create the model object beforehand using its actual source code before loading this state_dict or you could try to save the entire model (as was apparently done for resnet50), which can fail in multiple ways if you don’t guarantee to … |
tueboesen | How do I check whether a tensor is a float object without checking for all the specific dtypes (float16,float32,double). All I want, is to check that the object is some kind of float such that I can perform floating operations on it. I was expecting there to be some kind of abstract base class above all float types tha... | ptrblck | Besides@KFrank’s checks you could use torch.is_floating_point as seen here:
for dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64, torch.complex32, torch.complex64, torch.complex128, torch.int32, torch.int64]:
x = torch.randn(1).to(dtype)
print("dtype {} is_floating_poi… |
EnricoShippole | Hi@ptrblck,I just wanted to confirm what is the best way to ensure that only the new Flash Attention in PyTorch 2.0 is being used for scaled dot product attention:For example:# pytorch 2.0 flash attn: q, k, v, mask, dropout, causal, softmax_scale
with torch.backends.cuda.sdp_kernel(
enable_flash=True,
enable_m... | ptrblck | torch.backends.cuda.enable_flash_sdp is not a context manager and you could use with torch.backends.cuda.sdp_kernel instead as sen here:
print(torch.backends.cuda.flash_sdp_enabled())
# True
print(torch.backends.cuda.mem_efficient_sdp_enabled())
# True
print(torch.backends.cuda.math_sdp_enabled())
… |
Roy_Eyono1 | I am attempting to replicate the exact implementation of GroupNorm, but upon testing, I’m off by approximately1e-2when randomly generating a tensor and feeding it through my implementation of GroupNorm and pytorch’s GroupNorm function.I suspect that there is a running average implementation in GroupNorm that accounts f... | ptrblck | From thedocs:
The standard-deviation is calculated via the biased estimator, equivalent to torch.var(input, unbiased=False).
This layer uses statistics computed from input data in both training and evaluation modes.
After fixing this the error matches the expected precision limit of float32: … |
OddTD | My model is meant to classify 446x2048 images as either defects or non-defects, but it gives me a strange output:Defect: 0.0
No_Defect: 144.98797607421875
Defect: 0.0
No_Defect: 136.9902801513672
Defect: 0.0
No_Defect: 136.9709014892578
Defect: 0.0
No_Defect: 127.5387191772461
Defect: 0.0
No_Defect: 147.4520721435547
D... | ptrblck | Your code looks alright and the accuracy calculation should work as seen in this code snippet mimicking your code:
accuracy = 0.0
total = 0.0
for batch in range(100):
output = torch.randn(16, 1)
labels = torch.randint(0, 2, (16, 1)).float()
predicted = output > 0.0
total += labels.… |
arcanjomjr | Hello, my first post here. I did search for the question but wasn’t able to find it elsewhere in the forum.I have a tensor X of dimension A, and a tensor Y of dimensions MxNxP and want to create a new tensor Z of dimensions MxAxNxP where Z[m,a,n,p] = X[a]*Y[m,n,p].I did find a solution but was rather inelegant and poss... | ptrblck | Broadcasting should work as seen here:
# setup
A, M, N, P = 2, 3, 4, 5
X = torch.randn(A)
Y = torch.randn(M, N, P)
Z_ref = torch.zeros(M, A, N, P)
# slow approach to create reference
for m in range(M):
for a in range(A):
for n in range(N):
for p in range(P):
… |
Miguel_Campos | According to the documentation: “Waits for all kernels in all streams on a CUDA device to complete.”So my question is if this is needed (or good practice) before starting the validation phase (only one GPU is used).Thanks. | ptrblck | No, you don’t need to manually synchronize your code unless e.g. you want to profile the code or if you are using custom CUDA streams and want to synchronize the entire device. PyTorch will use the default stream and thus no explicit synchronizations are needed. |
maxhgerlach | My goal is build a PyTorch package for Python 3.9 inside Nvidia’s NGC containernvcr.io/nvidia/pytorch:23.02-py3(PyTorch Release 23.02 - NVIDIA Docs). The binaries that come with the container are for Python 3.8 only.I found an example Dockerfile/workspace/docker-examples/Dockerfile.custompytorchinside the container. I ... | ptrblck | You might need to use BUILD_TEST=0 during your build. |
nlgranger | It all in the title:torch.Tensor.cudahas anasyncparameter that allows asynchronous transfer from pinned memory to GPU. Doestorch.Tensor.toautomatically uses async when possible?I wasn’t able to find the relevant piece of source code. | ptrblck | It was added in the current master branch as non_blocking, since asynch will be a keyword in Python 3.7.
See thedocs.
If you want to use it, you would have to build PyTorch from source. You can find the build instructionshere. |
Jaturong | I’m beginner for Pytorch. I want to increase the number of datasets (data augmentation).In this case, I have one image of cat and I want to usealbumentationsto increase the number of images and save image into another folder as follows:import cv2
import torch
import albumentations as A
import numpy as np
import matplot... | ptrblck | Thank you for this information!
The docs seem to lack the information that normalized floating point tensors are expected, since internally the inputs will be “unnormalized” and cast to uitn8 as seenhere.
Additionally, the channels-first memory layout is expected. This code should work:
x = torc… |
SimCan | I am trying to usenn.BCEWithLogitsLoss()withResNet50architecture for a binary classification task.In order to do that, I have set the net’s fully connected layer in this way:fc = nn.Linear(2048, 1). Furthermore, I have also changed the targets’ shape:labels = labels.unsqueeze(1).float().It seems don’t work properly, be... | ptrblck | Check the min./max. values in your target and make sure they are in the range [0, 1].
Also, how do you calculate the accuracy? Since your model outputs logits you should use a threshold e.g. via:
preds = output > 0.0 |
MartinZhang | where is <ATen/ops/upsample_bilinear2d.h>?I can’t find it, who can help me.I can’t find it inpytorch/aten/src/ATen/ops at 652af5ec15b81c39ec7413519d0ce9938d87bcf1 · pytorch/pytorch · GitHubgithub.compytorch/pytorch/blob/652af5ec15b81c39ec7413519d0ce9938d87bcf1/aten/src/ATen/native/UpSampleBilinear2d.cpp// Adapted from ... | ptrblck | The file is generated bytorchgen/gen.pyfromnative_functions.yamland is located in torchh/include/ATen/ops/upsample_bilinear2d.h after PyTorch is built. |
Minennick | Dear all,I am currently building a network that gets complex numbers as input, processes them using complex layers, and gives back again complex numbers. I already recognized, that passing the input to the model, causes the input to automatically be viewed as 2-channeled real values, as is the case for applying torch.v... | ptrblck | I’m not sure why the error is raised, but note that nn.DataParallel is in “maintenance mode” as ofthis RFCand should eventually be removed.
We recommend using DistributedDataParallel for a better performance and support.
Could you try to use your code using DDP and see if the same error is raise… |
gggg111 | My goal is to implement the gradient * input relevance algorithm manually on my model. I know I can get the input of any layer using forward hooks. The problem is when creating a backward hook to obtain the gradients, I can not obtain the input and output values of the layer in the backward hook. What is the best way t... | ptrblck | You could try to use e.g. a global dict storing the forward activations and index it in the backward hook, but this approach sounds a bit hacky.
A cleaner way might be to implement custom autograd.Functions which would allow you to access the forward activations in the backward function directly, b… |
Animesh_Gupta | I am trying to compile custom cpp extension but I am getting following error:/workspace/cpp_build/cpp_functions.cpp:81:28: error: ‘struct DLTensor’ has no member named ‘ctx’
81 | dlMTensor->dl_tensor.ctx.device_id = device_id;Code related to this is:#include <torch/extension.h>
#include <vector>
#include <ios... | ptrblck | In Python you could use:
torch.nn.grad.conv2d_weight
torch.nn.grad.conv2d_input
and I think in libtorch
std::tuple<Tensor, Tensor, Tensor> convolution_backward(
const Tensor& grad_output_, const Tensor& input_, const Tensor& weight_,
const at::OptionalIntArrayRef bias_sizes_opt,
IntAr… |
Sobir_Bobiev | Is there a function that chunks a tensor along a dimension with given chunk sizes and stacks the chunks into a single tensor (also pads the chunks since they can be variable sized)?A = torch.randn(10, 512, 768)
sizes = torch.tensor([1, 3, 6])
assert sizes.sum() == A.size(0)
out = function(A, sizes, dim=0)
assert out.... | ptrblck | torch.split and pad_sequence should work:
A = torch.randn(10, 512, 768)
sizes = torch.tensor([1, 3, 6])
assert sizes.sum() == A.size(0)
out = torch.split(A, sizes.tolist(), 0)
out = torch.nn.utils.rnn.pad_sequence(out, batch_first=True)
assert out.shape == (len(sizes), sizes.max(), 512, 768) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.