user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
ttiago_jm
Hi,I’m porting a Tensorflow project to PyTorch and after executing I realize that Tensorflow is faster than PyTorch during training and it’s weird to me.I isolate the 2 projects in 2 different notebooks with all classes and functions needed to train the model.Remember this is just a snippet of a bigger project (a proje...
ptrblck
Since the conv is not trained at all, you could use adaptive pooling layers instead as I don’t understand how your current approach of using new random filters could work. In any case, since you still see a slowdown you would need to profile the code using the native profiler or e.g. Nsight Systems…
Martin_Kodovsky
Hello, I’m experiencing the following trouble:Python 3.11.1 (main, Jan 6 2023, 00:00:00) [GCC 12.2.1 20221121 (Red Hat 12.2.1-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import torch Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/user/...
ptrblck
Are you running your REPL in the source directory? File "/home/user/path/pytorch/torch/utils/backend_registration.py", line 1, in <module> from torch._C import _rename_privateuse1_backend ImportError: cannot import name '_rename_privateuse1_backend' from 'torch._C' (/home/user/path/pytorch/tor…
ays
I have two segmented images, and I’ve computed the dice score using the formula below, however, I keep getting values greater than 1 (like 11.8, 12.8) as a dice score. is there a reason why? or is my approach for computing the dice score wrong?def dice(X, Y): intersection = (X * Y).sum() union = X.sum(...
ptrblck
It depends what these values now represent and which of tour operations applied during the training process change the range of these tensors. E.g. if X represents raw logits (in which case any value in [-Inf, +Inf] would be valid) you could create probabilities using sigmoid or softmax (it would d…
Kirtikumar_Pandya
How can I remove model state_dict keys?model_checkpoint_path = 'xyz.ckpt' model_checkpoint_load = torch.load(model_checkpoint_path, map_location='cpu') model_state_dict = model_checkpoint_load['state_dict'] model_state_dict = model_state_dict.copy() for key in model_state_dict.keys(): if key.startswith('loss'...
ptrblck
You could collect the keys you want to remove in the loop and delete it afterwards: model = models.resnet18() sd = model.state_dict() layers_to_remove = [] for key in sd: if "conv" in key: layers_to_remove.append(key) print(layers_to_remove) # ['conv1.weight', 'layer1.0.conv1.weight',…
desert_ranger
I am trying to write my own actor critic algorithm. Unlike other implementations, I tried to keep a separate actor and critic network.The problem arises somewhere in my actor or critic loss functionI found a similar question here, but that doesn’t solve my problem -Backward error, although there are two different netwo...
ptrblck
Both losses, critic_loss and actor_loss use the advantage tensor in their computation. The first actor_loss.backward() call will free the intermediate forward activations stored during the previous forward pass, which will cause critic_loss.backward() to fail since both backward passes depend on th…
ha2ka
Hi,I am currently experimenting with automatic differentiation.I wrote the following script, but the error signal returned fromtorch.tanhis not what I expected.I expect the error signal returned from tanh to be 0.9151. Because the input oftorch.tanhis 0.3 of tensor in the following script, so its derivative must be1.0 ...
ptrblck
The tanh derivative shows the expected value using: x = torch.tensor(0.3, requires_grad=True) y = torch.tanh(x) y.backward() print(x.grad) # tensor(0.9151) and also shows the same value in your code if you remove fc2.
Aml_Hassan
Hi there,I’m trying to embed my data using ResNet34 as an embedding model and Triplet loss as my loss function. The backpropagation step in my training takes an insane amount of time and I need help making it faster. You can see my loss function and the training loop below:class TripletLoss(nn.Module): def __init__...
ptrblck
How slow is the backwards pass? On my system using a 3090 and a recent nightly pip wheel I get: forward pass: 0.085 loss calculation: 0.001 backward pass 0.177 optimizer step 0.007 forward pass: 0.092 loss calculation: 0.001 backward pass 0.175 optimizer step 0.006 forward pass: 0.087 loss calcu…
Anton_Uramer
I’m using the nightly PyTorch (for CUDA 11.8) installed with conda, conda was installed with the standard visual installer.python -m torch.utils.collect_env Collecting environment information... PyTorch version: 2.0.0.dev20230130 Is debug build: False CUDA used to build PyTorch: Could not collect ROCM used to build Py...
ptrblck
I don’t know why (as I’m not using Windows), but the CPU-only binaries were installed as indicate by the cpu tag: [conda] pytorch 2.0.0.dev20230130 py3.9_cpu_0 pytorch-nightly Maybe try to install the pip wheels and see if this would work.
yongjun_Hong
Hello.When I do following, o1 and o3 are different (Isn’t it should be the same values?)Model contains only BatchNorm2dIf model is not updated in train mode (like below, no optimizer step), I think o1 and o3 should be same.o2 can be different from o1/o3 due to BatchNorm2dWhen is it possible o1 and o3 different ? (I thi...
ptrblck
The outputs are computes as: o1 will be computed using the running stats from batchnorm layers to normalize the corresponding input activations. o2 will be computed using the activation stats in batchnorm layers to normalize the input activations. The running stats of batchnorm layers will be up…
mas
Hi all follow developers,I have been struggling to create a custom dataloader in c++ torch. I think I am missing some key concepts. Could someone help guide me to the right path?I have both input and target. However, I am struggling to create a dataset to run:torch::data::make_data_loaderThank you.
ptrblck
What kind of issues are you seeing?This code snippetshows a minimal example how to use make_data_loader.
Shisho_Sama
Hi everyone, hope you are having a great time.I recently faced this issue, where back in 1.8 or 1.9 I had to train a model with dropout’sinplace=Flaseor otherwise it would crash, now in 1.11 and 1.13.1 I cant seem to flip that back to True and seems I’m stuck with dropoutinplace=False! if I set that to True, I get this...
ptrblck
That’s not the case, since ReLU uses its output for the gradient computation as definedhereand as shown in this code snippet: x = torch.randn(1, 10, requires_grad=True) # works relu = nn.ReLU() out = relu(x) out.mean().backward() # out-of-place dropout still works out = relu(x) out = F.dropout…
shrbrh
Is there a way to plot the histograms of a colored image in pytorch?
ptrblck
torch.histogram should work as seen here: x = torch.from_numpy(np.array(image)).float() bins = torch.linspace(0, 256, 257) hist = [torch.histogram(c, bins=bins) for c in x] plt.plot(hist[0].bin_edges[:-1], hist[0].hist, color="r") plt.plot(hist[1].bin_edges[:-1], hist[1].hist, color="g") plt.plot…
qiminchen
I have two questions aboutzero_grad()releasing GPU memoryDoesnet.zero_grad()release the GPU memory occupied by the gradients computed from previoue epoch?Suppose I have two networksnetDandnetG, in the below code snippet, can I add extrazero_grad()afteroptimizer.stepto release some GPU memory before going to the next ep...
ptrblck
Not in the default .zero_grad() call, since the .grad attributes will just be filled with zeros, but not deleted. To delete the .grad attributes and to save memory, you would need to call .zero_grad(set_to_none=True). Yes, if you don’t need the gradients from a previous model anymore you can di…
NishantN
I am using torch.utils.save_image() to save an image that has 5 channels. The image is formed by concatenating 12 images together across dim 3. The current dimensions of the image are (16, 5, 128, 1536) with 16 being the batch size.Code:r = self.denorm(x_concat.data.cpu()) save_image(r, sample_path, nrow=1, padding=0)T...
ptrblck
I don’t think a native image format using 5 channels exists, so you would not be able to store this type of data as an image. I don’t know what your data represents, but you could store the tensor directly via torch.save.
Yuxuan_Xue
Hi!i have a question regarding the usage of the torch.scatter() function.I want to construct a weights matrix weights (# [B, N, V]. B is batch size, N is number of points and V is the number of features for each point. )Let’s say i have two tensorsa = # shape [B, N, k], where B is batch size, N is number of points, k i...
ptrblck
Isn’t this exactly what my code is doing? It selects values from a matrix a in the shape [B, N, V] using indices in [B, N, k] and assigns these to b, which is initialized with zeros for all other values. If not, could you post a slow reference implementation, please?
sailboats
Hi! I just migrated to Ubuntu on my Asus Tuf Laptop and am having difficulty getting Stable Diffusion via Automatic1111 repo up and running due to pytorch not being able to use my GPU.My setup:I installed nvidia drivers via apt (tried 525, also didn’t work). Currently nvidia-smi gives me:+------------------------------...
ptrblck
Yes, I think you are right and indeed the rocm version was installed. I don’t know how you are installing PyTorch (and other dependencies) in your environment, but maybe it’s possible to pre-install PyTorch with e.g. CUDA 11.7 via pip install torch as described in theinstall instructions.
Johan_Adler
I have defined a function as follows:class GradReverse(torch.autograd.Function): def __init__(self, lambd): self.lambd = lambd @staticmethod def forward(self, x): return x.view_as(x) @staticmethod def backward(self, grad_output): return (grad_output * -self.lambd)But during...
ptrblck
The forward and backward methods are defined as staticmethods and are thus expecting cls as the first argument, while you are expecting to access the self attribute of an object (not the class). Pass lambd into the forward and use ctx.save_for_backward() or assign it to cls to use it in the backwar…
BanBot2
Hello everyone,I’m currently working on a deep neural network that tries to locate musical onsets in audio samples. It returns a 1D tensor containing the probability of an onset at each timestamp, from 0 to 1. It’s working pretty well, but sometimes it returns a double onset where there should only be one.(The double p...
ptrblck
I haven’t read the details of this paper, but something like this might work: x = torch.zeros(1024) x[512] = 1. x[525] = 1. # add noise x = x + torch.randn(1024) * 0.01 plt.plot(x) filt = torch.hamming_window(32) out = F.conv1d(x[None, :], filt[None, None, :], padding=filt.size(0)//2) / filt.sum()…
0x97
I am instantiating a model, and I would like to pass the device as an arg from a configuration dataclass, and then inside the model class perform:self.to(config.device)but after a check, the model is not on ‘cuda’.Is there any way of doing this?
ptrblck
It works for me: class MyModel(nn.Module): def __init__(self, device): super().__init__() self.fc1 = nn.Linear(1, 1) self.fc2 = nn.Linear(1, 2) self.to(device) model = MyModel("cuda") print(model.fc1.weight.device) # cuda:0 print(model.fc2.weight.device)…
Adlrn
I am trying to minimize the results of some operations that involve the output of a model inside my training loop.First I use the outputs of the model to compute a set of equations. Then I compute new values base on the equation results. I calculate the loss per these new values and sum it to send it to the backward ()...
ptrblck
No, I don’t see where issue might be caused and using random input tensors: model = NeuralNetwork(10, 13, 3) criterion = nn.MSELoss(reduction='mean') optimiser = torch.optim.SGD(model.parameters(), lr=1e-5) input_tensor = torch.randn(10, 10) step = torch.randn(10) I get a different error: # Run…
mzimmerman
InDataLoader, we could specify theworker_init_fnargument to change the seed accordingly. This however requires the worker to call the init function, effectively only during initialization of the worker. Is there any way I could change the seed of worker during runtime? For example, changes at every n minibatches?Thanks...
ptrblck
Yes, you can set the seed via torch.manual_seed inside the Dataset.__getitem__ and could also use the worker info as seen here: class MyDataset(Dataset): def __init__(self): pass def __getitem__(self, idx): worker_info = torch.utils.data.get_worker_info() if worker_…
0piero
I checked the source of the Subset class (torch.utils.data.dataset — PyTorch 1.13 documentation) and saw that passing a list to a subset object like subset.getitem([1,2,3]) should work, but actually it’s not:…/dataset.py", line 272, ingetitemreturn self.dataset[self.indices[idx]]TypeError: list indices must be integers...
ptrblck
It seems to work for me: dataset = TensorDataset(torch.arange(10)) subset = Subset(dataset, indices=list(range(0, 10, 2))) for data in subset: print(data) # (tensor(0),) # (tensor(2),) # (tensor(4),) # (tensor(6),) # (tensor(8),) data = subset.__getitem__([0, 1, 3]) print(data) # (tensor([0, …
zak_bel
Hi, I am having doubt about using a traced function during training. So I made this regularization function that is quite computationally expensive and slows down training (despite vectorizing it). I tried optimizing it using JIT so I trace it and use it during training. Is it safe to use that way even if JIT is more f...
ptrblck
Yes, Autograd will still work and will calculate the same gradients (up to floating point precision). You can run a quick check as seen in this small example: device = "cuda" model = nn.Sequential( nn.Linear(10, 10), nn.ReLU(), nn.Linear(10, 10) ).to(device) x = torch.randn(1, 10, dev…
bugramurat
My trained FasterRCNN object detection model returns NoneType output while predictionError output:Test instances: 8 Traceback (most recent call last): File "c:\Users\lemon\Desktop\ap_py_2\inference.py", line 48, in <module> outputs = model(image.to(DEVICE)) File "C:\Users\lemon\miniconda3\envs\cnn-env-03\lib\si...
ptrblck
Detection models use the ImageList class to hold a list of tensors with potentially varying sizes. You should be able to access the internal tensors via the .tensors attribute. I don’t know what exactly you’ve changed but I would probably check why self.backbone(images.tensors) is failing as an Im…
cjpurackal
I’m pretty new to libtorch, i’m calling the below function inside a for loop for every new image.torch::Tensor Tracker::optimize_cam_in_batch(torch::Tensor& cam_tensor, torch::Tensor gt_color, torch::Tensor gt_depth, int batch_size, NICE decoders) { std::vector<torch::Tensor> cam_para_list{cam_tensor}; cam_tensor = ...
ptrblck
Could you check the stacktrace via gdb to see which line of code is raising the error and which tensor might be undefined? I don’t see any obvious issues in your code so far.
J_Johnson
Wondering what the best practices are. Model gives out [batch_size, sequence_length, class_probabilities]. And I would like to apply CrossEntropyLoss on the class probabilities and sum up that loss over the sequence length before back prop.So my question is should I loop over the sequence length and sum the losses, or ...
ptrblck
I’m unsure if I understand the use case correctly, but would this work? batch_size = 2 sequence_length = 3 class_probabilities = 4 logits = torch.randn([batch_size, sequence_length, class_probabilities], requires_grad=True) targets = torch.randint(0, class_probabilities, (batch_size, sequence_leng…
tanabe.d.zc32s
Hi there.I tried to implement Grad-CAM with Register_forward_hook, but ran into a problem when I let the loop process estimate test data from Dataloader.If I apply the following hook with Register_forward_hookdef forward_hook(module, inputs, outputs): global feature feature = outputs[0].clone() forward_handle ...
ptrblck
Yes, that’s the case. The registered forward hook will be triggered in each forward pass as seen here: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer = nn.Identity() def forward(self, x): x = self.layer(x) r…
tanabe.d.zc32s
Hello.I have recently been trying my hand at learning with Data Parallel using Distributed Data Parallel (DDP).I understand that learning with DDP is done by creating replicas of the model on multiple devices (e.g. GPUs), splitting the data and training them, and synchronizing the weights. My question is, when are the ...
ptrblck
DDP will broadcast the state_dict during the construction of the DDP object as described in theDDP - Internal Design docs.
nbansal90
Hello Folks,I am trying to trace my custom model usingtorch.jit.tracefor getting mobile runnable model. I am following the step-by-step procedure mentioned in thePytorch Mobiledocumentation page.However, for my model, it fails during the tracing process with the following error:Error: :List trace inputs must have eleme...
ptrblck
That’s a good point. Could you check if defining the optional arguments as: maybe_unused_argument=None, # type: Optional[List[str, Tensor]] would work? I checked some torchvision detection models as it’s used e.g.herefor the target input argument to forward, which is only needed during trainin…
soonchangAI
How to calculate second derivative gradients for mixed precision. I try calling backward() twice but it gave the same gradients as first derivative.self.scaler.scale(loss).backward() self.scaler.scale(loss).backward()
ptrblck
Calling backward multiple times will calculate the same gradients and accumulate them. You would need to backward the derivatives again as described inthis post.
arunppsg
Here is a small sample of code:import torch import torch.nn as nn def func(m: nn.Module): p_grad = m.weight.grad.data return NoneI am wondering, is it good to assignm.weight.grad.datato a variable and use it later? The reason ism.weight.gradcan also beNone. In pytorch 1.13.0, mypy throwserror: Item "None" of "...
ptrblck
No, it’s not because the usage of the .data attribute is deprecated and you shouldn’t use it and (as you can already see) the .grad attribute is not necessarily defined. Add checks to the .grad usage and make sure it was created before trying to assign or use it.
Zhaoyi-Yan
When running my code on pytorch 1.2, it takes 305s per epoch, it speeds significantly and costs only 220s on pytorch 2.0.I do not usetorch.compilesince the cuda is only 11.1 in my environment.It is really a big surprise for me.I wonder how it could run so fast ?
ptrblck
torch.compile with the pytorch-triton backend uses your locally installed CUDA toolkit to compile the kernels during its code-generation step (in particular the locally installed ptxas) and depends on CUDA>=11.4. In future releases the needed ptxas should be packaged into the binaries so that your l…
Aryaman_Pandya
I just got torch and CUDA (11.7) set-up on my device and am able to verify that cuda.is_available() and is being used. However, when I run a script in a Python3.8.10 virtual env with all the necessary modules, I get the following error:Could not load library libcudnn_cnn_train.so.8. Error: /home/aryaman.pandya/Desktop/...
ptrblck
Yes, cuDNN is a dependency and the PyTorch pip wheels will pull them as shown during the install steps: pip install torch Collecting torch Downloading torch-1.13.1-cp39-cp39-manylinux1_x86_64.whl (887.4 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 887.4/887.4 MB 58.3 MB/s eta 0:00:00 Collect…
Ruslan_Mukhamadiarov
Hello! I am trying to implement Actor Critic algorithm in C++, and for some reason the weights of my Actor and Critic networks are not being updated.My Actor.h#pragma once #include <torch/torch.h> class ActorImpl : public torch::nn::Module { public: ActorImpl(int input_dims, int hidden_size, int n_actions)...
ptrblck
Thanks for the missing code! These lines of code: auto av_total_loss = accumulate(total_loss.begin(), total_loss.end(), 0) / (1.0*total_loss.size()); torch::Tensor return_loss_as_tensor = torch::tensor(av_total_loss, torch::requires_grad()); are detaching av_total_loss from the computation graph …
ptrblck
I’m not familiar with developing on Windows but based on the screenshot it seems the compiler (in particularcc1plus) ran into an internal error. Maybe updating the C++ toolchain could help.
ptrblck
If you have trouble installing the CUDA toolkit inside a container, use the CUDA development containers with an already installed CUDA toolkit. You can check the compiler version via nvcc --version.
papoo13
I am trying to initialize my original PyTorch ResNet18 model with pre-trained weights. I’m targeting all the layers but the last weight and bias. My code in the following does not work. I am not getting any errors but the model is not getting pre-trained. Is this incorrect? I am not bale to find the bug in there.I have...
ptrblck
This assignment: self.model.state_dict()[key]=value will not work and you should copy_ the value into the parameter directly via: with torch.no_grad(): model.layer.parameter.copy_(value) or manipulate the state_dict separately and load it into the model: sd = model.state_dict() ... sd[key]…
111357
I know the fp32 and fp16 have different ranges.How does the PyTorch handle the tensor whose value is outside the fp16 range when casting?For example, x = torch.Tensor([66666])If it cast x into inf, does this mean the gradient is Nan, and the training will fail?
ptrblck
Yes, you can take a look atGradScaler.stepand_maybe_opt_stepto see the implementation.
Taejune
Hi, I’m wondering what is the main difference betweentorch.cuda.synchronize()anddist.barrier().I know that the former prevents CPU thread from proceeding until the previous works are done,and the latter makes processes wait until every process reachesdist.barrier().So I think those two have the same purpose… what’s the...
ptrblck
torch.cuda.synchronize() synchronizes the current device and waits until all GPU work is finished thus blocking the host from advancing. dist.barrier is used in a distributed setup and synchronizes all processes until the group enters this function. Even if all GPU work is already done in one proce…
emma_ng
Hi, I am confused about the BatchNorm layer behaviour during testing:In previous answer (The behavior of the BN layer in train and eval mode), it is mentioned that if I set model.eval(), the running stats (mean, std) will be used to do normalization.What is the running stats? Are those values fixed from the trained mod...
ptrblck
No, the running stats are stored as the internal running_mean and running_var and updated during training (i.e. after calling .train() on the batchnorm layer which is the default mode after initialization) in each forward pass using the specified momentum as described in thedocs: This momentum ar…
peony
I am doing action recognition with mediapipe keypoints. These are the shapes of some of my tensors:torch.Size([3, 3, 75]) torch.Size([3, 6, 75]) torch.Size([3, 10, 75]) torch.Size([3, 11, 75]) torch.Size([3, 9, 75]) torch.Size([3, 4, 75]) torch.Size([3, 21, 75])The height of each tensor varies as they refer to the numb...
ptrblck
Negative padding seems to slice the tensor as seen here: x = torch.randn(3, 3, 75) height = x.size(1) source_pad = F.pad(x, pad=(0, 0, 0, 8 - height)) print(source_pad.shape) # torch.Size([3, 8, 75]) x = torch.randn(3, 9, 75) height = x.size(1) source_pad = F.pad(x, pad=(0, 0, 0, 8 - height)) prin…
Geoffrey_Payne
The error message appears clear enough but I do not understand why I am getting it or how to fix it.My code is as follows;for epoch in range(hyper.epochs): epoch_loss = 0 epoch_accuracy = 0 for data, label in train_loader: data = data.to(gpu.device) label = label.to(gpu.device) ...
ptrblck
Based on the error message it seems as if the input tensor use the uint8 dtype while the model uses the expected float32 dtype. Note that PILToTensor will keep the same dtype of the input image which is most likely causing the issue. Use ToTensor() to normalize the input image and return it in float…
ycy
I’m getting the errorValueError: Expected input batch_size (72) to match target batch_size (32).for the following code:import torchimport torch.nn as nnimport numpy as npimport matplotlib.pyplot as pltfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoaderimport pandas as pdclass DiabetesDataset(Dat...
ptrblck
nn.CrossEntropyLoss expects model outputs containing raw logits in the shape [batch_size, nb_classes, *] and target in the shape [batch_size, *] containing class indices in the range [0, nb_classes-1]. Based on the error message you are trying to use a target class index of 372 while the model outp…
Arthur_F
Hello,I would like to know exactly how are the eigenvalues and eigenvectors computed when calling torch.linalg.eigh. I tried to look into the C source code but I could not find the information, hence my post.Thanks in advance !
ptrblck
On the CPU LAPACK would be used as seenhereon the GPU either MAGMA or cuSOLVER would be used as seenhere.
peony
Hello, I am trying action recognition. If I understand correctly the codef = f.view(f.size(0), -1)flattens the tensor but forfs[:, i, :] = f, I can’t seem to guess what it is doing there.def forward(self, inputs, hidden=None, steps=0): length = len(inputs) fs = torch.zeros(inputs[0].size(0), length, sel...
ptrblck
fs[:, i, :] = f assigns the tensor f in the shape [fs.size(0), fs.size(2)] to each “row” in fs. Here is a small example where f is containing increasing values for the sake of simplicity: fs = torch.randn(2, 3, 4) f = torch.randn(2, 4) for i in range(fs.size(1)): f = torch.ones(fs.size(0), fs…
John4
Hello! I’m implementing a ViT to be applied to (76,50,50,116) images where the possible classes are [0,1,2,3]. When I run the script with a reduced dataset (ex. 5 images) it works, but when I use the entire dataset the “IndexError: too many indices for tensor of dimension 1” appears in the following part:class MyMSA(nn...
ptrblck
Based on your code you are passing sequences to your model’s forward method and are then iterating this object so check where sequences comes from and how its shape is defined.
sashapiv
Hi everyone,I have two tensors:A -> (128,19,3,99,99) #(batch, date, data, data, data) B -> (128,9,223) #(batch, date, data)After encoding I will have something like that:A2 -> (128,19,10) # (batch, date, encoded data with CNN_1) B2 -> (128,9,10) # (batch, date, encoded data with CNN_2) C -> (128,28,10) # merge of A2 a...
ptrblck
You could concatenate both tensors with their dates to a single (unsorted) one, create the sorted indices via e.g.: date = ['2021-12-13', '2022-01-02', '2022-02-14', '2021-12-28', '2022-02-06', '2022-01-10', '2022-01-20', '2022-01-26', '2022-03-17', '2022-02-22', '2022-03-02', '2022-03-21', '2022-0…
Vinayaka_Hegde
I’m getting a runtime error that :An attempt has been made to start a new process before the current process has finished its bootstrapping phase.Whennum_workers = 0, there is no problem at all. But when I increase it to 1, I’m getting the above error.Code used :import torch import torchvision import torchvisio...
ptrblck
Could you wrap your code into the if-clause guard as describedhereand see if this would solve the issue?
rinkujadhav2013
I’m trying to follow tips fromPyTorch’s performance tuning guide. One of them is that one could try using tcmalloc from google.Since I don’t have root permission on the server, I installed it locally and added path to thetcmalloc.so*files toLD_LIBRARY_PATHand path to include files toCPATH. I then added the# export LD_P...
ptrblck
export LD_PRELOAD should not be a comment in your Python code but should be exported in your current terminal. Once this is done you could use LD_DEBUG=libs to check if the linker is indeed preloading the right library.
JkimIshere
class CNN(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) # 1 * 28 * 28 -> 6 * 24 * 24 self.conv2 = nn.Conv2d(6, 16, kernel_size=5) # 6 * 12 * 12 -> 16 * 8 * 8 self.pool = nn.MaxPool2d(2) self.fc1 = nn.Linear(256, 100) ...
ptrblck
The usage of torch.flatten(x) sounds wrong as it would flatten the entire tensor as seen here: x = torch.randn(10, 256) print(torch.flatten(x).shape) # torch.Size([2560]) Using x = x.view(-1, 256) sounds better in case you can guarantee the tensor has a feature size of 256. The better approach wou…
nalinbot
Hey, I am trying to train a FCN model(https://pytorch.org/vision/stable/models/generated/torchvision.models.segmentation.fcn_resnet50.html#torchvision.models.segmentation.fcn_resnet50) on a segmentation dataset however the loss doesn’t seem to decrease and converge and I’m totally clueless why. I do my backward and for...
ptrblck
These lines of code look wrong as it should not be needed to set the .requires_grad attribute of the model output to True unless it was detached. If so, then the previously used parameters to calculate preds will not be updated which could explain the issue you are running into. If you are seeing…
FHofstaetter
While I am working on an RL problem I am tagging this under vision because it seems to be a problem with a convolutional network I am using. I have tried my code on a different problem with a non-convolutional architecture and it worked fine.I’m implementing a Reinforcement Learning algorithm to learn Atari games using...
ptrblck
Could you check if removing the last nn.ReLU might help? Negative outputs would be clipped to max(0, x) which would result in a zero gradient: x = torch.tensor([-1., -2., -3.], requires_grad=True) out = F.relu(x) out.mean().backward() print(x.grad) # tensor([0., 0., 0.])
Vinayaka_Hegde
Hi, I want to find a very simple dataset of let’s say 10 images per class and few very classes. I would need small dataset since I’m modifying pytorch source code. And adding log statements. So, when there arenum_workers> 0, then it would be very difficult to trace what’s happening internally.The simplest dataset I kno...
ptrblck
Yes, your explanation is right and I’ve used the code to create nb_images each containing a different value. I’ll reduce the nb_images as well as the spatial size as it would otherwise be a long output in this post but here is the result: nb_images = 5 data = torch.ones(3, 5, 5).expand(nb_images, …
Vinayaka_Hegde
Ive installed pytorch version below and tried running a piece of code which is producing the below error. Please help !!Error log when I ran the code below:File "D:\DREAM\pytorch\mycode\dataloader_test_1.py", line 15, in <module> transforms.toTensor(), AttributeError: module 'torchvision.transforms' has no attribut...
ptrblck
You have a typo and transforms.ToTensor() should work (note the capital T).
Huxwell
I am trying to pass soft targets to mobilenet v2 (with the only change that I am using 2 classes instead of 1000).According toCrossEntropyLoss — PyTorch 2.1 documentationand various similar posts, since ~2022 float targets are accepted by CrossEntropyLoss. However, for me it still fails.The Last layer is:nn.Linear(in_f...
ptrblck
As described in the docs the shape for “soft” targets is expected to be the same as the model output: If containing class probabilities, same shape as the input and each value should be between [0,1]. This would thus work: activations = torch.FloatTensor([[-0.3139, -0.0486], [-0.0510, 0.0470],…
Alireza
Hi,I have trained a fully convolutional neural network for monocular depth estimation, and its performance is quite satisfactory. I have used depthwise separable convolution instead of all normal convolutions in order to decrease the trainable parameters. However, the speed of testing a new image is relatively slow. Th...
ptrblck
Take a look at thePerformance Guide, which explains that e.g. cudnn.benchmark=True could be used for static inputs etc.
Mafuyu_Aizawa
Hello I’d like to ask how could I do bitwise operations on float tensors? Currently I have to use struct to convert them and then do the operation on CPU and move back, which is very inefficient… Do we have pytorch solutions for that?Found previous questions like 6 years ago but no solutions there:Bitwise Operations on...
ptrblck
view should work as seen here: a = torch.tensor(1., device="cuda") b = a.view(torch.int) print(b) # tensor(1065353216, device='cuda:0', dtype=torch.int32) # both represent this bit pattern # 00111111 10000000 00000000 00000000 and allows you to interpret the data in another format.
spiegelball
I have two instances of the same model, living on different devices. The inference results differ. Is it possible to compare the models “step-by-step” to figure out which calculation is faulty?
ptrblck
One possible approach would be to use forward hooks and to compare the intermediate outputs of each layer.This postgives you an example on how to register the hook and how to print it. You could use different dicts or store the desired outputs using different keys etc.
shrbrh
Hello!I want to check whether each value of a tensor of shape [1, 1, 16, 16] is greater than 2. I tried doing it simply byif(myTensor > 2)but it throws the following error:RuntimeError: Boolean value of Tensor with more than one value is ambiguousIs there any way to create a tensor of shape [1, 1, 16, 16] with all its ...
ptrblck
The if condition expects a single True or False statement while your comparison myTensor > 2 could yield multiple outputs as it’s an elementwise comparison. If you want to check if all values in myTensor are > 2 you could use: if (myTensor > 2).all(): To create a tensor with all values set to 2 y…
John4
Hello, I’m developed the following model, but when I tried to print model(x) I get the NotImplementedError (I think the indentation is ok). Did anyone meet this problem?class MyVit(nn.Module): def __init__(self, chw=(1, 28, 28), n_patches=7, hidden_d=8): super(MyVit, self).__init__() self.chw = chw ...
ptrblck
You have to pass the input activation to each layer as seen here: n_heads = 5 d_heads = 10 q_map = nn.ModuleList([nn.Linear(d_heads, d_heads) for _ in range(n_heads)]) x = torch.randn(1, d_heads) out = x for layer in q_map: out = layer(out) print(out.shape) # torch.Size([1, 10])
PaTrickWwW
According to the torch.fft doc, the rfft2 is equivalent to a combination of 'fft()'and ‘rfft()’, but when I apply it to an image, the results of the combination of separable fft mismatch with the rfft2, why?image1033×227 11.8 KB
ptrblck
The docs use assert_close which compares floating point numbers with a small eps depending on their dtype while you are comparing both results for bitwise-identical results, which will easily fail for floating point numbers due to the limited precision and a potentially different order of operations…
Mole_m7b5
I’m currently training a ResUnet with 3 encoding blocks, 1 bottleneck, 4 decoding blocks, and an output layer and I’m using an RTX 3090. I seem to be having trouble fitting the model, training, and validation within the available 24GB memory.The model size itself isn’t that large, and I have a batch_input.shape() of (4...
ptrblck
During training Autograd will store intermediate forward activations since these are needed for the gradient computation. If you don’t want to train the model or compute gradients you could disable this behavior by using with torch.no_grad() which will delete the intermediates.
AleTL
Hi!I’m running a script and, always, at the iteration number 30 of the second epoch, which has nothing special, I receive the following CUDA error:File "/home/script.py", line 86, in forward print("X before mask: ", x, flush=True) File "/home/envs/myenv/lib/python3.8/site-packages/torch/_tensor.py", line 203, in ...
ptrblck
The prob_array is most likely containing invalid values as seen here: # works prob_array = torch.tensor([0.0, 0.5, 1.0], device='cuda') sample_prob = torch.bernoulli(prob_array) print(sample_prob) # tensor([0., 1., 1.], device='cuda:0') # fails prob_array = torch.tensor([0.0, 0.5, 1.1], device='cu…
J_Jordano
Hi, I’m currently working on PyTorch project to implement a minibatch discrimination(kind of nested module in discriminator) on my GAN code.But after monitoring the training procedure, I find that my RAM usage is increasing over epochs. And RAM usage causes my whole system halts so that my GAN cannot continue to learn....
ptrblck
An increase in memory usage is usually caused by storing tensors which are still attached to a computation graph which would disallow the backward call to free the intermediate tensors. Could you check if you are storing the loss(es) or outputs in a list or in another tensor?
mfkasim
I would like to save myBatchedTensor(the tensor type that’s produced byfunctorch.vmap) to a file for debugging my application. However, a RuntimeError is raised whenever I calltorch.saveto the BatchedTensor:RuntimeError: Cannot access data pointer of Tensor that doesn't have storage.How can I save aBatchedTensor?
ptrblck
Thanks for the code snippet. I don’t know if there is a public and supported way to save the internal and intermediate tensors, but this code using internal calls should work: def func(x: torch.Tensor) -> torch.Tensor: # some function where we want to debug closely here y = 2 * x print…
ChineseBest
Hi, for a specific machine learning problem, is it possible to me to choose a function, like f(a) to evaluate a, while my loss function is actually generated from g(f(a))? If yes, are there any examples? If not, why I cannot use it? Thanks a lot.
ptrblck
I’m not sure if I have ever seen a use case of an evaluation function f(a) and a loss g(f(a)), but I don’t see why it couldn’t work assuming both methods are differentiable. Note that you are often using a metric function f(a) and a loss g(a) such as the accuracy as the metric function and e.g. cro…
Vinayaka_Hegde
Hi, lets assume thatnum-workers= 8 andbatch_size=2.So, 2*8 = 16 number of batches have to be pre loaded .Now, when the current batch is consumed by a worker andnextis called on the data loader, how many new batches does it fetch? As I understand, 1 new batch is fetched for every consumed batch to maintain the constant ...
ptrblck
This would be the case if the default prefetch_factor of 2 is used but note that the 2 is not coming from the batch_size. You can take a look atthis code snippetto see how the prefetch_factor works.
Vinayaka_Hegde
Hi, I needed to know where the data loader opens the file to read/ access the disk?In the fetch function below, I can see that we get the data. But, I’m not exactly able to find out wheregetitemis defined exactly?image1524×447 46.2 KBOne possible explanation could be thatgetitemcould be used from the custom datasets. E...
ptrblck
The __getitem__ method is defined in your Dataset.
Ragiarc
I’ve read a lot of posts of similar problems, but none of the solutions appear to help me.I’m implementing MADDGP and get the: “Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed)…” error. I have a for loop that iterates through my agents and performs...
ptrblck
In learn_agent you are calling backward on critic_loss and actor_loss, which is inside the for agent_index, agent in enumerate(self.agents) loop. I would probably start by checking if any of the inputs to learn_agent are attached to a computation graph and are used in the loss computation, since th…
J_B_28
Hello,I am making a simple test on MLP to replace the normal weight with a customized residual version weight, I used torch.nn.Parameter to achieve that:for i, lin in enumerate(self.lins[:-1]): if self.residual_weight and lin.weight.size(-1) == args.hidden: print("before", lin.weight.grad) lin.w...
ptrblck
It seems you are recreating the parameter in the forward method without any gradient history so the None .grad attribute is expected in the "after" line of code. The .grad attribute will be populated in the .backward call of the loss. Note however, that your optimizer might be update this paramete…
Rishav_Sapahia
Hi,I come acrossthisblog and couldn’t wrap my head around this calculation.For simple operators, it's feasible to reason about your memory bandwidth directly. For example, an A100 has 1.5 terabytes/second of global memory bandwidth, and can perform 19.5 teraflops/second of compute. So, if you're using 32 bit floats (i....
ptrblck
“400 billion numbers” seems to be picked as an example and the corresponding “20 trillion operations” are then calculated by multiplying the compute of “19.5 teraflops/second” by the data transfer time. Here is a quick example: mem_bandwidth = 1.5 * 1024**4 compute = 19.5 * 1024**4 data = 400 * …
Jun_Park
class NICE(pl.LightningModule):def __init__(self, in_features=784, hidden_features=1000, num_coupling=4): super().__init__() self.save_hyperparameters() self.layers = nn.ModuleList() self.num_coupling = num_coupling for _ in range(self.num_coupling): self.layers.append(nn.Sequential( ...
ptrblck
Check if self.layers were moved to the GPU and if x2 was moved as well since one of these two objects is still stored on the CPU and causes the device mismatch.
Nikola_Andro
I’ve created a module that is a subclass of nn.Module and I cannot add a single attribute to it that is not in the superclass.class net(nn.Module): def __init__(self, input_nc, output_nc, ngf, norm_type = 'batch', act_type='selu', use_dropout=False, n_blocks=6, padding_type='reflect', gpu_ids=[]): assert(n_...
ptrblck
It’s working for me: model = net(1, 1, 1) print(model.initialization_counter) # 0
kayuksel
Hello,I am using torchsort.soft_rank to get ranked indices from the model output logits, and then calculate a loss function for TSP (Travelling Salesman Problem) as follows. (I had previously tried it with argsort but switched to soft_rank as it was not differentiable).points = torch.rand(args.funcd, 2).cuda().requires...
ptrblck
Based on your code you are detaching rank from the computation graph by calling long() on it. Integer types are not differentiable so you would need to stick to floating point types.
HallerPatrick
Hey,I am running into problems I am not able to comprehend. Maybe you can help me out.I am working on a C++ extension and reimplementing some functions for performance.In one of them I am trying to iterate through a 1-dimensional tensor and access each element in it.torch::Tensor unpack(const torch::Tensor &self) { ...
ptrblck
You won’t be able to access device memory on the host via a direct pointer dereference and would either need to move the data back to the host or access the memory in a CUDA kernel.
PedroC
HiI’m facing an issue during training with yolov8. After each epoch the following errror appears several times.lib\site-packages\torch\storage.py", line 520, in _free_weak_refAttributeError: ‘NoneType’ object has no attribute ‘_free_weak_ref’Exception ignored in: <function StorageWeakRef.delat 0x000002448E3708B0>Althou...
ptrblck
The issue seems to be related tothis onewhich is apparently fixed in 1.12.0+, so you might want to update your PyTorch release.
Niraja
I get this error. I don’t understand how to solve this error. How can solve this error.‘’’X_train, X_test, y_age_train, y_age_test, y_gender_train, y_gender_test = train_test_split(X, label_age, label_gender, test_size=0.2)y_age_train = np.array(y_age_train)y_gender_train = np.array(y_gender_train)y_age_test = np.array...
ptrblck
The DataLoader will already return a batch of samples while it seems you are trying to index this batch with the original dataset stored in a numpy array. Check the object type of sample_batches which should be a list containing tensors.
rahulbhalley
Hi,I’m trying to implement convolution transpose 2D for StyleGAN2 that uses constant weight instead of computed one.This constant weight for transpose convolution is required for CoreML.I am using animplementation from this issuein coremltools repo:import torch from torch.nn import functional def conv_transpose_stride...
ptrblck
The warning is raised because you are randomly initializing the module before assigning it’s weights: def conv_transpose_stride2(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor: dilate = torch.nn.ConvTranspose2d(in_channels=128, out_channels=128, kernel_size=1, stride=2, groups=128, bias=False)…
rinkujadhav2013
I’m using C++cudnn_convolution_backwardto implement a custom op. I’m making use of streams in there. My question is that if I callcudnn_convolution_backwardinside a stream context manager, will the cudnn backward pass run on that stream or not?I looked at function’simplementation in C++but couldn’t find anything there....
ptrblck
The cuDNN calls use their cuDNNHandle, which uses the current stream as seenhere.
dsethz
Hey,Question: Is it feasible to install a CUDA-compatible version oftorch(andtorchvision) on a machine without a GPU (and no CUDA installed) (e.g.pip install pip install torch==1.10.1+cu111)?Context: I want to declaretorchas a dependency in my packaging meta-data. The project is a plug-in for a GUI-based software → int...
ptrblck
Yes, I don’t think installing the default pip wheels with the CUDA 11.7 runtime has any side effects besides the size increase (since CUDA libs will be downloaded and stored).
laro
Pooling layers dosn’t have paramaters to learns.So if I build the following network:import torch import torch.nn as nn import torchinfo class PoolModel(nn.Module): def __init__(self): super().__init__() self.GRU1 = nn.GRU(input_size = 2, hidden_size = 32, num_layers = 2, batch_...
ptrblck
You can reuse the same layer and don’t need to initialize a new object for each call.
Abhi_Agarwal
I get the following error when trying to run a demo code for Multi Object Tracking from the following repo :Demo encountering Error · Issue #64 · megvii-research/MOTR · GitHub:Traceback (most recent call last): File "demo.py", line 284, in <module> detector.run() File "demo.py", line 254, in run res = self....
ptrblck
I would recommend to check what exactly is breaking in deformable DETR using newer releases, as neither PyTorch 1.5.1 now CUDA 9.2 will receive any backports of fixes.
pumplerod
I’m rather new to pytorch (and NN architecture in general). While experimenting with my model I see that the various Loss classes for pytorch will accept areductionparameter (none | sum | mean) for example. The differences are rather obvious regarding what will be returned, but I’m curious when it would be useful to ...
ptrblck
You would not only change the loss scale, but also the gradients: # setup model = nn.Linear(10, 10) x = torch.randn(10, 10) y = torch.randn(10, 10) # mean criterion = nn.MSELoss(reduction='mean') out = model(x) loss = criterion(out, y) loss.backward() print(model.weight.grad.abs().sum()) > tensor(…
MagedSaeed
Suppose I have the following tensor:a = torch.Tensor([[1,2,0],[0,-1,0]])I want to remove zeros but keep the dimensions. The results should be:[[1,2],[-1]]Is there an easy way to achieve this?
ptrblck
You could try to use the experimental NestedTensor support as seen here: a = torch.tensor([[1,2,0],[0,-1,0]]) a_list = [a_[a_!=0.] for a_ in a] b = torch.nested.as_nested_tensor(a_list) print(b) # nested_tensor([ # tensor([1, 2]), # tensor([-1]) # ])
ammar_siddiqui
I have a custom custom company dataset which has 14 features and 1 output label having 6 classes [9,12,15,18,21]. I have built a linear model using following definition:class HourPredictor(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(in_features=14, out_features=64) ...
ptrblck
nn.CrossEntropyLoss expects target tensors to contain class indices in the range [0, nb_classes-1] while your target apparently contains an index of 25, which is wrong. Map the targets to [0, nb_classes-1] and it should work. Also, you are explaining to deal with 6 classes but the last output laye…
Hiba_Ahsan
I have a model with a linear layer and I wish to multiply the linear layer weights element-wise with a torch.nn.Parameter at every forward pass. I tried it the the following way but this not compute a gradient for the parameter.class LinearModel(nn.Module):def __init__(self, args): super(LinearModel, self).__init...
ptrblck
Your code should not even be executable and fails with: lin = LinearModel(0) x = torch.randn(1, 10) out = lin(x) # TypeError: cannot assign 'torch.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected) since you are trying to assign a tensor to a parameter. In case you want to m…
1418_Shiina
I’m working with a very simple script with TextCNN. Below is a small working example. WithMAX_LENGTHbeing 64, it works normally. However, whenMAX_LENGTHis changed from 64 to something like 128, the speed becomes extremely slow (at least 100x slower, and seems due to backward) on GPU. There should be something wrong, bu...
ptrblck
You might want to update to the latest release in this case as older releases might have already fixed performance regressions.
Andreas_Binder
Hi all!I look for the most efficient, differentiable way for a 3D PointCloud matrix with shape (1024,3) to find the vector containing the pairwise distances (shape: (1024x1024,1).Currently, I use this:x = torch.ones(1024, 3, requires_grad=True) pdist = nn.PairwiseDistance(p=2, keepdim=True) out = torch.cat ([ pdist(x[...
ptrblck
Your code works for me: x = torch.ones(10, 3, requires_grad=True) pdist = nn.PairwiseDistance(p=2, keepdim=True) out = torch.cat ([ pdist(x[n], x[i]) for n in range (len (x)) for i in range (len (x))]) out.mean().backward() print(x.grad) # tensor([[ 9.3132e-10, 9.3132e-10, 9.3132e-10], # …
DKH
When I generate images using generator network like GAN and save it,it takes too long time and I think that is from IO bottleneck.How can I solve this problem?
ptrblck
Assuming you’ve profiled the code already and narrowed down that it’s indeed an IO bottleneck, you might want to use a faster storage (SSD etc.) to store the data.
pytorch_user1
Suppose I have a tensor that looks like this:a = torch.tensor([ [1. 2.], [3. 4.], [5. 6.], [7. 8.] ])Is there a way to compute the mean of every two row tensors (without overlap) inawithout looping?The expected output tensor would ...
ptrblck
Something like this would work: b = torch.stack([a_.mean(0) for a_ in a.split(2, 0)], 0) print(b) # tensor([[2., 3.], # [6., 7.]]) or using scatter_reduce_: torch.zeros(2, 2).scatter_reduce_(0, torch.tensor([[0, 0], [0, 0], [1, 1], [1, 1]]), a, reduce="mean", include_self=False) or index…
yoelshoshan
Is it possible to do the following (in pytorch 1.x or 2) during training to modify what happens before/after each of the following:During the forward pass, after the activations are store (to be later used in the backward pass), to do operations on them (for example, like transfering them to another device and other th...
ptrblck
Your use case sounds similar to CPU offloading, which usestorch.autograd.graph.saved_tensors_hooksortorch.autograd.graph.save_on_cpuif I’m not mistaken, so you could take a look at these context managers.
ranvirsv
I have a 3d tensor A = [5, 12, 12] and a 2d tensor B = [5, 12]So basically 5 2d tensors and 5 1d tensorsAnd I want to multiply them to get a 2d tensor C = [5, 12]i.e. I want to multiply every 1d tensor with every 2d tensor to get a 1d tensor and then stack them to get a 2d tensor.I did something that I thought would wo...
ptrblck
unsquezeing B should work: A = torch.randn(5, 12, 12) B = torch.randn(5, 12) t_res = [] for i in range(len(A)): t_res.append(B[i].matmul(A[i])) ref = torch.stack(tuple(t_res), dim = 0) out = torch.matmul(B.unsqueeze(1), A) print((out.squeeze(1) - ref).abs().max()) # tensor(0.)
aksj
Hi! I wanted to add to the Pytorch developer facing documentation wiki (Home · pytorch/pytorch Wiki · GitHub) - specifically, I wanted to add more information about what the specific sub-files and sub-folders purpose is as an overview page. How can I get access to create a page on the wiki to do so?Thank you!
ptrblck
Based onthisandthisentry I would suggest to start with a GitHub issue describing your proposal and discuss it there first.
carbocation
In theTorchVision with Batteries Includedeffort, I didn’t notice theblog postor thetorchvision ConvNext documentationindicating the expected input pixel value range before or after transform.Are the pixels expected to be in the 0-1 range? 0-255 range? Something else?
ptrblck
The transforms for ConvNext all reuse ImageClassification as seenherewhich accepts a PIL.Image and will scale it to [0, 1] first and then normalize it as describedhereso I assume the input can be a pure uint8 PIL.Image in [0, 255] assuming you are using the predefined transformation.
Kendos93
Hi there!I wanted to upgrade the torch version I am currently using. I am using a K80 GPU, which, if I understand correctly supports CUDA Driver Version 11.4 and CUDA Runtime Version 11.1. So I am using nvidia/cuda:11.1.1-cudnn8-runtime base image for my docker.I have been using torch==1.11 before, but recently, I have...
ptrblck
K80s are still supported in all of our binaries, since we are building for compute capability 3.7-8.6. You should not expect to see any issues.
fourleafclover
I downloaded the ImageNet 2012 training and validation datasets and use them for training a ResNet-50 model. At first, during training aCUDA device-side assert errorwas triggered and after some web-search, I found its cause: the targets that are provided by my training set dataloader are in the range of [1, 1000], whil...
ptrblck
I guess your root folder contains an unneeded and unexpected folder since the class index mapping will be performed based on the number of folders. torchvision.datasets.ImageNet will initialize its base classherewhich is ImageFolder and which will eventually call into find_classeshereenumerati…
lpex1314
The result obtained after an operation from a tensor obtained from pyTorch model does not have grad_fn and can not backward. I use .clone().detach() to the input and cast tensors of the compute_grad function shown below, So they should be disassociated from the previous model. However, the grad_fn of y is None, and the...
ptrblck
Thanks for the updated code. Autgrad is disabled in backward hooks, so you might want to enable it via with torch.enable_grad():. Once this is done you will run into shape mismatch errors: print(self_dw==dw) RuntimeError: The size of tensor a (10) must match the size of tensor b (50) at non-si…
crownz
I want to use torch.nn.functional.dropout1d for my code. But when I try to use it, python prompts me:AttributeError: module 'torch.nn.functional' has no attribute 'dropout1d'.Then, I go to the source code of functional.py. And I find there is no dropout1d function in the script. However, PyTorch has officially provided...
ptrblck
I would recommend to either uninstall all PyTorch binaries in your current environment and then use the install instructions or to create a new and empty virtual environment and install the latest PyTorch release there.
ElkeAusBerlin
Hey,just to verify. the aarch64 release are not compiled with cuda enabled? Is this true?The installation:python3 -m pip install torch --extra-index-url https://download.pytorch.org/whl/cu102The output:root@localhost:~# python3 -m torch.utils.collect_env Collecting environment information... PyTorch version: 1.10.2 Is ...
ptrblck
Yes, I think that’s the case as the aarch64 builds might have been created for Mac. You could use theNGC containerswhich provide ARM support.
vggls
As per DenseNet official paperhttps://arxiv.org/pdf/1608.06993.pdfthe classification layer starts with a Global Average Pooling (GAP) layer (see Table 1 page 4).I would like to replace the GAP layer with a Flatten layer.However, when I runfrom torchvision import models dnet121 = models.densenet121(pretrained=True) dnet...
ptrblck
Your approach sounds correct and manipulating the forward method in a derived model as well as manipulating the state_dict assuming you’ve changed attribute names should work.
avyavkumar
Hi,I fine-tune a transformer + linear layer on different few-shot data and I then evaluate the model on a test set. However, it looks like the model weights are being initialised differently each time. While ideally they should converge as training converges, I was wondering if it is possible to initialise all linear w...
ptrblck
You could seed to code via torch.manual_seed before creating a new model instance. This would however initialize the global pseudorandom number generator (PRNG) and thus also define the random sequence of every other call into it. Alternatively, you could initialize the model once, save its state_d…