user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
RohitDulam | I would like to modify the weights of a convolution operation before the convolution operation on the input. For example -conv = torch.nn.Conv2d(in_ch, out_ch, 3, 1, 1)
conv.weight.data = conv.weight * values
out = conv(x)In the above code, ‘x’ is the input and the convolutional weights are modified using the ‘.data’ a... | ptrblck | No, it won’t work. In this case you might want to use the functional API via:
out = F.conv2d(x, conv.weight*values, ...)
instead of manipulating the weight of the conv layer. |
ksasi | Dear Community,I have usecase where dlib based models need to used to perform face detection and face alignment. Is there a way to use these models to perform face detection and alignment as part of pytorch transforms?Please suggest and possibilities or resources.Thanks | ptrblck | In the common use case you would apply any transformation in the Dataset.__getitem__ method on each sample. Assuming your dlib transformation works on a single numpy array (or any other object you could transform into a PyTorch tensor) you could just apply it in the __getitem__, too.
Additionally, … |
noob_programmer | As per documentationhereforcudamethod intorch.nn.Module, the model parameters and buffers should have moved to GPU. SO I assume that the model in RAM will get wiped out, but when checking the Resident Set Size of the program, it was increasing 3x than the initial model in cpu.Here is the code I’ve used to test,import ... | ptrblck | The model is tiny and I assume the lazily loaded driver uses the host RAM. Update to the most recent stable or nightly release with CUDA 11.8 or 12.1 and the host RAM usage should decrease. |
pepper8362 | I have a network with SyncBatchNorm for multi-GPU training. If I train the network on a single GPU in a normal non-parallel way (i.e. without using DDP), do I need to change SyncBatchNorm to BatchNorm? Does SyncBatchNorm still work normally in this case? Thanks for your help! | ptrblck | It should fall back to the vanilla batchnorm operation if no distributed setup is detected as seen inthis line of code. |
Onon0 | Each epoch takes 5 minute longer than the last. How can I improve my code.def train(loader, model, optimizer, loss_fn, scaler):
loop = tqdm(loader)
history = []
for batch_idx, (data, targets) in enumerate(loop):
data = data.to(device = DEVICE)
targets = targets.to(device = DEVICE)
... | ptrblck | You are appending all computation graphs in the history list which will increase the memory usage and eventually run out of memory. Detach the loss tensor before appending it. |
linuxtroubleshooting | I’m trying to run this project on my local machine:GitHub - RVC-Project/Retrieval-based-Voice-Conversion-WebUI: Voice data <= 10 mins can also be used to train a good VC model!I followed all the instructions on the read me of the project and when I try to run the project, I’m getting this error:/home//.local/lib/python... | ptrblck | NVML is the NVIDIA Management Library and is used on NVIDIA GPUs. You might have installed the PyTorch binaries with CUDA support by mistake and might want to install the ones with rocm for AMD GPUs. |
Wang-MieMie | When I have two networks that need to be trained alternately, for example, GAN network as a typical case (generator A, discriminator B).I train A, B alternately, for example, A->B->A->B…. At this point, will the benchmark be run every time, or only the first time A is executed and the first time B is executed?In fact, ... | ptrblck | The benchmark will be executed once per workload (input size, data layout, dtype, compute capability, etc.) and the selected algorithm will be cached. |
Nguyen_Duy | Hello. I have a question as follows:With a large model, if I initialize all the child modules in theinitfunction of a final model I may end up having to pass in many parameters. Can I build a build_model() function like the example below?import torch
class A(torch.nn.Module):
def __init__(
self,
i... | ptrblck | Your approach is fine and should not cause any issues. I would claim it comes down to your programming style and the use case. |
Salman_Abbasi | HiI have a question. I have two different models. I would like to transfer learned weights of model1 to a different model (differnt layers and structure- autoencoder), such that output of this 2nd network first iteration(epoch), is equal to the output of the learned model(model1).I do not have a code, because I simply ... | ptrblck | If your models are “entirely different” I assume their structure and layers do not match. In this case you might not be able to transfer weights between these unless you can create a mapping between layers. E.g. a 1x1 conv layer could be mapped to a linear layer, but of course not every layer is tra… |
ireneferfo | Hello, I have the following net to perform a binary classification of some trajectories:Architectureclass DCR(nn.Module):
def __init__(self, kemb_size, nvar, points, device):
super().__init__()
self.phis = load_phis_dataset()
self.kemb = get_kernel_embedding(self.phis, nvar, samples = kemb_s... | ptrblck | Remove the sigmoid and use nn.BCEWithLogitsLoss instead for a better numerical stability. |
AlbertZeyer | I want to run some multi-node multi-GPU training where some GPUs are connected via NVlink but potentially/probably not all of them (but I don’t really know in advance).How would I ideally do that with PyTorch?For the reduce, I ideally would want that it does it in the most efficient way possible, i.e. first reduce over... | ptrblck | I don’t know as I’m not using gloo and usually don’t want to hold data on the CPU.
Yes, NCCL should give you the best performance for data stored on the GPU. |
mttbrv | PreambleHello, I’m trying to solve a classification task where, given a text sample, I have to infer three labels:label_1_binary,label_2_binaryandlabel_3_multiclass. Two of them are binary i.e. they can only take one of two values. The third label is multi-class i.e. it can take one ofnpossible values.My idea was to fi... | ptrblck | Yes, creating multiple classifier “heads” is a valid approach. I don’t know how your data is distributed but would recommend scaling down the use case to try to overfit a small dataset (e.g. just 10 samples) by adapting the hyperparameters. |
MidnightChaos | Hey all,I’m a beginner experimenting with resnet50 transfer learning, and I’ve been getting the runtime error “element 0 of tensors does not require grad and does not have a grad_fn” when attempting to do a training run. I’m doing this in a google colab environment, and here’s the code:train_session_epochs = 12
with t... | ptrblck | In your code you are freezing all parameters in:
for param in model.parameters():
param.requires_grad=False
However, you are replacing the .fc layer afterwards. Did you execute the cells in a different order by mistake as I cannot reproduce the issue locally? |
Girum_Senay | my code is which is generating error is:class ToTensor(object):defcall(self, sample):image, mask = sampleimage = torch.from_numpy(image).permute(2, 0, 1).float().unsqueeze(0)mask = torch.from_numpy(mask).long()return image, masktransform = transforms.Compose([ToTensor()])train_dataset = CustomDataset(image_paths, mask_... | ptrblck | Your custom ToTensor transformation would accept two inputs, but transforms.Compose does not. Since you are using a single transformation only, just use transform = ToTensor() or also provide a custom Compose transformation accepting multiple inputs. |
tbergeron | I’m currently adapting an existing model to push it on Replicate which implies building a container to push it onto their servers. They use a tool called cog that is basically an abstraction around Docker.When running the model within the container, I get the errors below.I tried to run the container elsewhere and also... | ptrblck | That’s right. You would need to use a properly installed NVIDIA driver, but don’t need a locally installed CUDA toolkit or cuDNN, since these are shipped as dependencies in the PyTorch binaries.
Your locally installed CUDA toolkit (including cuDNN) would be used if you build PyTorch from source or… |
Oberon | Hi, I’m new to PyTorch. I’m trying to usingImageFolderto load my own dataset.When I load the folder, the imgs/samples are:[
("img0path.ext",0),
("img1path.ext",0),
...
]For some reasons, I need to group them up by targets, just like:[
0=[img list of targets 0],
1=[img list of targets 1],
...
]Is... | ptrblck | You could create a custom Dataset and use the ImageFolder as a template or base class, which would probably the cleanest approach. |
Bakhtiyor_Jumanazaro | hi, i am new to pytorch and i am having compatibility issues i tried everything, ran out of options. when i ran this:pip3 install torch torchvision torchaudio --index-urlhttps://download.pytorch.org/whl/cu118Looking in indexes:https://download.pytorch.org/whl/cu118ERROR: Could not find a version that satisfies the requ... | ptrblck | Python 3.12 it not supported yet so you would need to downgrade. |
vutya | Dear PyTorch Community,I am encountering an issue related to the usage of a 1x1 convolutional layer in my script. The problem is comprehensively described in the attached screenshot:image926×1328 115 KBI appreciate any assistance or insights the community can provide to help resolve this issue.Thank you,V. | ptrblck | These small numerical mismatches are expected and caused by a different order of operations to calculate the result and the limited floating point precision. Neither of the two outputs is “more correct” and should show a similar error to a wider dtype. |
elebot | Hi,I’m trying to troubleshoot apparitions of nan values that seemed to appear during my training steps. For this purpose I used torch.anomaly_detection() and caught the errors in order to save my variables and state_directory to more accurately highlight the issue.I was able to highlight my problem with the calculation... | ptrblck | In your previous post you claimed to use autocast:
while you are now casting the tensors manually.
Use autocast as seen in e.g.this exampleand the code will work.
import torch
import torch.nn.functional as F
nb_batchs = 16
nb_classes = 135
shape = (64,72,64)
# send to gpu here (internal soft… |
Mona_Jalal | So I have this test script in order to debug another problem I have with torch.matmul. Please note I need to use this specific version of PyTorch and torchvision due to reproducibility reason of HybridPose framework.test.pyis:import torch
a = torch.rand(2, 3, device='cuda')
b = torch.rand(3, 2, device='cuda')
try:
... | ptrblck | Your RTX 6000 Ada needs CUDA >= 11.x as it’s compute capability 8.9. Your current PyTorch installation comes with CUDA 10, which is not compatible with your GPU, so update PyTorch to any binary using CUDA 11.x. |
Yuerno | Hi all! I’m dealing with batch of images where each item in the batch is a time sequence of data. So essentially, imagine that each entry in the batch is a set of frames. I’d like to apply convolutions to the last three channels, but of course Conv2D expects 4 dimensions.Is the correct way to approach this problem that... | ptrblck | Yes, of you want to treat each time step as a separate sample you can flatten the temporal dimension into the batch dimension. However, you are still mentioning channels while I assume you mean dimensions? |
rookiearun | So I downloaded the datasets and was trying to load the waveform using torchaudio.load(), I have given the arguments as below :> filename = "./data/SpeechCommands/speech_commands_v0.02/yes/00f0204f_nohash_0.wav"
> waveform, sample_rate = torchaudio.load(filepath=filename, num_frames=3)
> print(f'waveform tensor with 3... | ptrblck | The docs show the first argument is called uri instead of filepath, so you might want to change the argument name or just pass the filename implicitly without specifying the argument name. |
cerisara | Hi,I’m training a model on 4xGPU A100 80GB and it trains fine, but is really occupying nearly all the VRAM. Now, when I want to save the model, I cannot directly use torch.save(model) because of the ProcessGroup, so I use torch.save(model.state_dict()); but this creates an OOM crash, because it allocates new VRAM for t... | ptrblck | Yes, it doesn’t as also seen here:
model = models.resnet152().cuda()
print("{:.2f}MB".format(torch.cuda.memory_allocated()/1024**2))
# 230.27MB
sd = model.state_dict()
print("{:.2f}MB".format(torch.cuda.memory_allocated()/1024**2))
# 230.28MB
clone = copy.deepcopy(sd)
print("{:.2f}MB".format(tor… |
Fyu | I’m trying to load custom data for a CNN via mps on a MacBook pro M3 pro but encounter the issue where the generator expects a mps:0 generator but gets mpsPython ver: 3.11.6PyTorch ver: 2.1.1PyVision ver: 0.16.1Environment: Jupyter Notebook (on VSCode)Code:if torch.backends.mps.is_available():mps_device = torch.device(... | ptrblck | Try to use the mps backend explicitly instead of using set_default_device. |
chanaka | I’m making modifications to third party submodule (Gloothird_party/gloo) to accommodate my use cases and I want to test them through PyTorch without building it from scratch. Is there a way to rebuild PyTorch and incorporate these changes without going through the whole build process again as I only changed the Gloo so... | ptrblck | Only the initial source build would need to rebuild the entire framework. Changes to local files would then trigger incremental builds for the changed files. However, I’m not sure how third party dependencies are handled and if changes there would be detected properly, so you should try it out and r… |
Nikolay_Blagoev | I know the question seems like it answers itself (compute weight gradients without gradients?). But the issue I am trying to resolve is that I will need to change leaf variables before computing the backwards pass. Without no_grad pytorch will complain about in-place modifications.Define the model (it is split in two s... | ptrblck | The approach fails since the intermediate forward activations were not created by the manipulated weights and are thus wrong. You could try to directly pass the new gradients to this particular layer, by this sounds like a painfully manual approach. |
Mahdi_Amrollahi | Why we use torch.cuda.synchronize()? When we do an operation oncudadevice, does not it mean that it has done one the same line of code? Should we always wait for the ongoing operations oncuda?import torch
# Check if GPU is available
if torch.cuda.is_available():
# Move tensor to GPU
device = torch.device("cuda... | ptrblck | To explicitly synchronize the code, e.g. to profile the kernel execution time.
No, since CUDA operations are executed asynchronously w.r.t. the CPU.
No, as it will slow down your code since your CPU is constantly blocked.
PyTorch adds needed synchronizations for you, e.g. if you want to print … |
skyfail_ufg | I finally finished tuning my model algorithm and it was running pretty fast, about 23 secs per epoch, now I want to get the model’s metrics, I concatenated every single batch results so I could do a quick math when the loops end, but now I’m getting 40 secs/epoch. I think it’s because a) I used torch.cat, b) it’s too s... | ptrblck | Instead of calling torch.cat in each iteration, append the temp. results in a list and create the tensor after the loop finished, which should speed up the code as only one copy will be triggered. |
Devymex_Wang | This is a piece of reproduced code.import sys, torch
@torch.jit.script
def magic_func(x, y):
return torch.tanh(x + y)
x, y = torch.rand(8, device="cuda"), torch.rand(8, device="cuda")
before_encoding = open(sys.argv[0]).encoding
for _ in range(int(sys.argv[1])):
output = magic_func(x, y)
after_encoding = open(s... | ptrblck | This seems to be annvrtc issueand you might need to set the encoding explicitly to restore it again as a workaround. |
chrismile | When manually building PyTorch (v2.1.1), I tried using CUDNN_INCLUDE_DIR and CUDNN_LIB_DIR to set the path to the include and lib directory of cuDNN (which is mentioned in, e.g.,How to build with cuDNN - #7 by EthanZhangYi).However, even though CUDNN_INCLUDE_DIR contains cudnn.h, I get the following error message when ... | ptrblck | Most likely your dev environment is not correctly set up and you could test it by trying to build any cuDNN application locally.
I don’t know where your CUDA toolkit etc. is installed, but if you’ve used the default locations installing cuDNN should work via:
cp -a cudnn-linux-x86_64-VERSION-archi… |
eastchun | Is there a torchtext release that supports the followings ?pytorch 2.1.0, cuda 11.8, numpy 1.24.3 | ptrblck | torchtext==0.16 was released on the same day together with torch==2.1.0, so should be compatible. |
Spam_Me | There is a large amount of time spend incudaMemcpyAsync, related toMemcpy DtoH (Device -> Pageable)operation , between forward and backward pass, I do not know where it comes from.I noticed this when I used PyTorch profiler.I am attaching the observation when viewed in chrome tracing.I am using the PyTorch data parall... | ptrblck | As the profile shows it comes from aten::item, which is triggered by tensor.item() in Python and synchronizes the host with the GPU.
Remove unneeded item() calls to avoid synchronizing the code as the memcpy kernel doesn’t take such a long time but needs to wait for the GPU to finish its execution … |
tinted | In the below code, y and y2 plot differently even though they get same input, why is that?import torch
import matplotlib.pyplot as plt
torch.manual_seed(42)
# Data, inputs and outputs
x_rand = torch.randint(-1000, 5000, (10000, 1), dtype=torch.float)
# Fn 1
x = 0.1 * x_rand
y = torch.sin(0.5 * x)
# Fn 2
x2 = 0.5 * ... | ptrblck | You are using different x axis values and are thus moving the smaller sine wave. Use the same axis and you will see the outputs overlap:
plt.plot(x_plt.numpy(), y_plt.numpy())
plt.plot(x_plt.numpy(), y2_plt.numpy())
You can also check if by computing the error e.g. via (y - y2).abs().max() which i… |
Mohamed_Farag | Hi everyone,I am using a pre-trained vision transformer from Pytorch available models. The question now, if I am using the pre-trained weights and I am applying the same transformations applied to the during training on Image-Net as an example, does is by nature do the reshaping of the input data?pre_trained_weights = ... | ptrblck | Unsure, if I understand the question properly, but if you are wondering if the transformation contains a Resize, just print it. |
Hackster | I want to implement automatic mixed precision into my training framework. According tohttps://pytorch.org/docs/stable/amp.html#torch.autocastautocasting is available for cuda and cpu.I wondered that for their training example on cpu# Creates model and optimizer in default precision
model = Net()
optimizer = optim.SGD(m... | ptrblck | AMP on the CPU supports bfloat16, which does not need gradient scaling. |
_lovepytorch | I have a tensor - batch of images with shape [32, 3, 640, 640] and values in the range [0, 1] after diving by 255. How can I resize that tensor to [32, 3, 576, 576]?I see the optiontorch.nn.funtional.interporlateand the documentation wroteThe input dimensions are interpreted in the form: mini-batch x channels x [option... | ptrblck | This should work:
x = torch.randn(32, 3, 640, 640)
y = F.interpolate(x, (576, 576))
print(y.shape)
# torch.Size([32, 3, 576, 576]) |
AlbertZeyer | For demonstration, here only 2 processes. You see it innvidia-smi:+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.147.05 Driver Version: 525.147.05 CUDA Version: 12.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name ... | ptrblck | Your processes are all initializing a CUDA context on the default device. This can be avoided by setting the device via torch.cuda.set_device. Could you post a minimal and executable code snippet reproducing the issue, if you get stuck and it doesn’t help? |
Mahdi_Amrollahi | I need to useregister_forward_hookmethod to receive some layers output but I will not receive the results when I call.forward()for any module however, when I change it to just calling that module likelinear1(), I get the results on hooks. Is that a bug?This does not work:from torch import nn
class cls_model(nn.Module)... | ptrblck | No, this is the exact reason why you should call the module directly instead of its .forward pass, as e.g. hooks will be skipped otherwise. |
i_amRifat | Is there anytorch == 1.3.1whl available for thePython 3.10version? I am using my university server so I can’t downgrade the Python version, and the admin of the server has already mentioned that they are not going to downgrade Python because of some issues.So, Can anyone help to find another way to solve the issue? | ptrblck | No, since the old torch==1.3.1 version was released on Nov 2019 while Python 3.10 came out October 2021. |
weiskohlmoe | In a current project of mine I need to project the weights of my convolutions. To do that I used my own module that usestorch.nn.functional.conv2dinstead oftorch.nn.Conv2dHowever I realized that it is very slow when I use the model on a GPU instead of a CPU.Even more surprising, when I just use conv2d outside of the mo... | ptrblck | CUDA operations are executed asynchronously and you would need to synchronize the code manually before starting and stopping the host timers. Alternatively, you could also use torch.utils.benchmark. Your current profiling is thus most likely invalid. |
zhenxz0121 | In my project, I need to load video frames into memory. Through analysis, I observed that themodel.forward()operation takes approximately 1 second, while loading the data consumes about 18 seconds (without multi-processing). It is evident that I require (additional) workers to independently read the data.I have 2 RTX 4... | ptrblck | Right now the data loading order should be deterministic by adding batches to the queue from each worker sequentially. If you now want to add more flexibility by limiting this queue you would still need to guarantee the data loading order as determinism is important for a lot of use cases.
Of cours… |
starkj | I cannot get a value of True from Tensor.is_cuda, even though moving the tensor to the GPU seems to go with no problem. Here is a simple test program:import torch
avail = torch.cuda.is_available()
print("Cuda available: ", avail)
a = torch.randn(2, 2)
print(a)
print("Moving a to the GPU...")
a.cuda()
verif = a.is_cu... | ptrblck | .cuda() and .to() calls on tensors are not executed inplace and you would need to assign the result.
This should fix it:
a = a.cuda() |
External_happy | I am training a ViT-B/16 on a dataset with 4K samples using 24 NVIDIA Quadro RTX 6000 GPUs.The training was going well until I add a line to make an inference on the same model twice using different inputs at the same iteration. This resulted in the error message “RuntimeError: CUDA out of memory. Tried to allocate 148... | ptrblck | If you are not disabling the gradient calculation each forward call will store intermediate results which are needed for the gradient calculation during the forward pass. Either call backward() between these forward passes or disable gradient calculation by wrapping the forward calls into a torch.no… |
luchungi | Can DataParallel / DistributedDataParallel be used for basic tensor operations and sums without a model being involved?For example, I have a custom loss function with computation that blows up the size of the output tensors from the model and I want to split these operations across GPUs. It is mostly basic operations s... | ptrblck | No, DistributedDataParallel wasn’t designed to share operations but you could manually move parts of your tensors to another device via the .to() operation. |
Sai_Kishore | My custom Model looks like this where I have matrices to be sent through conv layers and Im using those weight matrices to calculate a loss function.class MatrixModel(nn.Module):
def __init__(self, num_matrices=10,layers = 10,img_shape=(32,32),lamda=1.0) -> None:
super().__init__()
self.num_matrices = num_mat... | ptrblck | You could use my proposed approach by checking the input as well as all intermediate activations via torch.isfinite(x).all(). |
cbd | The result of last training iteration and first iteration of validation is different. Which parameters are vary during validation? I have taken the same image in last iteration of training and first iteration of validation. The result is different. | ptrblck | Assuming you are calling model.train() before starting training the model and model.eval() during the evaluation some layers will change their behavior, such as Dropout (which will be disabled during evaluation) and BatchNorm (which will use its running stats during evaluation instead of the batch s… |
Kuljeet | I am attempting to add two new attributes to my custom dataset that can give me the shape of input data and a class map of unique classes. I am getting a AttributeError , seemingly because the new attributes are not part of the base class. Is there any way I can achieve this ?def __getattr__(self, attribute_name):
... | ptrblck | Your code works fine for me:
class CustomDataset(Dataset):
def __init__(self):
self.data = torch.randn(10, 3, 24, 24)
self.labels_map = {
"a": 1,
"b": 2,
}
self.image_shape = self.data.shape
def __len__(self):
return l… |
cbd | By running the same code on cloud giving difference in inference time of 10 seconds for 1000 images. What may be the reason? | ptrblck | Everything could be related, starting from the hardware, driver, math libs, PyTorch release, to your actual code.
Profile your workload with the native PyTorch profiler or e.g. Nsight Systems and compare both profiles from theses systems. |
cbcase | I am debugging a memory usage issue for tensor-parallel training, and I observe that runs with tensor-parallelism enabled that OOM have large amounts of “reserved but not unallocated” memory (pointing to fragmentation). If Iremovethe all_reduce calls in the TP region (but change nothing else), the max batch size that c... | ptrblck | Hi Carl!
Thanks for reporting the issue and the great memory allocation plots.
You might be running intothis issue. Inthis PRwe exposed an env variable to avoid the stream recording via TORCH_NCCL_AVOID_RECORD_STREAMS=1. Could you use it and let me know if the memory allocation behavior changes… |
sxlllslgh | I’m trying to train a CLIP-based model using FSDP on three GPUs, but when each epoch start iterating the data loader, it may take about 1 minute for reading 4K pieces of data.DataSet key codes:class MyDataset(DataSet):
def __init__(self, …):
self.label_table = pd.read_csv(…) # About 4K rows
def __len_... | ptrblck | Your current MyDataset.__init__ method only loads self.label_table via pd.read_csv, so I assume you are referring to this line of code?
This behavior is expected since each new DataLoader iterator will recreate the Dataset on each worker. If you want to avoid this behavior you could use persistent… |
coballe | This issue has suddenly arisen whenever I run torch.cuda.is_available.UserWarning: CUDA initialization: CUDA unknown error - this may be due to an incorrectly set up environment, e.g. changing env variable CUDA_VISIBLE_DEVICES after program start. Setting the available devices to be zero. (Triggered internally at /opt... | ptrblck | This error is raised e.g. if your system cannot communicate with the GPU, which might be caused e.g. by a driver update without a restart or any other setup issue.
On my personal workstation I see this issue after waking the system from its “suspend” status, as this still does seem to cause such is… |
Torcione | Hi everyone,I need to implement a customized version of a normalization layer.The idea is the following:after initialization we forward the dataset (or a single batch) through the network; similarly to batch norm, every time the module is called inside the model we compute the mean over the batch (first foundamental di... | ptrblck | Thanks for the update!
I guess this line:
self.stored_means[self.layer_id] = x.mean(dim=0, keepdim=True)
is storing the gradient history in self.stored_mean so you might need to .detach() the x.mean() tensor before assigning it. |
ThePiromaximus | Hi everyone, I am developing a model to perform semantic segmentation. Basically as the title said, I obtain different performances if I change the shuffle parameter of the validation dataloader. Specifically, with shuffle=True the mIoU computed on the validation data is higher than the mIoU computed on the same datalo... | ptrblck | Could you describe how the binary_iou is implemented and if its result depends on the actually used samples in the batch? If so, your results would be expected. |
fraragon | I am getting various problem in pytorch about the Dataloader.I created a custom dataloader but after every batch the GPU allocated memory increases even if the gpu memory utilziation is constant after the initial batches. I would expect the same for the GPU allocated memory, but since it does not happen my training cra... | ptrblck | You are properly detaching the loss but are then accumulating the output of psnr:
psnr_train += psnr(predicted_peak, img_peak, torch.max(predicted_peak))
Could you check if this method returns a tensor which is still attached to the computation graph? If so, detach it too before accumulating. |
vince62s | I found that .tolist() was kind of slow but the I was puzzled by the slowness of over-tensor iteration.Maybe I am doing something wrong, here is a snippet:import torch
from math import cos
import time
def test_with_list(topk_ids):
true_value = 0
false_value = 0
topk_ids_list = topk_ids.tolist()
for i i... | ptrblck | You are using a Python if condition checking if any value of a CUDATensor meets a specific condition, so yes: this line of code will synchronize the code. Otherwise your Python program wouldn’t know which path to take. Python itself is running on the host and thus needs to read the value from the GP… |
weirenorweiren | I tried to run amultilayer perceptron (MLP) regression model written in PyTorchthrough GPU in Google Colab. However, I encountered a bunch of errors with different approaches. Below is the code that works fine for CPU.import torch
from torch import nn
from torch.utils.data import DataLoader
# from sklearn.datasets impo... | ptrblck | Ah sorry, I missed the questions and just saw the update it’s working now.
I personally would not use torch.set_default_device as I was seeing too many issues in the past. With that being said, I don’t know what its current status is and if things improved, but I just stick to explicitly transfer… |
my-name-s | Which PyTorch version supports GeForce GTX 480? | ptrblck | None of the current binaries as they support compute capabilities 3.7 - 9.0, while your GPU uses the Fermi architecture with compute capability 2.0.
CUDA 8.0 was the last version supporting it, so you might be able to find a really old PyTorch release with this CUDA version. |
Vaibhav_Chahar | I have a class of single layer (below) of neural network (Neural_Made) going from one layer to another layer. I want to construct my whole network using this class as a building block. For that I used another class Made to build my whole network. But I am unable to figure out how to do it. Please provide a solution for... | ptrblck | Take a look atthis exampleto see how a custom neural network is created.
There you can see the initialization of each layer in the Net.__init__ method and how to use them in the forward. |
njukenanli | Hello, everyone. I have been trying to use DDP to train a transformer. It all runs well on our own cluster, but after I transfer the code and the env to a server rent from an outside company, some bugs occur at torch.nn.parallel.DistributedDataParallel(model)Here is the code and the error information with NCCL_DEBUG=IN... | ptrblck | You could try to increase the VM areas e.g. by sudo sysctl -w vm.max_map_count=262144 or as a workaround you could disable IB via NCCL_IB_DISABLE=1 as your setup seems to have trouble with it. |
e1920019 | HelloI have a question for experts. I’m trying to install PyTorch, but I’m encountering errors. I have installed CUDA 12.3.0. Is PyTorch not compatible with CUDA 12.3.0? Please help. | ptrblck | I don’t know if you’ve just posted a response from a bot, but https://download.pytorch.org/whl/cu123/torch_stable.html is an invalid URL and you should use the provided ones fromhere. |
zizhao.mo | Hi,I am wondering how I can implement the logic that the result evaluated in GPU can be directly written to CPU memory, without temporarily storing it in GPU memory and then transferring it. I think it may be feasible due to the existence of the DMA technique but I am not sure about that. The motivation is that in my p... | ptrblck | I don’t think this is possible, but you could use the aforementioned utils. or offload the activation to the host after it was stored temporarily on the GPU as describedhere. |
123456 | I am training pretrained deeplabv3 model with resnet101, and got the following errorRuntimeError: Given groups=1, weight of size [64, 3, 7, 7], expected input[4, 6, 128, 128] to have 3 channels, but got 6 channels instead.Actually I need to send two concatenated images to architecture. Concatenated along channel dimens... | ptrblck | No, it doesn’t:
import torchinfo
from torchinfo import summary
from torchvision.models.segmentation import deeplabv3_resnet101
model = deeplabv3_resnet101(num_classes=2)
model.backbone.conv1 = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
summary(model, input_siz… |
guoyaohua | I use huggingface Transformer to fine-tune a binary classification model. When I do inference job on big data. In rare case, it will trigger “CUDA error: device-side assert triggered” error, but when I debug the single wrong batch, it is strange that it can pass (both on GPU and CPU) , I don’t know why.This error first... | ptrblck | You could run the script with the aforementioned env variable, which would point to the operation raising the error.
Your approach could work, but note that once you are running into an assert the CUDA context might be corrupted and I don’t know if you would be able to store any additional data. |
Kungbohan | Hello,When I use apex amp, it always shows a warning:Warning: apex.amp is deprecated and will be removed by the end of February 2023. Use [PyTorch AMP](Automatic Mixed Precision package - torch.amp — PyTorch 2.1 documentationThus, I am trying to update my code (from apex to pytorch build-in).When I used apex library, m... | ptrblck | Yes, that’s correct as its deprecated apex implementation was too limiting in its flexibility and disabled a few important use cases. There are workarounds using a custom optimizer now holding the states. |
jakethecake | Hello!As i understand it “torch.backends.cudnn.benchmark” benchmarks multiple convolution algorithms during the first epoch to then uses the fastest during subsequent epochs. If i checkpoint my model and then resume it, cudnn has to rerun the benchmark again for the first epoch of the resumed run. Is there away to save... | ptrblck | No, it’s currently not possible. |
nil_tdr | Hello!I trained my model and saved it. When I load the checkpoints from model.pth file and try to get output for different runs I am getting different outputs for the same input. Should not the weights and biases to be same for each testing of the model?Thanks for your help!Nil | ptrblck | Yes and you can manually verify it by accessing and comparing the parameters of both models.
Did you disable any randomness via model.eval()? |
Ajit | Hi,I have added classification and regression head to resnet50 pretrained model. But while training after the fine-tuning getting below error message:Screenshot from 2023-10-29 21-52-311432×1144 105 KB | ptrblck | It seems the input is a list while a tensor is expected.
Post a minimal and executable code snippet instead of screenshots for better debuggability. |
Andreas_Reich | System:I have a 1-year old Linux Machine with 1x A100 40GB, plenty of ram and a server-grade CPU. I’m using Ubuntu 20.4…Main Use:I use the machine manly to run LLM models with torch (textgeneration-webui and loading LLMS directly, but also other vision algorithms…)PreviouslySo, torch and The GPU were working fine and s... | ptrblck | All drivers are compatible within a major version due to the driver’s minor version compatibility support.
Disable MIG and it might work. |
EloyAnguiano | I’m running occupancy tests with an empty GPU, and when I move the following PyTorch module to the GPU (cuda:1), it occupies843 MiBaccording to NVIDIA SMI:I can’t make sense of it; the module is trivial.This happens even with a freshly created script that creates a Linear layer and moves it to the GPU:>>> Linear(1, 3).... | ptrblck | The first CUDA operation will initialize the CUDA context containing the driver, kernels, etc., and thus the memory usage is expected. All PyTorch binaries shipping with CUDA>=11.7 enabled lazy loading which lazily loads all needed kernels but reduces the context size. |
calcifer4889 | hello. I am trying to write a training code with two models (A, B) and two optimizers (A’, B’).For model A, it corresponds to an autoencoder structure that recovers the input data, and for the input of model B, I need a latent variable (z) that has passed through the encoder of the autoencoder.For model B, it takes the... | ptrblck | This error is raised if you are attaching new operations for the computation graph from previous iterations. Make sure the inputs to the model don’t have a gradient history (i.e. their .grad attribute shows None) or .detach() the inputs explicitly if needed. |
Teddy_Salas | Respected every one , i wanted know how to deploy a CNN model in android play store , can any one please help? | ptrblck | You could check thelegacy workflowor the newExecuTorch workflow(which is still in development if I’m not mistaken) to create your application and could then try to publish it as any other application. |
Jean-Marc_Fauche | I noticed a small bug in torchrl.envs.utils:Indeed in the _per_level_env_check function, line 394 it is codedif _data0.shape != _data1.shape:
raise AssertionError(
f"The shapes of the real and fake tensordict don't match for key {key}. "
f"Got fake={_data0.shape} ... | ptrblck | You can check theContribution Guideand create the fix inpytorch/rl. The code owners will then take a look at the fix and merge it. |
dvdsosa | Hi all,I’m trying to reproduce the example listed here with no successGetting started with transforms v2The problem is the way the transformed image appears. If I remove the transforms.Normalize line of the transforms.Compose (see code) then the transformed output looks good, but it does not when using it. I attached a... | ptrblck | This is expected since matplotlib will use the default colormap to visualize the normalized floating point numbers. “Unnormalizing” the image should show the original again. |
aghand0ur | Hello,I am installing a project that asks to set environment variableCUDA_HOME.I have installed Pytorch inside venv using:pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118How would I know CUDA path, especiallt thatnvccis not installed?Ali | ptrblck | The PyTorch binaries ship with their own CUDA runtime dependencies, not with a full CUDA toolkit including the compiler.
Since a project requires CUDA_HOME I assume it’s asking for a full CUDA Toolkit, which you would need to install separately. |
ruccidavinci | I’m wondering whether we can control class distribution from dataloader to produce every minibatch to have the same class distribution or not. I understand that we can apply class weight to the loss function, however, it is ok for batch training but I’m not sure about model learning behavior when apply the fixed class... | ptrblck | You are not multiplying the loss. The WeightedRandomSampler uses the passed weights to draw samples from the dataset ideally creating a balanced batch. The loss calculation is then a standard one without any modifications or weighting. |
cinjon | I have a model that uses torchaudio.transforms.MelSpectrogram and torchaudio.models.Conformer. It works in torch==2.0.0, torchaudio==2.0.1, and torchdata==0.6.0. However, it does not work in the latest packages - torch==2.1.0 torchaudio==2.1.0 torchdata==0.7.0. This is an issue for me as I need stuff from the later pac... | ptrblck | PyTorch ships with its own CUDA dependencies (including cuDNN) and the error message points to a locally installed cuDNN version. Either uninstall it as a workaround or remove it from the LD_LIBRARY_PATH to allow PyTorch to use its own version. |
timbmg | I have a preprocessing pipeling withtransforms.Compose(). However, I’m wondering if this can also handle batches in the same way asnn.Sequential()?A minimal example, where the img_batch creation doesn’t work obviously…import torch
from torchvision import transforms
from PIL import Image
img1 = Image.open('img1')
img2 ... | ptrblck | Yes, it can, if you pass tensors to it:
transform = transforms.Compose([
transforms.RandomCrop(24),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
x = torch.randn(64, 3, 30, 30)
out = transform(x)
print(out.shape)
> torch.Size([64, 3, 24, 24])
CC@JosueCom |
Jerome_Ku | What is the difference between Caffeopsand those in ATennative? | ptrblck | Caffe2 was merged into PyTorch a while ago with the idea to combine development efforts into one code base. However, Caffe2 is deprecated and you might want to ignore these ops. |
Potasiuombun | Hello, I am trying to implement a encoder decoder network in Pytorch, like the Tensorflow implementation here:def EncoderMiniBlock(inputs, n_filters=32, dropout_prob=0.3, max_pooling=True):
"""
This block uses multiple convolution layers, max pool, relu activation to create an architecture for learning.
Dr... | ptrblck | torchsummary is deprecated as stated on theGitHub repository:Use the new and updatedtorchinfo.
as it didn’t get any updates for a few years. |
deJQK | I would like to implement one customized function similar toscaled_dot_product_attention, as shown inthis doc. Specifically, suppose I want to replace the softmax with some modified function with learned parameterw, but maintaining the potential efficient implementation from the lower end of CUDA. I notice fromthis dis... | ptrblck | Yes, C++/CUDA extensions are a supported approach to write custom implementations and to pipe them to PyTorch as fucntions or layers. |
MidKnightXI | Hello I trained a model with MPS on my M1 Pro but I cannot use it on Windows or Linux machines using x64 processors.I was wondering if that was possible in general to do that, because I need to distribute it to these types of machines and my macbook is the most powerful machine I have currently and training it on the C... | ptrblck | As@KMT62pointed out it seems the device is stored in the actual data. Try to use map_location="cpu" in the torch.load operation or move your model to the CPU before saving its state_dict. |
Haoke_Xu | Hello,I’ve been working on developing a new convolution algorithm. During my benchmarks with cuDNN in PyTorch, I encountered an issue: I’m unable to determine which convolution algorithms were selected by cuDNN.I reviewed theConv_v8.cppfile but couldn’t find any relevant clues. Even after extracting the logs from cuDNN... | ptrblck | TheExecutionPlanBuildercontains the engine config responsible for the algorithm selection. |
vulkomilev | When I try to use this functiontorch.Tensor.masked_scatter_ — PyTorch 2.1 documentationlike solocal_add = input[0:67, 0:32, 160:192]
zeros = torch.zeros_like(input)
zeros[0:67, 0:32, 160:192] = local_add
mask = torch.zeros(67,32*10,32*10).bool()
#mask[0:67, 0:32,160:192] = True
#zeros = zeros.cuda(... | ptrblck | Try to replace the inplace tensor.masked_scatter_ op with torch.masked_scatter and assign the result to your attribute. |
cookie | Hi, I followed a tutorial on how to train a dataset for Image Classification:[link removed]github.commano3-1/Mr-AI/blob/main/Pytorch Zero to Hero/pytorch-zero-to-hero-image-classficiation.ipynb{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","ve... | ptrblck | I’m unsure where exactly you are stuck, but in case you want to interpret the output of your model you would interpret it as a tensor containing probabilities for each class given the input image. In your case the model predicts with a high probability the sample belongs to class4. Let me know if I … |
tunahanertekin | Hi,I’m trying to run distributed training on a cloud instance that has A100 80Gb NVIDIA GPUs in MIG mode. I have 7 MIG instance with type “1g.10gb”. I assigned multiple MIG instances to a container (using NVIDIA’s Kubernetes device plugin) and checked that if the instances are visible when runningnvidia-smiand saw the ... | ptrblck | You cannot use multiple MIG slices in a distributed setup as described alsohere. |
Ha_St | Hello all,I am building a model that needs to perform the mathematical operation of convolution between the batches of 1D inputcand a parameter, call itE.Thus, I want something similar tonp.convolve(E,c)but in native pytorch . Am I taking i correctly, that Conv1D is not the right tool for the job? Thedocumentationstate... | ptrblck | Flip the input or filter and you will perform a true convolution instead of a cross-correlation. |
robhen | Hi all,I have a model that I want to train using DDP in a way where I have two sets of workersW_1andW_2. Now a worker fromW_1shall update only the layersL_1, while a worker fromW_1shall update only the layersW_2. The set of layersL_1andL_2are disjoint. How can I achieve this?Let see an example:I have a modelclass Dumm... | ptrblck | Your code won’t work assuming you are using DDP since you are diverging the models. Model parameters are only initially shared and DDP depends on the gradient synchronization as well as the same parameter update to keep all models equal. In your example you are explicitly updating different parts of… |
mcorange | Here is a short code snippet.In [1]: import torch
... | ptrblck | nn.Parameter just wraps a tensor and sets its .requires_grad attribute to True as seenhere.
Don’t use or depend on the internal .data attribute as it’s user-facing usage is deprecated and it’s only used internally.
Same as 2. |
yxz77777 | My algorithm is DDPG, and my actor network is unable to backpropagate. How should I handle this issue?class ActorNet(nn.Module):definit(self):super(ActorNet, self).init()init_w = 1e-3self.input_size = 3self.output_size = 1 + 1self.fc1 = nn.Linear(self.input_size, HIDDEN_SIZE_1)self.fc2 = nn.Linear(HIDDEN_SIZE_1, HIDDEN... | ptrblck | Yes, as you can see here:
state_batch = torch.FloatTensor(np.array(state))
action_batch = torch.FloatTensor(np.array(action))
state_actor_batch = torch.cat((state_batch, action_batch), 1)
policy_Q = torch.mean(self.critic(state_actor_batch))
actor_loss = -policy_Q
actor_loss.backward()
actor_loss … |
Alon_Hazan | Using the standard code to save a model:checkpoint = {
'model': model,
'state_dict': model.state_dict(),
'optimizer': optimizer,
'scheduler': scheduler
}
torch.save(checkpoint, path_out)Since refactoring my code, the architecture Class is in a different name so i ... | ptrblck | You are not using the standard and recommended approach since you are storing the model directly besides its state_dict. Storing model will add the requirement to restore the same file location, so remove 'model': model and just store the state_dict instead to avoid such issues. |
TsukeBurrel | Hello, I am fine-tuning pretrained SSDlite model from torchvision.The training somehow goes well when I feed bounding boxes coordinates in absolute coordinates to the fed image size. However, the bb coordinates “theoretically” should be normalized.I’d like to know that In what format does the SSDlite in torchvision exp... | ptrblck | I don’t know how exactly you are feeding the bounding box coordinates to the training, but based on themodel definitionthe output coordinates don’t seem to be normalized:
- boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
``0 <= x1 < x2 <… |
AlanTuring | Dear PyTorch community,in PyTorch, can you tell me if and how i can know if the weights of a neural net are re-initialized with a random seed at each run, i.e., if I run multiple times my .py script, are the generated weights different (i.e., different realizations of a R.V. of the same distribution (uniform I guess)) ... | ptrblck | You can simply print any weight (or e.g. its .double().abs().sum()) and will see that different seeds are used in each run unless you are explicitly seeding the code. |
riririririi | Let’s say I have trained a resnet-50 model and i have replaced its last fc layer with a custom defined layer which performs l2 normalisation on the output of the avgpooling layer, making the last few layers look like this:-----previous layers------)(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))(fc): Sequential((0): L... | ptrblck | The simplest approach might be to load the state_dict into the model before adding the new layers. Alternatively, you could also add new key-value pairs into the state_dict as it’s derived from a dict. |
mariosconsta | I have this function to save the modelsave_checkpoint(
{
"epoch": epoch + 1,
"state_dict": self.model.module.state_dict(), # Model layers / weights
"best_score": self.args[
"best_pred"
], # Save best score (scalar)
"optimizer": self.optimizer.state_dict(),
}... | ptrblck | The additional .module keys were added by nn.DataParallel and manipulating the state_dict is a valid approach to fix it. Use strict=False only if you are sure you can ignore missing or unexpected keys. |
Gennaro_Vaccaro | Hi.I’m trying to install torch version 2.1.0 but with cuda 11.7.I tried this installation: python3.9 -m pip install --no-cache-dir torch --index-urlhttps://download.pytorch.org/whl/cu117But strangely, it installs torch 2.1.0+cu121.On my Pod there is the installation of nvidia 515.65.01+ cudnn 8.5.0.96, with cuda 11.7, ... | ptrblck | If you don’t want to update your NVIDIA driver making it compatible with CUDA 12.x, you could install the PyTorch binaries with CUDA 11.8 as given in the install instructionshere. |
Chuong_Vo | Hello,I’m currently working on a problem that involves annotating the classification ground truth for three elements, where each element can belong to one of three classes. An example of this type of annotation is:[0, 1, 2],[2, 0, 0], or[0, 2, 2]. This form of annotation is reminiscent of semantic segmentation, as it c... | ptrblck | I don’t fully understand the use case since you describe it first as:
which sounds as if these lists contain class indices for 3 elements while later you explain:
I assume each batch contains 3 elements each belonging to one of 3 possible classes?
If so I also assume your target has the shape [… |
Mona_Jalal | I have these: (GitHub - chensong1995/HybridPose: HybridPose: 6D Object Pose Estimation under Hybrid Representation (CVPR 2020))(hybridpose) mona@mona-ThinkStation-P7:~/HybridPose/lib/ransac_voting_gpu_layer$ export CMAKE_CUDA_HOST_COMPILER=/usr/bin/g++-10
(hybridpose) mona@mona-ThinkStation-P7:~/HybridPose/lib/ransac_... | ptrblck | Could you update your locally installed CUDA toolkit (currently 11.5 is installed) to the latest 11.8 or 12.x release, please? |
Nerrror | Hey,so I’m working on a problem where I have multiple losses and I want to stop backpropagation of one of the losses before the end of the computational graph. In more detail:I have a tensor x (y_0 in my second post) which has already been passed through a couple of pytroch functions, so the grad_fn attribute is not No... | ptrblck | I’m not sure if I fully understand the network structure but would explicitly computing gradients for the subnetwork via e.g. torch.autograd.grad or by providing inputs to backward work? |
Chuong_Vo | Hi guys!I’m doing some experiments with the EfficientNet as a backbone.I’m using the pre-trained EfficientNet models fromtorchvision.models.As I found from the paper and the docs of Keras, the EfficientNet variants have different input sizes as below.image734×355 11.2 KBIs it true for the models in Pytorch?If I want to... | ptrblck | Yes, the torchvision EfficienNet models also expect a different input shape as described in thedocs:
The sizes of the EfficientNet models depend on the variant. For the exact input sizescheck herewhere the link points to:
elif args.model.startswith('efficientnet_'):
sizes = {
… |
Jazzy66 | Hi, everyone. I am working on a dynamic programing problem in which a nested neural network is implemented. For the sake of better understanding my question, simply assume the loss isL = G(k’) - H(k’')where G and H are two functions we do not need to know but variable k’ and k’’ stem from neural network NNs such thatk’... | ptrblck | Autograd will create a computation graph during the forward pass and will use it to backpropagate through it during the backward call.
Yes, increasing the computation graph adds more operations to the forward and backward passes and increases the memory usage.
Depending on how the entire recursion … |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.