user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
maria.solyanik
I see a lot of implementations of the function:with torch.no_grad(): for layer in mask_model.state_dict(): print(layer) mask_model.state_dict()[layer].data.fill_(const)where the weights are filled with a constant number or a distribution. I have a custom tensor I want to pass. How do I do that? Than...
ptrblck
In your code snippet you are currently hard-coding the shape to (16,1,5,5) which is wrong for most of the layers. Printing the shape of the parameters gives: for layer in cnn.state_dict(): print(cnn.state_dict()[layer].shape) torch.Size([16, 1, 5, 5]) torch.Size([16]) torch.Size([16]) torch.S…
Elad_Cohen
I;m trying to perform gradient descent on a point, but fail in loss.backward() because requires_grad is False.My code:class Net(nn.Module): def __init__(self, p, P1, P2): super(Net, self).__init__() self.p = torch.tensor(p, dtype=torch.float32, requires_grad=True) self.P1 = torch.tensor(P1, ...
ptrblck
I don’t know which shapes you’ve used and how the undefined variables are used, but this code snippet shows that output has a valid grad_fn and also its .requires_grad attribute is True: b = torch.randn(1, 1) c = torch.randn(3, 2) net = Net(b, c, c) outputs = net() print(outputs.grad_fn) # <CatBac…
yellowishlight
Hello everyone,As a follow-up to this questionPyTorch + CUDA 11.4I have installed these Nvidia drivers version 510.60.02 along with Cuda 11.6.I’d like to install Pytorch in a conda virtual environment, and I’ve found in the Pytorch website that we couldn’t choose a stable version that relies on the latest versions of C...
ptrblck
You could build PyTorch from source followingthese instructionsor install the nightly binaries with CUDA11.6 via: pip install torch --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu116
Anonymou5
How can I fix the following error?TypeError Traceback (most recent call last)in ()86 ])87—> 88 train_dataset = data_transforms(train_dataset)89 class_names = train_dataset.classes90 print(class_names)/home/test/.local/lib/python3.6/site-packages/torchvision/transforms/transforms.py inca...
ptrblck
torchvision.transforms expect PIL.Images or tensors as their input, while you are passing a Dataset object to it. Take a look at theData loading tutorialfor an example how to use transformations.
Anikily
I defined a neural network with theinitandforwardfunction,class Model(nn.Module) def __init__(): self.sub1 = Module1 self.sub2 = Module2when i add some layers such as Conv2d into the self.sub1 or self.sub2, i found the performance after one epoch is different!I can’t figure out the reason above, co...
ptrblck
I mean you would have to re-seed the script at the point where you can guarantee the same order or calls into the PRNG. Seeding the PRNG guarantees that the sequence of randomly generated numbers will be equal between runs for the same order of calls into the PRNG. In your case you are changing th…
sebastian-sz
I’m following thetutorial on Custom C++ / CUDA Extensions.In the end there are two implementations of the module:In C++, imported aslltm_cppIn CUDA, imported aslltm_cuda.(Note that althoughlltm_cpualso runs on the GPU, CUDA is still a lot faster)Is there a recommended way to use LLTM (or any other extension) inside my ...
ptrblck
Ah OK, I see. In this case, thisDispatching tutorialmight be useful, which seems to target your use case: The dispatcher is an internal component of PyTorch which is responsible for figuring out what code should actually get run when you call a function like torch::add. This can be nontrivial, b…
HassanAli
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument target in method wrapper_nll_loss_forward)My model and inputs both are already on gpu. But I am still getting this error.device = torch.device('cuda' if torch.cuda.is_availab...
ptrblck
I cannot execute the code as parts are missing (e.g. GradientReversalFn as well as the input shapes). However, based on your code snippet you are neither passing y_s_domain nor y_t_domain to the device, which might create the issue.
Emil
We have a model in which one of the layers is used to generate logits for a OneHotCategorical distribution. When autocast is disabled the code seems to work, but when we enable autocast it will run for a seemingly random amount of iterations and then fail with the following error:Traceback (most recent call last): Fi...
ptrblck
I don’t know if casting the logits to float32 would help (you could try it) or if it’s already done, but the values are already “invalid”. Do you know what “invalid” means in this case and which values are unexpected in state.logit?
hohohihi
Hi, i am making custom activation function here.I want to pass a variable(which is pre-defined outside of function) to the backward function.Here is the code.But it saysAttributeError: ‘custom_tanh_variableBackward’ object has no attribute ‘variable’So, i don’t know what to do.Help me.self.activation = custom_tanh_vari...
ptrblck
autograd.Functions are stateless and cannot register buffers. If you want to register self.val as a buffer or parameter, do so in the nn.Module (i.e. Module_custom_tanh). In your custom_tanh pass all needed tensors to the forward and use ctx.save_for_backward if you need specific tensors in the ba…
seitzy
When I try and run my program I get the error: raise AssertionError(“Torch not compiled with CUDA enabled”) AssertionError: Torch not compiled with CUDA enabled.nvcc --version returns:nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Sun_Mar_21_19:24:09_Pacific_Daylight_Time_2021...
ptrblck
The reported CUDA version via nvidia-smi depends on the driver and does not necessarily match the installed CUDA toolkit including the compiler. I guess the CPU-only release was installed or you have multiple installations in your current conda environment. Check the install logs and make sure th…
Cornelius_Denninger
Hello,I’m trying to multiply two tensors to mask out certain values.a = torch.tensor([[1,2],[3,4]]) b = torch.tensor([[1,0],[0,1]]) c = a*bWhere c should return tensor([[1, 0],[0, 4]]). This works perfectly in my python notebook.However, in my train loop, I’m multiplying X_pos * y which outputs the X_pos tensor rather ...
ptrblck
Your current screenshot shows the expected output since the values at y where x contains ones are also ones.
YuhskeHujisaki
When building CNN with pytorchRuntimeError: Expected 2 to 3 dimensions, but got 4-dimensional tensor for argument # 1’self’ (while checking arguments for max_pool1d)What does the error mean?class Net (nn.Module):definit __ (self):super (Net, self) .init__ ()self.conv1 = nn.Conv1d (1, 60, kernel_size = (1, 15), stride =...
ptrblck
nn.MaxPool1d expect a 3-dimensional tensor in the shape [batch_size, channels, seq_len] while you are apparently passing a 4-dimensional tensor to this layer.
e-cockroach
Hi guys,I was trying to implement a paper where the input dimensions are meant to be a tensor of size ([1, 3, 224, 224]). My current image size is (512, 512, 3).How do I resize and convert in order to input to the model?Any help will be much appreciated. Thanks!
ptrblck
First you would have to permute the dimensions to create a channels-first tensor from the channels-last input and could then use torchvision.transforms.Resize to resize the tensor to the desired 224x224 spatial size: input = torch.randn(512, 512, 3) x = input.permute(2, 0, 1) print(x.shape) # torch…
Aaron_Tseng
I have 3 kinds of spatial data to use as inputs. I want to simulate them as image data with 3 channels. Those data are all 5x35 size with 5000 samples.for i in range(5000): in_x.append([x[i].reshape(35,5), delta[i].reshape(35,5), np.pad(z[i], (0,170),'wrap').reshape(35,5)])The three types of data are x, delta and z...
ptrblck
I don’t know how you are exactly creating the Dataset or DataLoader but this small example shows that the batch size is used as expected: dataset = torch.utils.data.TensorDataset(torch.randn(5000, 35, 5), torch.randn(5000, 35, 5), torch.randn(5000, 35, 5)) loader = torch.utils.data.DataLoader(datas…
mmazuecos
I’ve come across a problem when using PackedSequences and LSTMs:Traceback (most recent call last): File "thing.py", line 23, in <module> ...
ptrblck
Your Ampere GPUs would need to use CUDA11 while it seems you have installed the CUDA10 binaries with cuDNN7.6.5, which is expected to fail. Install the latest pip wheels or conda binaries with CUDA11.3 (or 11.5) and check if you are still hitting the issue.
Z_Huang
In the tutorial (Transfer Learning for Computer Vision Tutorial — PyTorch Tutorials 1.11.0+cu102 documentation), why do we set set_grad_enabled when we predict in train? When phase == “val”, the grad is disabled. My question is does the statement “_, preds = torch.max(outputs, 1)” generate different results mathematica...
ptrblck
You would disable the gradient computation during the validation phase to save memory by avoiding storing the intermediate forward activations, which would be needed to compute the gradients. A more aggressive optimization might be achieved via with torch.inference_mode() which would disable the vi…
tjoseph
Hi,can someone explain if this behavior is intended and if so, why and what the solution would be to get the same behavior with scripting as without:import torch @torch.jit.script def scripted_bar(x): with torch.no_grad(): y = x * 2 z = 2 * x + y print("scripted_bar", x.requires_grad, y.requires_...
ptrblck
This behavior seems indeed unexpected. Could you create aGitHub issuewith this minimal code snippet, please?
HitM
Hello,I’m not experienced in PyTorch very well and perhaps asking a weird question.I’m running my PyTorch script in a docker container and I’m using GPU that has 48 GB.Although it has a larger capacity, somehow PyTorch is only using smaller than 10GiB and causing the “CUDA out of memory” error.Is there any method to le...
ptrblck
No, docker containers are not limiting the GPU resources (there might be options to do so, but I’m unaware of these). As you can see in the output of nvidia-smi 4 processes are using the device where the Python scripts are taking the majority of the GPU memory so the OOM error would be expected. T…
carologawa
I am creating designing a Convolutional Neural Network to predict labels of the images, using CIFAR10.num_workers = 2 # how many samples per batch to load BATCH_SIZE = 4 # percentage of training set to use as validation valid_size = 0.2 # convert data to a normalized torch.FloatTensor transform = transforms.Compose([t...
ptrblck
Usually these shape mismatches are caused by a wrong view operation, which would change the batch size. In your code you are using: x = x.view(-1, 16 * 5 * 5) which might indeed change the size of dim0. Use x = x.view(x.size(0), -1) instead and check for shape mismatches in self.fc1. If a shap…
Sajid_Ahmed
(base) sajid@sajid-pc:~/Desktop/dctts-pytorch$ python3 main.py --action train --module Text2Meltrain: Text to Melloop 0▝[1/60] |gs: 0, mels: 0.384276, bd1: 0.694295, atten: 0.783801, scale: 99.999000| [0.0% eta ETA unknown]Traceback (most recent call last):File “/home/sajid/Desktop/dctts-pytorch/main.py”, line 62, inma...
ptrblck
The issue seems to be raised by numpy in: im = ax.imshow(np.flip(spectrum, 0), cmap=“jet”, aspect=0.2 * spectrum.shape[1] / spectrum.shape[0]) > ValueError: step must be greater than zero so maybe you are passing a non-contiguous tensor to this method. Call spectrum.numpy() or spectrum.contiguou(…
Anwarvic
Right now, I’m trying to train a model using a weighted sum of two loss functions (loss1andloss2) of the same type; as shown below:alpha = 0.5 for input, labels in data_loader_train: out1, out2 = model(input) loss1 = criterion(out1, labels[:, 0]) loss2 = criterion(out2, labels[:, 1]) loss = alpha * loss...
ptrblck
I cannot reproduce the issue and the loss weighting works as expected: class MyModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10, 10) self.fc2 = nn.Linear(10, 10) def forward(self, x): out1 = self.fc1(x) out2 = self.fc2…
Charan0
I wanted to perform semantic segmentation using PyTorch. There are a total of 103 different classes in the dataset and the targets are RGB images with only theRchannel containing the labels. I was usingnn.CrossEntropyLossas my loss function. For sanity I wanted to check if using it has the expected behaviourI pick a ra...
ptrblck
Based on the target shape and the dtype (target is a LongTensor) the target is expected to contain class indices and should not be one-hot encoded. Could you check the min/max values of target.to(torch.long)? Also nn.CrossEntropyLoss expects logits in the model output so you would have to fill outp…
cerebrou
We have a DataLoader that is using SubsetRandomSampler. Is it possible to tell the number of datapoints in the loader (which are sampled) from the DataLoader?
ptrblck
You can print the len of the internal .sampler as seen here: N = 100 dataset = torch.utils.data.TensorDataset(torch.randn(N, 1)) sampler = torch.utils.data.sampler.SubsetRandomSampler(indices=torch.arange(N//2)) loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=7) print(len…
tjoseph
Hi,is there a way (e.g. a ContextManager) to find cpu-gpu synchronization points in my code?#Best,Tim
ptrblck
You could usetorch.cuda.set_sync_debug_mode().
111114
Hello I’m trying mixed precision training with pretrained model.But when I load pretrained_model[1], nn.Parameter module[2] in WavLM(pretrained model) makes trouble.### Error Message File "/data/leecho/xi-stt/xi-stt/model/WavLM.py", line 286, in apply_mask x[mask_indices] = self.mask_emb RuntimeError: Index put r...
ptrblck
It seems you are trying to call index_put_ with mixed dtypes, which creates the error. Cast e.g. the value tensor to the source dtype and it should work: lin = nn.Linear(1, 1).cuda() x = torch.randn(1, 1).cuda() with torch.cuda.amp.autocast(): out = lin(x) print(out.dtype) # torch.float16…
Jeet
class Parent(nn.Module): def __init__(self,in_features,z_dim, img_dim): super().__init__() self.my_child1 = Child1 (z_dim, img_dim) self.my_child2 = Child2 (in_features) def forward(self,input): input=self.my_child1(input) input=self.my_child2(input) r...
ptrblck
All parameters which were used in the forward pass will get the corresponding gradient accumulated into their .grad attribute. In your example my_child1 and my_child2 are used and thus their parameters will get the gradients. You could use your custom forwardX method, but note that you would bre…
mba
I am kind of newbie to pytorch. I am trying to change the head of transformer which was:lm_head = nn.Linear(768, 32128)For this part, the model runs without error, However when I tried to add another fully connected layer using the Sequential function like:lm_head = nn.Sequential(nn.Linear(768, 32128),nn.ReLU,nn.Linear...
ptrblck
As the error message explains, the out_features of the first linear layer in the nn.Sequential block do not match the in_features of the second linear layer. A fix would be: lm_head = nn.Sequential( nn.Linear(768, 32128), nn.ReLU, nn.Linear(32128, 32128) )
witha
Hi,I am currently running on google colab. I have saved my running model to a directory in a drive. but when i reload it it gives the following error (saving the model does not generate any error).Traceback (most recent call last):File “multi_task_game_v3.py”, line 215, inmain()File “multi_task_game_v3.py”, line 205, i...
ptrblck
Your GPU might already be using device memory and loading the stored state_dict could cause the out of memory issue, so you might need to restart the notebook and load the state_dict at the beginning of it.
mkcho
Hi there!I downloaded the source of PyTorch and built the code on my own, but I can’t find the location of resulting object file. I really wanted to know the location of object file of PyTorch!Thanks!
ptrblck
The location depends on the actual build command (as you can install it “locally” or into an environment etc.) and you can find it via print(torch.__path__).
divinho
This is from the documentation on amp:Automatic Mixed Precision examples — PyTorch 1.11.0 documentationThis is talking about the scenario when one has multiple tensors that one is calling backwards on correct?Not the scenario where one adds the different losses together into onetotal_lossand calls backwards on that rig...
ptrblck
Yes, your understanding is correct. You don’t need to use separate scalers if you are accumulating both losses first.
hohohihi
Hi, there.I want to change the backward behavior of tanh.So, i have to touch the source of torch.But i don’t know where my downloaded torch code exist.So,where is my torch source code exist in my computer? (I am using anaconda)Where is the directory of tanh’s backward function?do i have to do something after changing t...
ptrblck
You won’t be able to change the pre-built binaries so would need to build PyTorch from source as describedhere. The easier approach to change the backward method of a specific operation would be to implement a custom autograd.Function and write the backward method manually as described e.g.here.
Samuele_Bolotta
I am trying to create a general feedforward net with CNN and FNN layers. What I am trying to do is: depending on the parameters that are passed in the class, then I want to create fully connected layers according to how config is specified.Would this be a good way of doing it inside a class EncodingNetwork(nn.Module)?f...
ptrblck
Yes, creating the modules in the __init__ method sounds like the right approach. Make sure to use nn.ModuleList for layers to properly register these modules or wrap the list into e.g nn.Sequential if this fits your use case. nn.Linear doesn’t have a kernel_regularizer argument so I’m unsure where…
Crisostomi
Hello,I am working on Semantic Role Labeling, I have tensors which are the result of concatenating the BERT embedding of a word and a bit which indicates where the predicate is in the sentence, so I have tensors of shape (batch_size, sequence_len, bert_embedding+1). I pass these to a dropout layer but the fact that the...
ptrblck
Yes, this is done during training with a scale factor of 1/(1-p) as seen here: drop = nn.Dropout(p=0.8) x = torch.ones(10) out = drop(x) print(out) > tensor([0., 0., 0., 0., 5., 5., 0., 0., 0., 0.]) Thedropout paperexplains the scaling in section 10.
Vidit_Goel
I am using a torchscript model and noticed that it occupies different memory on GPU for different versions of PyTorch. The torchscript model was created using torch version 1.8.0| Torch version | Memory | |---------------|---------| | 1.8.0 | 2879 MB | | 1.9.1 | 3383 MB |Is this an expected behavior? S...
ptrblck
No, the memory consumption on the GPU depend on various things: the largest portion would probably come from CUDA libraries (the driver, cuDNN, etc.) each PyTorch kernel will be loaded into the CUDA context, which could also increase it assuming the number of kernels grew between 1.8.0 and 1.9.0 c…
sebastian-sz
I’m following theofficial tutorialon writing custom CUDA extension I’m noticing and example CUDA kernel:template <typename scalar_t> __global__ void lltm_cuda_forward_kernel( const scalar_t* __restrict__ gates, const scalar_t* __restrict__ old_cell, scalar_t* __restrict__ new_h, scalar_t* __restrict__ n...
ptrblck
It depends on your use case and if you are writing a “monolithic kernel” or a “grid-stride loop”.This tutorialexplains it using the saxpy example.
seer_mer
Will there be any performance/memory/other difference if I do the following to create a model:using nested modules (for example, if I make Conv-BN-ReLU a module, which is nested in a Residual Module, which is nested in a stage module, which is nested in a body module, which is nested in the module of the whole model) v...
ptrblck
All your points seem to be concerned about the Python call overhead by nesting objects. While I think you might see more overhead in the actual function calls, I would claim they might be tiny for “real” workloads where you are able to keep the GPU busy and would thus probably stick to the “cleanes…
TeDataPro
Hey !Here’s a description of my problem:I want to create a Custom Loss to be able to take into account only some predictions in the loss calculation. But I have a problem with the backward function which doesn’t work and prints:RuntimeError: element 0 of tensors does not require grad and does not have a grad_fnHere is ...
ptrblck
In your custom loss function you are detaching output from the computation graph as you are using numpy operations and are then re-creating the tensors. You would need to either use PyTorch tensors in all operations so that Autograd can track these ops or you could alternatively implement a custom a…
babuya
In python, if I want to realize a custom ops which is extended by autograd.Function, I may code as following. The idx’s grad is not need for updating.class MyOps(torch.autograd.Function): @staticmethod def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: # some operations, and o...
ptrblck
I think returning a torch::autograd::variable_list object with empty tensors for the None equivalents could work as seen inthis example.
Felipe_Mello
Hi,I tried to google the answer, but couldn’t find it.i) Is each worker in the the dataloader calling __ getitem __withinthe same batch, and then collating it,ii) or is each worker loading and collating each batchindependently?Imagine this scenario:16 batches per epoch, each with 100 examples.24 workers available.Will ...
ptrblck
The second case is currently used, i.e. each worker creates a full batch and pushes it to the queue. Once it’s ready it’ll start creating the new batch until prefetch_factor*num_workers batches are available.
martin_xiao
Hello,In order to improve the sampling efficiency I decide to use multiprocessing to do the sampling with CPU(model prediction also with cpu) and train the model with single a process by GPU.image1168×409 41 KBThe multiple rollout workers code as followed:def multi_sampling(_env): # _env.actor's and _env.critic's n...
ptrblck
Sorry I don’t fully understand the use case and e.g. don’t know what the to() operation in “Update Weights” refers to. The usual use case would be to use a DataLoader with multiple workers for the data loading and push the data to the GPU once it’s ready. Based on your issue I guess you might be r…
JansonYoung
My computer configures GTX1080ti, PyTorch =1.0. The model can work. After changing the GPU to GTX3070ti, I run “torch.cuda.is_available()”, and it return True. But, the running code stops to “model = model.cuda()” for a long time, and not possible to keep going.I have updated the GPU driver to 497.29, CUDA to 10.0, and...
ptrblck
Your Ampere GPU needs CUDA11, so install the latest binaries with the 11.3 or 11.5 CUDA runtime.
mvillanuevaaylagas
Hello, I’m trying to compute a batched version of KNN. At the moment I’m looping over scipy’s cKDTree.I saw that PyTorch geometric has a GPU implementation ofKNN. However, I find that the documentation is not very clear thexandyinput variables are matrices of points times features. Now, if I run the example codex = tor...
ptrblck
Ah OK, thanks for the explanation. If I thus want to combine both examples into a single operation I could just assign my new example to timestep 1? This output seems to show that it’s working fine: x = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1], [-1, 0], [1, 0], [1, -1], [-1, 0]]) batch_x …
Jacfger
I was training a model using DDP and I wished to train multiple instance with some difference in configuration. However, when I tried to checkout to another branch, the running instance suddenly report an error and stopped. The error also only existed in the newly checkout branch, indicating the process actually read t...
ptrblck
The behavior seems to depend on the OS or rather the method to fork or spawn the processes as describedhere.
nalinbot
I have trained a multi-class segmentation model on some data and my data was in the form (4, 320, 320)/(4, 512, 512) which denotes 4 classes with each (1, 512, 512) being a binary segmentation of the one class which is how I’m pretty sure it works, if not please correct me. I got my predictions back and everything look...
ptrblck
You could either pick a colormap in plt.imshow which would work for you or you could map each class index to an RGB value before visualizing the output.
ai007
I am trying to map mfcc to images but I can’t find out what the correct parameters should be for my nn.Linear and Conv2d layers.This is the error I get:“RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x196608 and 25565904x26)”The images and mfcc features which are in npy format are pre loaded in the facedata...
ptrblck
It seems the import is failing so make sure model is actually a script which can be imported. If you get stuck, just copy/paste the model definition into your current script.
feiyuhuahuo
My code in a network forward:print(feat.shape) atten = F.avg_pool2d(feat, feat.size()[2:]) lll = F.adaptive_avg_pool2d(feat, (1, 1)) print(atten.shape) print(lll.shape) print((atten-lll).max()) print((atten-lll).min())And the result:The outputs have the same sha...
ptrblck
You are most likely running into small numerical errors due to the limited floating point precision caused by e.g. a different order of operations in these layers.
Wookie
Hi!I have been struggling with this code for a couple days. I couldn’t find many similar posts but the one’s I found have attributed to the code below.I have 3 inputs that are three independent signals of a sensor. The rows represent a signal and the columns are values of that signal. On another file I have the target ...
ptrblck
The expected input shape for linear layers is [batch_size, *, nb_features] where * denotes additional dimensions (which we will skip for now as I don’t think it would fit your use case). No, don’t worry.Coming from the signal processing domain I’ve spent sme time with MATLAB. I’m unsure how to…
MaKaNu
I have builded a model of darknet using alot of nn.Sequential modules. I choosed to do so, because I was thinking: putting the Sequential parts together in my nn.Module initializer method benefits later speed instead iterating over a nn.ModuleList in the forward method.This works fine and I tested a dozen times the out...
ptrblck
No, I doubt you would see any difference between using nn.Sequential and e.g. calling the modules line-by-line manually. If you are concerned about the launch overhead for each CUDA kernel, checkCUDA graphsbut note the limitations of using it.
J2M2
Hi!I have a unique unordered tensor A with shape (batch, N) and another unique tensor B (batch, n) where N >= n.I am trying to find the indexes of A that matches in B but for each batch. (batch/row wise)Examplea=torch.tensor([[0,1,2,3,4,5,6,7,8,9],[6,11,1,3,14,15,9,17,18,19]]) b = torch.tensor([[2,4,6,7],[3,9,15,19]])...
ptrblck
It’s possible but you would need to: compare each value of a against b which could be faster but would need to store the intermediate results so would need more memory you would then need to make sure that the number of matches for each “row” is equal in order to be able to create a single output …
qubehead
Hello, I have a problem and I cannot figure out what I am doing wrong. I want to get samples from a pytorch DataLoader and store them in a buffer, so that I can use them for training later. The normal way to do a train-loop (without the buffer) would look something like this:for epoch in range(epochs): for data, targ...
ptrblck
The main difference would be that the second approach would disable the data augmentation. I.e. if you are using random transformations in your Dataset, the first approach would apply them on each sample on-the-fly during the data loading and processing in for data, target in data_loader. In your …
stevethesteve
Ifais some tensor andbis a tensor or a number, is there a difference betweentorch.eq(a, b)anda == b?If not, why does Pytorch API specify thetorch.eqmethod?Should I avoid using the==operator and usetorch.eqinstead?
ptrblck
I think both approaches should yield the same result: a = torch.arange(10) b = 2 print(a == b) print(torch.eq(a, b)) b = torch.arange(10) print(a == b) print(torch.eq(a, b)) I guess: convenience if you prefer to use the explicit torch.* methods, e.g. such as torch.add instead of + to allow us…
jayz
Hey,I am currently reading the resnet paper, and I noticed their residual blocks always contain two convolutions. I see the first convolution is used to map the input channels to the desired channel number of the residual block (if there is a change in channel dimensions between subsequent residual blocks), while the s...
ptrblck
Right, if you are only concerned about getting the shape right a single layer would do it. However, the actual processing of multiple layers with non-linearities between them would not be the same, so you might lose the actual training properties of these blocks.
Mona_Jalal
I have created a subset of my data (a bit smaller) and now I have negative values in my std and mean tensors:This subset is designed in a way that I would have same number of positive and negative classes.train mean and std: tensor([0.0050, 0.0225, 0.0250]) tensor([0.9833, 0.9977, 0.9932]) val mean and std: tensor([-0....
ptrblck
The idea is that the val and test sets are “new” or “unseen” data. If you are using these splits to calculate any stats or use them in any other way, they are not new anymore as you are leaking the data information into your training. This is also why a validation and test set is needed. Even th…
ageryw
I have to train two models sequentially, where the loss of one model will somehow be used by the other model. Part of the code is as follows:# model1 pred1 = model1(data) loss1 = loss_fn1(pred1, targets) optimizer1.zero_grad() loss1.backward() optimizer1.step() # model2 pred2 = model2(data) loss2 ...
ptrblck
In your current code snippet the kl_loss is created using pred1 and pred2 and will thus try to calculate the gradients for both models. Since loss1.backward() and optimizer1.step() were already performed, this is invalid and will raise the errors. Assuming you don’t want to train model1 anymore, y…
Gaurav_Sharma
Hi there!I am trying to run a simple CNN2LSTM model and facing this error:RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn.The strange part is that the current model is a simpler version of my previous model which worked absolutely fine.To solve this error, I have tried setting “requ...
ptrblck
The point of initialization wouldn’t matter since you are currently not using outputs at all. I assume you would like to assign some computed values to it at one point, but this code seems to be missing.
cbd
I have custom loss function. If loss is positive i do backward() as mentioned below in code and after validation free the space using “torch.cuda.empty_cache()”The code execute fine till the loss is positive. When loss is negative it doesn’t execute Training part mentioned in code as per logic but when it starts traini...
ptrblck
self.backward_G() will compute the gradients and free the intermediate forward activations, which would reduce the memory usage. I assume you are not calling backward if the loss is negative and might thus keep the computation graph (with the intermediate activations) alive, which could raise the OO…
ljeonjko
Hello!I have trained a generator model as defined by:class Downscale(nn.Module): def __init__(self, in_size, out_size, normalize = True, dropout = 0.0): super(Downscale, self).__init__() model = [nn.Conv2d( in_size, out_size, kernel_size = 4, ...
ptrblck
Based on your code snippet the Generator.__init__ method doesn’t initialize any modules and just stores the features and number of channels. I thus guess that you’ve either forgotten to call self.build() in __init__ or model.build() to actually initialize the modules.
HaiNam
I got the following error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.HalfTensor [20, 75, 52, 52]], which is output 0 of ReluBackward0, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that f...
ptrblck
You are manipulating the predict tensor inplace here: predict[...,1:3] = self.sigmoid(predict[...,1:3].clone()) which is disallowed. You could create a new clone and change it inplace instead: new_predict = predict.clone() new_predict[...,1:3] = self.sigmoid(predict[...,1:3].clone()) or use e.g…
mahmoodn
HiHow can I find whether pytorch has been built with CUDA/CuDNN support? Is there any log file about that?
ptrblck
You could use print(torch.__config__.show()) to see the shipped libraries or alternatively something like: print(torch.cuda.is_available()) print(torch.version.cuda) print(torch.backends.cudnn.version()) would also work.
Tianyi_Zhou1
Hi!I am now doing a project about translation and using torch.nn.CrossEntropyLoss with torch version == 1.11.0.CrossEntropyLoss — PyTorch 1.11.0 documentationRefering to the document, I can use logits for the target instead of class indices to get the loss, so that the target/label shape will be (batchsize*sentenceleng...
ptrblck
I don’t think your second approach would avoid the OOM issue and would force PyTorch to allocate new memory in the next iteration. To avoid keeping the gradients around you could use optimizer.zero_grad(set_to_none=True) which could help.
Heberht_Dias
class Network(nn.Module):def __init__(self,): super(Network, self).__init__() self.conv1 = qnn.QuantConv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, weight_bit_width=3, padding=1) self.bn1 = nn.BatchNorm2d(12) self.quantReLU1 = qnn.QuantReLU(bit_width=3) self.conv2 = qnn.QuantCon...
ptrblck
You can add a print statement directly after its usage: output = self.quantReLU3(self.bn3(self.conv3(output))) print(output) ...
Qiyao_Wei
Is there examples of using the parameter is_grads_batched intorch.autograd.grad? Thanks!
ptrblck
If I understand the usage correctly, you could avoid writing a for loop as internally vmap will be used: x = torch.randn(2, 2, requires_grad=True) # Scalar outputs out = x.sum() # Size([]) batched_grad = torch.arange(3) # Size([3]) grad, = torch.autograd.grad(out, (x,), (batched_grad,), is_grads…
Adam007
Hi I have image with values from 0 to 255. What is best way to normalize this image to -1,1 ?Thank you
ptrblck
You can just undo the normalization: x = torch.randint(0, 256, (100,)).float() print(x.min(), x.max()) # > tensor(0.) tensor(255.) y = 2 * x / 255. - 1 print(y.min(), y.max()) # > tensor(-1.) tensor(1.) # undo normalization z = (y + 1) / 2 * 255. print(z.min(), z.max()) # > tensor(0.) tensor(255.)…
kuzand
I was checking the different transforms invision/transforms.py at main · pytorch/vision · GitHubin order to see how to implement my custom transform. Theget_params()method of different transform classes are marked asstaticmethod. What is the reason for this?
ptrblck
The @staticmethod decorator allows you to get the parameters without creating an object, which might be more convenient in some use cases. You could still call the get_params method on the object directly: transform = transforms.RandomCrop(size=(10, 10)) x = torch.randn(1, 3, 24, 24) params = tran…
ken012git
I tried to profile the model by using the hook, but I found the behavior is not expected when I increase the batch size for batch normalization layers. Here is the minimal reproducible example:import copy import torch from torch import nn from torchvision.models.mobilenetv3 import mobilenet_v3_small def register_bn_...
ptrblck
I haven’t checked what your code is exactly doing, but you are dealing with values larger than 2**24 in e.g. m.counter in float32 which will start rounding towards powers of 2. Checkthis Wikipedia articleto see the precision limits. E.g. using the larger batch size shows m.counter as 25233408, w…
Ch-rode
I’m stacked with this model, every day errors came to my code! Anyway I’m trying to implement a Bert Classifier to discriminate between 2 sequences classes (BINARY CLASSIFICATION), with AX hyperparameters tuning.This is all my code implemented anticipated by a sample of my datasets ( I have 3 csv, train-test-val). Than...
ptrblck
I think you are hittingthis issueagain. Based on your last statement in the linked topic, I guess your output has the shape [batch size=2, seq_len=512, nb_classes=1024] while the target only contains the class indices for [batch_size=2]. This doesn’t work, since: the target should contain valu…
maggette
Hi,Sorry for the vague question.I have about a dozend implementations of that in numpy. So I am not looking for “one possible way to do it”.But I know that I found somewhere on the internet ( I think it was either here or on StackOverflow) a beautiful “one liner” solution in PyTorch and thought “awesome, will try that ...
ptrblck
Maybe you are thinking about unfold: x = torch.arange(10) y = x.unfold(dimension=0, size=3, step=1) print(y) # tensor([[0, 1, 2], # [1, 2, 3], # [2, 3, 4], # [3, 4, 5], # [4, 5, 6], # [5, 6, 7], # [6, 7, 8], # [7, 8, 9]]) or with@KFrank’s va…
jayz
Hey,when we have a kernel with size that would result in an “odd” padding, which side would the larger padding standardly be applied?The simplest case is kernel_size = 2. Consider a 1D input (X Y Z) of length 3. If we apply same padding, we would have to add a pad on either the left or the right side of the input:P X Y...
ptrblck
Let’s perform your experiment with some pre-defined kernel values as [[[0., 1.]]] which would use the “right” pixel value of the current patch: conv = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=2, stride=1, padding='same', bias=False) with torch.no_grad(): conv.weight.copy_(torch.tens…
ken012git
Hi,I am tryingregister_forward_hookandregister_full_backward_hookforInvertedResidualblock. However, I got an error caused by residual connectionresult += inputwith a message:File "/home/usr/anaconda3/envs/pytorch-1.10-nightly/lib/python3.8/site-packages/torchvision/models/mobilenetv3.py", line 127, in forward resul...
ptrblck
I think your workaround of using the out-of-place addition is correct. Since your backward hook expects to work with the unmodified output activation, manipulating it inplace could easily break your hooks as the values would be invalid.
Shen
Hi,I’m trying to train a ResNet50 for ImageNet dataset, but observed a fluctuation of GPU utilization between 32% and 89% (measured vianvidia-smi). I’m using the provided network at this point:model = torchvision.models.resnet50(pretrained=True) model.type(torch.cuda.FloatTensor)However, when I switched to VGG network,...
ptrblck
Are you profiling your custom implementation? If so, I would guess you are not calling into cuDNN but are using maybe cublas? You could check the kernel section to see which kernels are executed etc. to see which part of your implementation needs how long. Generally,this presentationorthis repos…
Sherlock_Wan
Hi! I am a beginner in PyTorch. I have a folder containing thousands of 3-d segmented images (H x W x D x C) in .mat (Matlab files). I have searched for similar topics on PyTorch forum (e.g.,this link), but my dataloader remains not workable. Specifically, elapsed time is too long when I call ‘real_batch = next(iter(da...
ptrblck
Could you set num_workers=0 and rerun the test, which could hopefully give a better error message, please?
Alexander_Soare
According to the PyTorchdocumentationtorch.cuda.synchronize“Waits for all kernels in all streams on a CUDA device to complete.”. Questions:Should this say “Waits for all kernels in all streamsinitiated by this Python sessionon a CUDA device to complete”? In other words, if Python session A is running CUDA operations, a...
ptrblck
Work of independent processes should be serialized (CUDA MPS might be the exception). Process A doesn’t know anything about process B, so a synchronize() (or cudaDeviceSynchronize) call would synchronize the work of the current process. However, if process B uses the GPU for a display output etc. …
h4ns
Hello everyone,I am searching for way to make this assignment to a slice of a tensor work, without copying data (and also understand why my version doesn’t work):import torch indices = torch.tensor([2,0]) lengths_new = torch.tensor([1,2]) lengths_old = torch.tensor([2,2,3]) tensor_new = torch.tensor([[3,1,2,4], [2,1,3...
ptrblck
If I understand your code correctly you are currently working on a copy of the data since you are indexing the tensor sequentially. This should work and yields the same results for new and result: indices = torch.tensor([2,0]) lengths_new = torch.tensor([1,2]) lengths_old = torch.tensor([2,2,3]) t…
cbd
I am little bit confuse with the data loader and number of workers. Lets say I have 100 images in my dataset and used shuffle=True. I run the code for 20 epochs. In each epoch it randomly shuffle the 100 images.(1) If i run the code again for 20 epochs, how to make it follows the same shuffle as previous run?(2) Lets t...
ptrblck
You can run code 1 right before starting the training in code 2, if you’ve set the global seed in both use cases at least once or if your model does not contain any random ops.
dachun
I have installed torch from whl, downloads frompytorch.orgpip install torch-1.10.2+cu111-cp37-cp37m-linux_x86_64.whlBut when I check the torch cuda version bytorch.version.cudait returns10.2. But I install cu111 version. What’s wrong?
ptrblck
Most likely you have multiple PyTorch installations in your current environment. Uninstall them all and reinstall the right wheel or create a new virtual environment where you could install the desired wheel.
dinatrina
Hi,config:torch 1.10.2, CUDA 11.3, Python 3.8.10after one iteration turning ontorch.autograd.set_detect_anomaly(True)I get the following error:[W python_anomaly_mode.cpp:104] Warning: Error detected in MulBackward0. Traceback of forward call that caused the error:File “/home/ddd/work/ASR/NeuroPhysModel/reproduceProblem...
ptrblck
The error seems to be raised since you are creating non-leaf tensors in the __init__ from self.a and self.l which will keep their gradient history. I’m not familiar with your use case, but if you want to train self.a and self.l while using a processed “form” of them, you could recreate them in the f…
lima
I have a dataset class function:class MYDataset(Dataset): def __init__(self, path): df = read_csv(path, header=None, delimiter=r"\s+") df = df.iloc[:, 1:-1].values self.X = df[:, 1:] self.y = df[:, 0] self.y = self.y.reshape((len(self.y), 1)) def __len__(self): r...
ptrblck
Something like this should work: train_dataset = MyDataset(transform=train_transform) val_dataset = MyDataset(transform=val_transform) test_dataset = MyDataset(transform=test_transform) # you can use e.g. train_test_split from sklearn here to create the indices train_idx, val_idx, test_idx = creat…
nullgeppetto
I modifynn.DataParallelso as it handles a modified network (a GenForce GAN generator in my case), as follows:class DataParallelPassthrough(nn.DataParallel): def __getattr__(self, name): try: return super(DataParallelPassthrough, self).__getattr__(name) except AttributeError: ...
ptrblck
I see the expected change in the current nightly, so I guess you are still looking into a wrong installation: root@4031504dc1c7:/workspace# pip install --pre torch -f https://download.pytorch.org/whl/nightly/cu113/torch_nightly.html Looking in links: https://download.pytorch.org/whl/nightly/cu113/t…
Bruno_Oliveira
Hey everyone.I’m trying to modify fasterrcnn_mobilenet_v3_large_320_fpn to train it on a custom 5 classes dataset. The problem is I’m having issues using this modified model.image1721×808 121 KBThis raises the error: TypeError: forward() takes 2 positional arguments but 3 were givenI have read that this is not a sequen...
ptrblck
I think the easier approach would be to specify the num_classes during the model instantiation and to use a pretrained backbone if needed: model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn( pretrained=False, num_classes=5, pretrained_backbone=True)
Sam_Lerman
I want to:Iterate through model parameters. Easily can be done:model.parameters()And:See what module type they belong to, e.g.,type(param.MODULE) == nn.Conv2dHowever, I’m not sure how to get the param’s module… doesmodel.named_parameters()return something I can use here to do this?
ptrblck
You could use the returned name to get the module. E.g this code would print the registered modules at the highest hierarchy level: model = torchvision.models.resnet50() for name, param in model.named_parameters(): print(name) print(getattr(model, name.split('.')[0])) # print "highest" modu…
Luke_Vassallo
I am observing the gradients associated with my neural network weights and sometimes they hold a value of zero throughout the whole training process. When the gradients are zero resulting loss value that does not change in between epochs. The images attached show the two scenarios being observed. The first shows the lo...
ptrblck
I would probably remove the last torch.relu applied on the output of the model to allow for unbouded predictions.
ADONAI_TZEVAOT
i have a tensor x = [1,2,3]. I have another tensor y = [4,5,6]. I want to stack x on top of y such that the new tensor z = [[1,2,3], [4,5,6]]. How to do this?
ptrblck
torch.stack should work: x = torch.tensor([1,2,3]) y = torch.tensor([4,5,6]) z = torch.stack((x, y), dim=0) print(z) # tensor([[1, 2, 3], # [4, 5, 6]])
Sam_Lerman
Or mustNormalize(mean, std)always be applied last?
ptrblck
torchvision.transform accept tensors as well so you could apply some of them after normaliying the tensor. However, I would use transformations designed to change the actual pixel values of images (e.g. random color transforms) before convertig the image to a tensor.
Santosh_Gupta
I’m looking how to do class weighting using BCEWithLogitsLoss.https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.htmlThe example on how to usepos_weightseems clear to me. If there are 3x more negative samples than positive samples, then you can set pos_weight=3Does theweightparameter do the same thing...
ptrblck
No, the weight argument will apply the weight to each sample of the batch.
Imahn
Hi,when I do the training of my model on a CPU-only device, does it make sense to choosenum_workers > 0? From thedocumentation, it’s not entirely clear to me, as it only states:[…] how many subprocesses to use for data loading.0means that the data will be loaded in the main process. (default:0)I’ve also taken a brief l...
ptrblck
Yes it could make sense to use multiple workers, as they would load the next batch(es) in the background while the model is being trained. Depending which operations are used to train the model and if they are able to use all CPU cores, you might or might not see a speedup, so you should check diffe…
AGescap
I’m studying a learning algorithm that has to do with how training samples are chosen in SGD, so this problem I’m going to present is “tangential”.The thing is that I want to use alearning rate scheduleas this:The user gives an input consisting in two different lists, e.g.:epoch_list_LR: [0, 100, 200, 500] so it’s impl...
ptrblck
I think writing a custom scheduler would give you the most flexibility and allow you to implement this custom learning rate scheduling. Something like this might work: class MyScheduler(torch.optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, lr_epochs, lrs, last_epoch=-1, verbose…
thedrewyang
Here is my D-Unet model. After doing model.to(device), the system still raise this RuntimeError.DEVICE = “cuda” if torch.cuda.is_available() else “cpu”x = torch.rand(16, 4, 192, 192).to(DEVICE)model = D_Unet().to(DEVICE)pred = model(x)RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor)...
ptrblck
You are creating new modules in the forward method of D_Unet e.g. here: conv3d1 = Bn_Block3d(in_filters=1, out_filters=32)(input3d) which won’t be pushed to the device in the model.to() call. I’m not familiar with your approach, but the standard approach is to initialize the layers in the __init_…
Anirban_Nath
So I have just 1 layer of conv2d defined as follows: -self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)Now I want to save its state dictionary for future use. I thought that the state dictionary is a python dictionary that contains the weights of the model but when I executeprint(sel...
ptrblck
You would have to call the state_dict method via: print(self.proj.state_dict())
hadarshavit
Hi, I’m trying many configurations of my model using SMAC. Therefore, I’m training many models in the same script.To speed up each of the models training, I’m using persistent_workers=True. However, it causes to the workers (and the file descriptors) to remain.How can I close them after training a single model or re-us...
ptrblck
Maybethis postcould help. I haven’t verified it, so let us know if it works for you.
zizhao.mo
Hi,I want to know if there is any method to use different batch sizes across processes in distributedDataParallel? If yes, to my knowledge, gradients from different processes should be weighted by their batch sizes. So can PyTorch intelligently handle this issue?Thanks for any comments in advance.
ptrblck
This commentsuggest different approaches using hooks.
Danil_Hu
Hi, everyone!I found a curious stuff recently. As far as I know, when you want to do some operations on two tensors, you should make sure that they are on the same device. But when I write my code like this, it runs unexpectly wellimport torch a = torch.tensor(1, device='cuda') print(a.device) b = torch.tensor(2, devic...
ptrblck
In your use case b would be interpreted as a scalar value and should be forwarded as an argument to the CUDA kernel directly if I’m not mistaken. E.g. adding a dimension to b will break the code as seen here: # works a = torch.tensor(1, device='cuda') print(a.device) b = torch.tensor(2, device='cp…
wadewang
I happen to find that torch.jit.trace() will call forward() three times, run the code below:import torch class MyCell(torch.nn.Module): def __init__(self): super(MyCell, self).__init__() self.linear = torch.nn.Linear(4, 4) def forward(self, x, h): print("execute forward") new_h...
ptrblck
TorchScript will optimize the model and uses multiple forward passes to do so.
li.hao
Hi community. Here is theissue reportI created. Can someone provide some insight or feedback in it? Thanks!Describe the bugSeems like the dropout layer is not disabled when saving aModuleintrainmode throughjit.ReproduceCreating and saving the model via:statesJIT script (with model in train mode)JIT script (with model i...
ptrblck
Answeredhere. TL;DR: tracing a module records the actual execution (with or without dropout) and you thus cannot change the behavior afterwards.
mgiessing
Hi, is it possible to check how a pytorch package has been compiled?I’m specifically interested in the optimization intrinsics (e.g. if SSE or AVX for x86, VSX or MMA for ppc64le etc. has been enabled)Thanks!
ptrblck
You could get some information about lib support via print(torch.__config__.show()).
Haizhuolaojisite
Hi, I trained a model using 2 GPUs, and I want to make inference using trained model.1. How to load this parallelised model on GPU? or multiple GPU?2. How to load this parallelised model on CPU?I find document mentioned the way to save the DataParallel model by add the “module”, but actually I successfully save the mod...
ptrblck
Saving the model.module.state_dict() would avoid having to manipulate the state_dict keys, but both approaches should work. Restore the model and wrap it again into DistributedDataParallel afterwards. Store the state_dict on the CPU or use map_location='cpu' to load the state_dict onto the CPU. …
Roua_Rouatbi
I trained a model on 0 and 1 labels now I’m testing it on unlabeled datalabels=[0,1] for i, images in enumerate(imgset_loader): images = images.to(device) net = net.double() outputs = net(images) _, predicted = torch.max(outputs.data, 1) print(labels[predicted])The last line returns an error : TypeE...
ptrblck
Transform labels to a tensor via labels = torch.tensor(labels) and it should work.
Ziyu_Huang
Just like torch.mm(a, b), we have a and b on GPU, on global memory now(?), and we use deeper implementation to use shared memory or something by cublas, and then we output a result to global memory, is that correct? Not sure…So I am wondering is there a function like a.device() in python to show, where the data current...
ptrblck
Yes, your data lives in the global memory on the GPU. Shared memory, L1, L2 etc. is used in the CUDA kernels.
Trishna_Barman
I am trying to run this code:GitHub - Jee-King/TSAN: A Two-Stage Attentive Network for Single Image Super-ResolutionAs per my understanding, the code is written for both GPU and multithreading. As this code runs on GPU, it should use GPU environment. But it is running on multithreading. How to change it to run on GPU?I...
ptrblck
The new issue seems to be a known error in the repository as it was already postedhere. Generally, this error is raised if you are either calling backward multiple times (where the previous backward calls have freed the computation graph already) or if you are appending the computation graph and a…
maflobra
I have seen in theofficial torchvision docsthat recently vision transformers and the ConvNeXt model families have been added to the PyTorch model zoo. However, even after upgrading to latest torchvision version 0.11.3 (viapip) these new models are not available:>>> import torchvision; torchvision.__version__ '0.11.3+cu...
ptrblck
The linked docs show the main branch which is currently at 0.13.0a0+d785158 so you might need to update torchvision to the latest nightly release.
Nurkhan_Laiyk
Hello, I was trying to do an image segmentation and after testing saved the three images ( as an example).The problem is that 3 images are merged, while I want to save each one separately.def save_test(loader, model, folder=‘/kaggle/working/saved_test/’,device=‘cuda’):model.eval()for idx, x in enumerate(loader):x = x.t...
ptrblck
torchvision.utils.save_image creates a grid if a batch of images is passed to it. Call this method on each images separately to create separate images.