user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
malfonsoarquimea | if I have multiple workers, would each worker collect consecutive indexes?For example, if I have num_workers set to 2 , prefetch_factor set to 2 and batch_size set to 10 then, would one worker collect the first 2 batches (idx 0 to 6) and the second worker the following 2 batches (idx 6 to 12)? | ptrblck | Yes, your description is correct but each worker would collect 10 samples as seen here:
class MyDataset(Dataset):
def __init__(self):
self.data = torch.arange(20).view(-1, 1)
def __getitem__(self, idx):
worker = torch.utils.data.get_worker_info()
if worker:
… |
asif_hanif | for idx, batch in enumerate(Data_Loader):…When we iterate over data_loader, do all samples in the current (idx_th) batch get loaded in parallel or they are loaded one-by-one and then collated by collate_fn ? | ptrblck | Each worker (specified by num_workers in the DataLoader) will load a full batch by loading and processing the samples sequentially. The workers work in parallel. |
DiWarp | Hi there! I’m trying to code a CNN for a Rabbin Dataset and got some issues.My dataset is looks like this:ExampleI’m using the UNet Architecture, the input image is 572x572 and the output image is 388x388.My Dataset class is like this:learning_rate = 1e-3
batch_size = 10
epochs = 10
class MyDataset(Dataset):
def __... | ptrblck | No, you are creating y with random values in [0, 2] now which are not your true class targets.
My code snippet uses random tensors to show the needed shape and value range since I do not have access to your real dataset.
As previously described: the target should have the the shape [batch_size, he… |
gerstla | HiI am new to Pytorch and I was wondering if the following can be done.If I have a 2D tensor of indices for example:tensor([[1, 2, 4],[4, 2, 0],[0, 1, 3]])and a 1D tensor of valuestensor([6, 8, 9, 11, 23])I would like to get an output oftensor([[8, 9, 23],[23, 9, 6],[6, 8, 11]])Thanks | ptrblck | Yes, you can directly index the tensor:
x = torch.tensor([6, 8, 9, 11, 23])
idx = torch.tensor([[1, 2, 4],
[4, 2, 0],
[0, 1, 3]])
ret = x[idx]
print(ret)
# tensor([[ 8, 9, 23],
# [23, 9, 6],
# [ 6, 8, 11]]) |
Prakhar_Sharma | I constructed a custom model which looks like this (open the figure in a new tab). It is a combination of multipleclasses.DGM1508×1740 170 KBThe figure shows a single custom hidden layer (everything in between the input and output).Finally I created a object usingDGM_model = DGMArch(len(input_tensor), len(output_tensor... | ptrblck | You would have to access the right layers inside the model as e.g.:
torch.nn.init.xavier_uniform_(DGM_model.layer.weight)
where DGM_model.layer is accessing the nn.Module which you can then use to access the internal parameters of this layer via .weight and .bias. |
malfonsoarquimea | Hi! I have a tensor of shape (300x1024) containing a 1024 length codification of 300 framesSome keyframes, one every 30 frames (frame 0,30,60…) is a keyframe.I need to, for each code that doesn’t belong to a keyframe, to interpolate between the previous and next keyframe and set the result as the code for that frameAny... | ptrblck | I guess interpolate would work if you select every 30th data point:
x = torch.randn(300, 1024)
x = x[None, None]
out = torch.nn.functional.interpolate(x[:, ::30], size=(300, 1024))
out = out.squeeze() |
vzmb | Hello, I am new to using pytorch, but I manage to get almost everything working, but now I am using Googlenet pretrained and the model works fine, the problem is that I need to see the visualization layers and verify that the model is considering the relevant aspects. , what I want is something like the following image... | ptrblck | I don’t know how the actual forward method is defined, but the conv setup should never work assuming these layers are executed sequentially:
convs = [nn.Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False),
nn.Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=F… |
Mashood | Yes, I have looked and tried solution from other related questions. Let me explain.Description:So, I am doing adversarial training and I’ve used code fromthis Githubrepo. It uses Pytorch to train model on MNIST dataset.What want is that instead of MNIST I want to use CelebeA dataset. And when I run this exact code on t... | ptrblck | Replace self.conv1 with a new nn.Conv2d layer accepting 3 input channels, then replace:
x = x.view(-1, 16*5*5)
with
x = x.view(x.size(0), -1)
and fix the in_features of self.fc1 in case you are running into a shape mismatch afterwards. |
Vedant_Roy | I currently have the following tensor:torch.Size([2, 2, 128, 1, 1])Normally the batch dimension is at the start, but here I’ve split the tensor on the number of channels. I.e.,(2, 512) => (2, 2, 128, 1, 1)1st dimension is the “split” dimension2nd dimension is batch dimension3rd dimension is # of channelsLast 2 dimensio... | ptrblck | torch.chunk will not detach the tensors from the computation graph and will yield the same results as seen here:
x = torch.randn(10, 3, 224, 224, requires_grad=True)
model = models.resnet18().eval()
# full batch
x.grad = None
out = model(x)
out.mean().backward()
print(x.grad.abs().sum())
# tensor(… |
valentin-cnt | Hello!class ActorCriticNet_Discrete(nn.Module):
def __init__(self, num_inputs, num_actions, learning_rate, hidden_size,
number_of_layers, is_dual):
super(ActorCriticNet_Discrete, self).__init__()
self.actor_nn = None
self.critic_nn = None
self.optimizer = None
... | ptrblck | In the first example self.actor_nn and self.critic_nn will both share the same base_nn module in their Sequential blocks while you have removed the shared module and seem to use it as a standalone module via self.nn in the second approach. Both approaches should have the same number of parameters. |
sakh251 | I fine tuned a fasterrcnn_resnet50_fpn model and try to convert it to torchscript.Load pre-trained model:model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)After training:in_size = 416
inp = torch.Tensor(np.random.uniform(0.0, 250.0, size=(1, 3, in_size, in_size)))
inp = inp.cuda()
with torch.... | ptrblck | You could try to use torch.jit.script instead, which should be more flexible. |
v-moayman | Hi all,I am raising this issue with the following example:for inner_step in range(self.inner_steps):
d_losses, _, bert_outputs = model.forward_with_params(
inputs_embeds=self.inputs_embeds,
labels=self.labels,
weights=weights,
... | ptrblck | Double post fromhere. |
Ilya_Kotlov | This is part is just a tracking on the issue which I though I solved (but actually I didn’t), see the final question in the end.part 1:using torch 0.3.0 by installingtorch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whlfromhttps://download.pytorch.org/whl/cu80/torch_stable.htmlFound GPU0 NVIDIA GeForce RTX 2080 Ti which requi... | ptrblck | Most likely the binary ships with the right GPU architecture so that that CUDA toolkit will not try to jit-compile PyTorch as already described in yourcross-post.
This might have been a known and already fixed issue or a completely unsupported case depending on your device you are using.
Don’t … |
Francesco_Lee | Hi, I am trying to load the audio files using DataSet and Dataloader, however it shows the following error, it seems to link the iter of the dataset. Could you help me solve it?import torch
import numpy as np
import os
import matplotlib.pyplot as plt
import torchaudio
from torch.utils.data import Dataset, DataLoadercla... | ptrblck | You have a typo here:
data_path = os.path.join(self.roo_dir,wave_file)
and would need to use self.root_dir to avoid the AttributeError. |
Tm4 | I’m using apretrained modelin which there are several self_attentions sequentially stacked each one after another and the number of them is 12. I need to extract the output of the fourth and 10th blocks of this sequential layers. In the following script, theBLockrepresents each self-attention layer:dpr = [x.item() for ... | ptrblck | You can use forward hooks as describedhereand register them to the 4th and 10th layers. |
wjeliot | I’m trying to build up an understanding of how nn.CrossEntropyLoss works. I see that it combineslog_softmaxandNLLLossbut am trying to work out exactly how.Suppose a model outputs logits of [1.761, 0.590, 3.157] and the ‘target’ is the third index (2). So if I manually assembled a one-hot encoding vector, the target wou... | ptrblck | Yes, you can directly index the logit as seen inthis small examplewhich calculates the loss manually using an explicit but slow approach.
No, as it would be wasteful to create the one-hot encoded target first and multiply it with the full logit tensor. The result would be equal to indexing just… |
ZHUANG_XIONG | When I use F.conv2d function, The above problem occurred.(pt1.9.0-cuda11.1) > $ python -m torch.utils.collect_env [±dev_PHRDV2 ●●]
Collecting environment information...
PyT... | ptrblck | Could you update to the latest stable release with the latest CUDA runtime and check if you are still seeing the issue, please? |
jhoanmartinez | Hello fellas,What is the purpose of find mean and std, is from each image or whole dataset, what is use for, how to find it? not clear yet and i have see that is a must in all models or am I wrong? thanks a lot | ptrblck | Normalizing the data is often beneficial and the standardization or whitening of the data by subtracting the mean and dividing by the stddev shows commonly a superior convergence of the model. I’m sure there might be exceptions, but it’s quite the standard now. I couldn’t find a quick reference but … |
danielmanu93 | Hi All I have data from a dataloader which I get a data and corresponding label from it. I am trying to normalize the labels within a certain range usingT.tonumpy_denormalize, however I get this errorAttributeError: 'numpy.ndarray' object has no attribute 'cpu'. I am not sure how to clear or override this error. Below ... | ptrblck | It seems your method expects a PyTorch tensor as it wants to call .cpu() on it while a numpy array is passed, which does not support the .cpu() operation so check and fix your input. |
werdas34 | I am working with a paperspace vm with an A6000 GPU and have a transformers/pytorch model there.I can’t get this to run on this GPU but it runs on the CPU.PyTorch must have version 1.4.The following is the setup of the VM and sample code.Interestingly, the same model with the same settings (except nvcc, because no tool... | ptrblck | That won’t work on your A6000, as you need CUDA=11.x for your Ampere GPU and thus cannot use the CUDA 9.2 runtime. |
a1o | Hey all,I am working on a Model in which a layer takes two inputs.The first input is part of the input data, and the second input are embeddings (of other input data.)I’ve tried to combine the two using torch.concat(), which returns a tensor.That tensor however cannot be used downstream without modifications;I receive ... | ptrblck | self.combined is a single tensor which is passed to an nn.ReLU and should work.
However, I guess you are trying to assign the output to self.l1 which seems to be an nn.Module and which is wrong. |
Sylvain_Ard | Hello,my classification program sometimes hangs at random epoch (the program doesn’t advance anymore) and tends to overfit. How to fix these two problems.This is the program :Dropbox - train.py - Simplify your lifeThank you for helping meBest regards | ptrblck | Sure! Assume you want to add another linear layer as well as a dropout layer to renset50’s classifier (which is a single linear layer assigned to model.fc), you could replace it with a new nn.Sequential container and add the new layers as well as the original linear layer to it as seen here:
model … |
MartinZhang | How to deal : register_forward_hook is not support on ScriptModulesOr whether there are alternative solutions, Thanks. | ptrblck | That’s a known limitation and the feature request is trackedhereso feel free to add your use case to the linked issue. |
mfatih7 | HelloLets say that in my CNN network I have a feature map with the dimensions N,C,H,WLets say that H=50 and W=4How can I pass the feature map through a nn.BatchNorm2d with dimensions H=10 and 4I do not want to instantiate 5 distinct nn.BatchNorm2d.Instead I want the learnable parameters of nn.BatchNorm2d shared.best ... | ptrblck | You approach should work. I would probably append the outputs to a list and call torch.stack or torch.cat afterwards to avoid concatenating the intermediates in each iteration. |
Soban_Khan | Explanation: I created a model with five inputs, three of them are CNN and two of them are linear. Then I concatenated them with the output as binary classification. The shape of input images are: (32,128), (16,64), (8,32), and the two linear inputs are: 64 and 16.Here is the code of the model that I used:class multi_n... | ptrblck | It seems the shape mismatch is raised in ch4 = self.fc_1_1(input_4) so check the input_4.shape and make sure the number of features matches the expected in_features in the linear layer. |
danielmanu93 | Hi All I have data from a dataloader which I pass to my model for prediction. I am trying to normalize my prediction within a certain range usingT.tonumpy_denormalize, however I get this errorRuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead. I have tried to use.detach()... | ptrblck | You are trying to call numpy() on a tensor, which is still attached to a computation graph, and which is disallowed without calling detach() explicitly. This error is used to make sure the users are aware that this tensor is being detached (and thus they have to use the detach() call explicitly) in … |
Chanu_hcu | Consider the memory usage of 4 GPUs while training my models usingnn.DataParallel.Screenshot from 2022-08-03 13-06-471118×217 8.66 KBWe can see thatcuda:0generally acts as the master node and needs more memory. Is there any way to distribute memory uniformly among all the GPUs? | ptrblck | That’s a known limitation of nn.DataParallel which is one reason why we recommend to use DistributedDataParallel besides the better performance of the latter approach. |
justin-larking-pk | I’m attempting to train a custom deeplabv3 model, using custom data. I continually run into this error with my current setup for my training, dataset, loss etc script.RuntimeError: stack expects each tensor to be equal size, but got [400, 640] at entry 0 and [400, 640, 3] at entry 17It seems that my dataloader is tryin... | ptrblck | Could you check if any mask has 3 channels by printing its shape in the __getitem__? |
richinex | I have these two functions, one written in pytorch and the other written in Jax. The one written in pytorch kills my kernel on my linux laptop (16 gb ram) and also on kills the kernel (out of memory) on my colab pro plus as soon as I set the num_epochs above 1e5. This happens even when I move device to GPU. Meanwhile ... | ptrblck | You are appending the loss with the entire computation graph here:
self.losses.append(self.loss.clone())
which would eventually yield the out of memory issue.
Assuming you want to use self.losses for logging purposes, detach() the loss before appending it. |
Caipi | Hello,I have been given access to a GPU cluster where the GPUs (2x NIVIDIA A100 80GB) are partitioned usingMIGto partition their GPUs into sub-elements…Unfortunately, the I cannot find an example which can show me how to access the part via a given UUID of the sub element (MIG-11c29e81-e611-50b5-b5ef-609c0a0fe58b)… Or ... | ptrblck | You have to define this env variable as given in theuser guide:
$ nvidia-smi -L
GPU 0: A100-SXM4-40GB (UUID: GPU-e86cb44c-6756-fd30-cd4a-1e6da3caf9b0)
MIG 3g.20gb Device 0: (UUID: MIG-GPU-e86cb44c-6756-fd30-cd4a-1e6da3caf9b0/1/0)
MIG 3g.20gb Device 1: (UUID: MIG-GPU-e86cb44c-6756-fd30-cd4a-1e6… |
blackbirdbarber | I have the stide2 conv defined:conv = nn.Conv2d(in_channels=256, out_channels=256,kernel_size=3, padding=1,stride=2)Out:torch.Size([1, 256, 25, 25])
torch.Size([1, 256, 13, 13])but I would like to have it like this:torch.Size([1, 256, 25, 25])
torch.Size([1, 256, 12, 12])I tried altering the dilation, padding, but didn... | ptrblck | You could play around with other settings, e.g. conv = nn.Conv2d(in_channels=256, out_channels=256,kernel_size=5, padding=1,stride=2) would create the desired output shape. However, if you don’t want to change the kernel_size it might be easier to just slice the output. |
avalon1511 | My code performs a loss minimization from the output of a pretrained GAN. Apart from the GAN parameters I am also trying to optimize the latent variable z.The code is set up as followswith torch.no_grad():
gan_out = G(z_initial)
z_initial.retain_grad = True
loss = MSEloss(gan_out, observed_image)
GAN_optim.zero_gr... | ptrblck | No, no_grad() is not a class method of nn.Module.
Are you trying to update the input to G only while G is frozen?
If so, this should work:
G = nn.Linear(1, 1)
# freeze
for param in G.parameters():
param.requires_grad = False
z_initial = torch.randn(1, 1, requires_grad=True)
gan_out = G(z_in… |
blackbirdbarber | Example:import torch
import torch.nn.functional as F
z = torch.tensor([3, -1, 2.])
y=torch.tensor([1,0,2]).float()
yhat = F.binary_cross_entropy_with_logits(z, y, reduction='none')
print(yhat)Out:tensor([ 0.0486, 0.3133, -1.8731])Can you clarify why PyTorch supports negative entropy solutions? | ptrblck | A target value of 0.5 would indicate that the sample belongs to both classes with the same weight.
You can interpret the target values as probabilities as they are supposed to be in [0, 1] or as any weights if it fits your understanding better. In any case, you should not pass targets out of this r… |
Godspeed | Hi,I am trying to generate a mask to get the positive logits.I get label_1 [1,2,3,4,7] and label_2 [1,2,7,2]the goal is to get a 01 mask M, when i and j are the same class, Mij=1, others = 0the above label_1 and label_2 could generate such mask with size[5,4][[1,0,0,0],[0,1,0,1],[0,0,0,0],[0,0,0,0],[0,0,1,0]]Well,... | ptrblck | A comparison with broadcasting should work:
label_1 = torch.tensor([1,2,3,4,7])
label_2 = torch.tensor([1,2,7,2])
res = label_1.unsqueeze(1) == label_2
print(res)
# tensor([[ True, False, False, False],
# [False, True, False, True],
# [False, False, False, False],
# [Fals… |
Hyeonuk_Woo | By adding a few layers to the pretrained model(PretrainedModel), I want to train new model(MyNewModel), where the existing pretrained layers(starting with pretrained weights) and newly added layers are trained simultaneously.class PretrainedModel(nn.Module):
def __init__(self):
self.layer_s=Pretrain... | ptrblck | Yes, the code looks generally alright.
I don’t quite understand the list(map(lambda ...) usage to create the parameters and think just using model.parameters() or list(model.parameters()) should do the same.
In any case, you would still need to fix the optmizer.step() calls, since now you are crea… |
AjeelAhmed1998 | import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
s... | ptrblck | Yes, the out_channels represent the number of output channels and thus the number of filters in the default setup.
No, you would get out_channels activation maps, as each filter uses all input channels to create one output activation map (in the default setup; grouped convs would work in a differ… |
zia_badar | Can someone point out the mistake in my code, loss is not updating optimizing parameter:bimport torch
from torch.nn import Parameter
if __name__ == '__main__':
a = torch.arange(start=1, end=5, dtype=torch.float32)
b = torch.arange(start=4, end=0, step=-1, dtype=torch.float32)
optim = torch.optim.Adam([Par... | ptrblck | Create b diredctly as an nn.Parameter object and it should work.
Currently you are passing a temporary object to the optimizer, which will not update the b tensor. |
Cai | using a simple DNN to predict Tox21 toxicity.with following modelclass DNN(nn.Module):
def __init__(self, n_features, n_layers, n_classes):
super(DNN, self).__init__()
self.layers = nn.ModuleList()
in_features = n_features
n_hidden = in_features//2
for i in range(n_layers):
... | ptrblck | You are resetting the losses only once before the training starts losses= 0 and are then accumulating the batch losses to it. Later you are dividing by the number of batches, so I guess you might want to reset losses once per epoch. |
robinho | How to choose an optimum initial learning rate in adam?When it’s too big, why does the net converge to a wrong solution? Normally too big a learning rate should make the loss oscillate too much but not get stuck in a wrong solution? | ptrblck | No, I don’t think this operation depends on the model architecture. You would need to install and use the fastai package or reimplement their learning rate finder in pure PyTorch. |
SU801T | I was wondering how can I keep my batch norm layers active using an untrained feature extraction network.Would this be considered feature extraction with an “untrained” network?:class DenseNetConv(torch.nn.Module):
def __init__(self):
super(DenseNetConv,self).__init__()
original_model = models.dense... | ptrblck | Yes, I guess you could call DenseNetConv an untrained feature extractor.
Yes. You’ve frozen all trainable parameters from the feature extractor by setting their requires_grad attribute to False, while the linear layers in MyDenseNetDens should still be trainable since no attributes were changed. … |
simines | I have installed PyTorch usingconda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorchInstallation is done with no error. However, when I import torch I get an error that cuda fails to initialize. You may not have gpu.Does anyone know why this happen? | ptrblck | That could be the case. On my Windows laptop I’m using an older 452.06 driver and can properly run the 1.12.0+cu116 binary as describedhere. |
MichaelMMeskhi | I have a tensor of images of size(3600, 32, 32, 3)and I have a multi hot tensor [0, 1, 1, 0, …] of size(3600, 1). I am looking to basically selecting images that correspond to a 1 in the multi hot tensor. I am trying to understand how to use torch.gather:tensorA.gather(0, tensorB)Gives me issues with dims and I can’t p... | ptrblck | Yeah, exactly. I was thinking if something like this could work for you:
N = 10
x = torch.randn(N, 32, 32, 3)
out = torch.randint(0, 2, (N,)).float().requires_grad_(True)
res = x * out[:, None, None, None]
idx = res.nonzero()[:, 0].unique()
print(len(idx), out.sum())
# 5 tensor(5., grad_fn=<SumBa… |
blackbirdbarber | I have thesegmentation.deeplabv3_resnet50under my test. It’s working bad at the moment.As you can see this is the original image normalizedAnd this is the ground truth with just 3 classes (background - red, vessel - black, and filled - blue).I just don’t have the experience training this model. Exactly:What should be ... | ptrblck | The output for a multi-class segmentation use case would usually have the shape [batch_size, nb_classes, height, width] where num_classes=3 in your use case.
Each channel of the prediction contains the logit values for the corresponding class. Using torch.argmax(output, dim=1) will return the p… |
Jakub_Mitura | Hello I am creating custom loss function, on of the component is modifying the values of the data array.so for example function f mutates A into B both A and B are the same shape and data typef(A)=Bin order to keep backpropagation working I need to supply new array as the output so for exampleB= zeros()
f(A,B)
return B... | ptrblck | Your indexing approach of:
x[index] = x[index] + b
would also manipulate x inplace and will also raise an error if it’s disallowed. |
jtorch | Hello,This is my first time posting. I wrote a super basic feed forward network in an attempt to optimize a function. However, I noticed that it was not learning. So I decided to simplify the function as much as possible, while using the same essential architecture, and it’s still not learning.Here is the network class... | ptrblck | You are detaching the loss tensor by r-wrapping it into a new tensor in:
loss = T.tensor([loss], dtype=T.float,requires_grad=True).to(self.device)
loss.backward()
Just call loss.backward() and remove the previous line of code and it should work.
EDIT: I just realized that you are detaching the co… |
Tm4 | I have a 5D tensorx(frames of a video) and I want to upsample the spatial size (the last two dimensions) of this tensor but when I use upsampling, the last three dimensions of the tensor are upsampled. For upsampling I use the following class:class Upsample(nn.Module):
def __init__(self, scale_factor, mode, align_c... | ptrblck | The issue is caused by the standard layout of a 5D tensor as [batch_size, channels, depth, height, width] and by specifying only a single scale_factor. This module then expects to apply the scale_factor too all 3 dims.
If you want to skip the interpolation in the depth dimension, specify the scale_… |
SeanX | Hi, I am getting a runtime error when using two fc layers for mixed precision training.Environment: pytorch 1.9.0 + CUDA 11.4Code to reproduce the error:import torch
import matplotlib.pyplot as plt
inputs = torch.zeros([6, 152, 128, 480], dtype=torch.float32).cuda()
targets = torch.ones([6, 2], dtype=torch.float32).cu... | ptrblck | Scripting and mixed-precision training had some issues in the past, so you could update to the latest nightly or stable release and it should work.
I just verified it in a current 1.12.0+cu116 release and don’t see any issues. |
maryma | Hi I had one datasets I made a dataloader of this dataset. I wanted to extract features of my datasets from a model. I dont know when I make a dataloader with batch = 1 and shuffle false is the data loader organized or not? I mean I wanted to know is the first data in my dataloader exactly first data in my dataset that... | ptrblck | If shuffle=False is set then a SequentialSampler will be used which will pass the indices in order to the Dataset.__getitem__. You could print the index in the __getitem__ and would see the used order. |
sneer | Hi,I want to freeze (some) layers of a network feature encoder (resnet50 in my case) and then add some dense layer to the feature encoder to evaluate on some classification task.I am freezing the layers like this:for child in self.feature_extractor.children():
for param in child.parameters():
param.requires... | ptrblck | The latter will return the name as well as the child module which could be useful to e.g. filter out child modules if needed.
.parameters() will return all parameters of the module and all internally registered submodules (children). Your approach would work, but you could also directly use self.… |
Ziyu_Huang | Hi! I am trying to allocate several torch.tensor continuously, can we somehow do that? Thank you!!!Well…their size are not equal…Allocate one big tensor and split it might be…not very practical…Otherwise maybe I can create a (1, m) and then split it and reshape each one??? Maybe…but dirty…Thank you!!! | ptrblck | Allocating a large tensor and then slicing it, might work. However, what’s your use case and why do you depend on this memory allocation? |
tal123 | I have a rather small GPU that can compute ImageNet classification loss on up to 32 images at once, and I’d like to simulate batch sizes of 256 images.Since I use SGD optimizer, the loss gradient on the whole batch is simply the sum of the image loss gradients.So theoretically, if I had access to the gradient vector, t... | ptrblck | Yes, you could use the approaches describedhere. |
Pablo_Garcia_Sant | Hi everyone!I have doubts mainly about how the strides in the ConvTranspose2D layers work.My model of an Conv AE is :def __init__(self):
super(ConvAutoencoder, self).__init__()
# Encoder
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, padding=1)
self.conv2 = nn.Con... | ptrblck | A guide to convolution arithmetic for deep learningis a great reference to as it visualizes how different convolutions are applied. The relevantrepositoryalso provides some animations. |
aonrdbit | Hello everyone!I am using NCCL as the backend for the distributed training of PyTorch. I used four compute nodes. But there was a strange problem in calculating the time consumption.Part of the code is as follows.def average_gradients(model):
size = float(dist.get_world_size())
for param in model.parameters():
... | ptrblck | loss.item() will synchronize the device for you, as the value stored on the GPU has to be moved to the host.
Since CUDA operations are executed asynchronously you would need to synchronize the code via torch.cuda.synchronize() before starting and stopping the timers. In your current code the profil… |
Qwwq | Is it possible to set different learning rates for different part of a tensor? | ptrblck | That’s not possible as you would be hitting the same limitations explained in yourother topic. |
Qwwq | I want to set a portion of a tensor (such asx[1:3, 5:10, :]) to haverequires_grad=False. Is this possible? | ptrblck | No, that’s not directly possible since the .requires_grad attribute is used for the entire tensor.
You could either zero out the gradients of the frozen tensor part, restore their values after the rest was updated, or recreate the x tensor from smaller tensors having different .requires_grad settin… |
Kore_ana | I have tried running the following code on CIFAR-10 dataset.However, I found that the test loss stays constant, which seems to indicate that training is not being donethe code is the following :class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.fc1 = nn.Linear(32*32*3, 512) #... | ptrblck | nn.CrossEntropyLoss expects raw logits as the model output so remove the F.softmax` from your model. |
ojipadeson | I’m new to pytorch and I found that the padding mode of conv2d is not zero padding in the following code:import torch
import torch.nn.functional as F
a = torch.tensor([[[[1,2,3,4],[4,5,6,7],[7,8,9,10]]]])
weight = torch.ones((1,1,3,3)).to(torch.long)
F.conv2d(a, weight, stride=1, padding=1)The output is:tensor([[[[12, ... | ptrblck | The default padding value is 0. and you can manually verify it:
import torch
import torch.nn.functional as F
a = torch.tensor([[[[1,2,3,4],[4,5,6,7],[7,8,9,10]]]])
weight = torch.ones((1,1,3,3)).to(torch.long)
ref = F.conv2d(a, weight, stride=1, padding=1)
a_pad = F.pad(a, pad=(1, 1, 1, 1), value… |
seer_mer | I noticed that torchvision chooses to use Conv2d to performsqueeze and excitation. However, I noticed that using equivalent Linear is much faster than Conv2d. Is there a reason torchvision chooses Conv2d? Or can this be improved? Below is the code I used to time these two.import torch
import torch.nn as nn
import time... | ptrblck | Yeah, I was able to confirm the different kernel selection in the default (legacy) cuDNN api.
If you are using the nightly binaries with a new cuDNN version (I would recommend to check the nightly binary with CUDA 11.6) you could set this runtime env variable to enable the cuDNN v8 API: TORCH_CUDNN… |
sspanceri | I need to do some experiments with digital mammograms to see if I get the best results with large images (maximum image size will be [3, 1024, 1024). So I try to change the input size of DenseNet121 with this:import torch.nn as nn
import torchvision
import torch.nn.functional as F
import src.experiment.settings as conf... | ptrblck | No, that shouldn’t be the case and the in_features should be set to the number of features of the incoming activation.
In your case the input activation is the flattened output of the self.maxpool(x) operation which seems to have 1024 features.
It’s already working with my suggested fix:
class … |
Alphonsito25 | Hi, I am trying to edit the input and output channel of Mobilenet_v3_small. I have created a class for this (avoid the encoder part). The change is based on the mobilenet source code.input_net = 3 (RGB image)
output_net = 2 (2 classes)
last_channel = 1024 (Default in Mobilenet_v3_small)
class mi_Net(nn.Module):
def... | ptrblck | If you want to reduce a tensor in the shape [1, 17, 2] to [1, 2] you could use any reduction operation such as e.g. torch.mean, torch.sum etc.
Also a linear layer would work in case you want to reduce it, but the right approach depends on your use case in the end:
x = torch.tensor([[[0.1626, 0.251… |
LuggiStruggi | So i have a tensor with a certain amount of dimensionsAfilled with values and a TensorCwith the same dimensions (but without the last) with indices forA’s last dimension. I want to pick the values ofAbased onCsuch that a Tensor with the shape ofCis returned.Example:Ahas shape (7, 2, 4),Chas shape (7, 2).A:[[[-10.0491,... | ptrblck | gather should work:
A = torch.tensor([[[-10.0491, -4.9780, -3.0346, -1.0746],
[ 1.1812, 1.8627, 3.2540, 5.5354]],
[[ -9.9464, -4.9588, -2.9927, -0.8602],
[ 1.0148, 1.9898, 2.7656, 4.7714]],
… |
cm8908 | Hi everyone. I am working on a transformer model that iteratively outputs probabilities of selecting node from N categories. I’d like to mask the probability of already selected node to zero so it doesn’t get selected any more. And I have encountered a runtime error at loss.backward() with message:one of the variables ... | ptrblck | The issue is raised in the masked_fill operation, but the error points to the inplace manipulation of mask in:
mask[:,torch.arange(10),city] = True
Assuming you don’t want to reuse the same mask you could recreate it:
...
mask = torch.zeros(1, 10, 5).bool()
mask[:,torch.arange(10),cit… |
may1 | I wanted to use less gpu memory and make inference speed faster by converting Pytorch models to TorchScript.TorchScript can create serializable and optimizable models from Pytorch code so I expected inference speed would be faster and also the size of module would be lighter.However, the size of a module was not decrea... | ptrblck | You might not expect to see memory savings right now depending which utilities you are using.
E.g. once the model is scripted, utils. such as AOTAutograd would try to cut down the memory usage by avoiding to store unneeded activations (and allow to recompute them instead). But these utils. are stil… |
hedeya1980 | I’m trying to use the u-net segmentation model atGitHub - khanhha/crack_segmentation: This repository contains code and dataset for the task crack segmentation using two architectures UNet_VGG16, UNet_Resnet and DenseNet-Tiramusu, and incorporate it into my pipeline. However, I noticed that whenever I use ‘inference_un... | ptrblck | You are explicitly setting pretrained=Truehereso that you are forcing torchvision to download the pretrained state_dict. If you don’t need it and are loading a custom pretrained state_dict pass pretrained=False and torchvision will not download anything. |
Simon_Watson | Hi All,I am porting a computational graph from tensorflow v1 to pytorch and have hit an issue with my float32 data.The illustrative example below sums up the issue. I get a result which is a vector of either 37059.996 or 37061.0 depending on the hardware used for calculation with a float32 tensor.# set up arrays in num... | ptrblck | Based on the error of ~1e-5 you are most likely running into small errors caused by the limited floating point precision.
It’s not a magic fix, but will give you more precision, thus reducing the error if you are using a wider dtype.
On GPUs you would expect to see poor performance using float… |
Jere_Poveda_Martinez | Hi,I’ve been using PyTorch (Lightning) almost for a year. However, I have little knowledge about CS things (processes, threads, etc.).Since now, my way of optimizing training time is None and my reasoning is as simple as: more data = more time, more parameters = more time. I wolud like to know how pytorch works with a ... | ptrblck | Generally, I would recommend to take a look at theperformance guideif you are trying to optimize your code.
I’ll also try to answer the questions in a general PyTorch setup, as I’m not deeply familiar with Lightning and guess that it might try to optimize the code for you in some of their utils.
… |
fkoe | Hello,I’m trying to train a model for predicting protein properties. The model takes as input a whole protein sequence (max_seq_len = 1000), creates an embedding vector for every sequence element and then uses a linear layer to create vector with 2 elements to classify each sequence element into 2 classes. To make use ... | ptrblck | Yes, nn.CrossEntropyLoss sounds like the correct loss function for your multi-class sequence classification. To calculate the loss you would have to permute the model output as this loss function expects model output in the shape [batch_size, nb_classes, *] (where * would be the seq_len in your exam… |
may1 | I wanted to reduce the size of Pytorch models since it consumes a lot of GPU memory and I am not gonna train them again.First, I thought I could change them to TensorRT engine.and then I was curious how I can calculate the size of gpu memory that it uses.Pytorch model size can be calculated bytorch.cuda.memory_allocate... | ptrblck | PyTorch will create the CUDA context in the first CUDA operation, which will load the driver, kernels (native from PyTorch as well as used libraries etc.) and will take some memory overhead depending on the device.
PyTorch doesn’t report this memory which is why torch.cuda.memory_allocated() could … |
Mahdi_Amrollahi | How can I know the difference between these three cross-entropies functions?How can I know the math formula of them?image888×676 68.2 KB | ptrblck | Thedocsof these functional API calls should refer to theclass docswhich show you the used formula. |
tolry418 | Hello.I want to skip update and go to next iteration. For examplefor it, input in dataloader:
optimizer.zero_grad()
output = model(input)
loss = myloss(output, label)
if loss.item()==0 or not torch.isfinite(loss):
loss.backward()
continue
loss.backward()
optimizer.step()I want ... | ptrblck | Yes, it should be possible to skip the backward and optimizer.step() calls by e.g. checking if the returned batch_loss tensor has a valid .grad_fn attribute or if it’s set to None. |
Mahdi_Amrollahi | In deep neural networks, sometimes we have a complicated estimated function at the end including many multiplication and applying activation functions. How do we know that is differentiable or not? We just add layers and changing activation functions without knowing it. | ptrblck | If you are unsure if a specific operation is differentiable you could check if it’s output has a valid .grad_fn attribute. |
ZahAbdel | I’m using a Unet architecture. During training the loss value is the same.Dataset: 4000 sample from 160 augmented imagesI changed the learning rate many time from 0.1 to 0.000001 but the result is the same.21146×512 132 KB | ptrblck | Try to overfit a small dataset (e.g. just 10 samples) by playing around with some hyperparameters.
Once this is done try to scale up the use case again. |
SantaTitular | I started discussion this topic in issue#81950. Basically, I have designed a custom CrossEntropyLoss function to work with complex-valued data (remote sensing, signal processing, etc.), and I designed a simple FNN. However, I’m getting an error getting the autograd to propagate:AttributeError: CrossEntropyLoss object h... | ptrblck | You would have to create the object first and then call it:
loss = nn.CrossEntropyLoss(inputs, targets) # wrong
# right
criterion = nn.CrossEntropyLoss()
loss = criterion(input, targets) |
sn710 | When running Pytorch inference on a Resnet model on Jetson Xavier GPU, in my python script I use -device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')so that I can later do something like -inputs = inputs.to(device)to copy the inputs from host to device (cpu to gpu) before running the inference.Simil... | ptrblck | The DLA is not a built-in device in PyTorch and you could use it e.g. via TensorRT. |
t-hyun | Hello everyoneI’m stuck with my remote server, trying to train huggingfaceEleutherAI/gpt-j-6Bmodel.minimal code example (no training. Just loading)command:python -m torch.distributed.launch --nproc_per_node=8 trial.pyminimal runnable code trial.pyfrom transformers import AutoModelForCausalLM
import torch
import argpar... | ptrblck | Each process would try to load the model into the host RAM and with ~10*22.9GB you might be too close to the max. available memory as the OS, Python, etc. would also need to be loaded into the RAM. You can certainly observe how much RAM is needed and if you are indeed running out of host RAM.
You s… |
oneilllml | There are several posts already about this error, and I’ve encountered it many times, but it’s still often difficult to solve.Partly this is because the stack trace is normally incorrect. As pointed out elsewhere, the right stack trace can be obtained using CUDA_LAUNCH_BLOCKING=1, but then I need to rerun everything, w... | ptrblck | Yes, that’s the right approach. Since CUDA operations are executed asynchronously, the stack trace could be wrong otherwise.
That’s expected as the device assert corrupts the CUDA context. Executing any CUDA operations could reraise the same or another error.
No, since this would synchronize yo… |
FrAnY | Hello,i want to perform multiple forward passes of full batches with a GPU.Therefore each batch uses the complete VRAM.I want to store them temporarily and perform tuple mining with the concatenad batches.This is my approach but i run out of VRAM:stored_embeddings = []
stored_labels = []
for i, (inputs, labels) in enum... | ptrblck | Ah OK. Yes, you will not be able to delete the forward activations and still be able to calculate the gradients (they are needed in the backpropagation). |
Andrei_Cristea | Per thetuning guide section on CPU-GPU synchronizationwe should try to allow the CPU to run ahead of the GPU and avoidingtensor.to(device)calls is a good idea. I assume one good practice is to usenon_blocking=Truein theto(device)calls.Is there ever a circumstance when one should avoidnon_blocking=True? or is itFalseby ... | ptrblck | Your would use page-locked (pinned) memory on the host, which is a limited resource. Once you use page-locked memory your OS won’t be able to use it anymore and depending on your system you might be running into a situation where the OS starts to use the swap and would kill the performance of your… |
rjsdebug | I created a subset of datasubset = torch.utils.data.Subset(train_dataset,newIndices)Here, newIndices is just a list of indices to use in my subset.I want to analyze the logits I get on a forward pass, so I need to pass all the data of the subset into my model at once.images=subset.data.type(torch.FloatTensor)
logits = ... | ptrblck | No, your approach sounds fine. |
SU801T | I’m doing binary classification, however used categorical cross entropy loss rather than binary to train my model (I believe this is ok as results appear to be normal).Using a saved model, during inference however, I would like to obtain class probabilities for the outputs from the model.I believe logits are output fi... | ptrblck | Yes, your usage of softmax looks correct, but note that the topk results will be the same using the logits or probabilities since softmax does not change the order of the logits. |
registerrug | I currently have 11 pt files of size “torch.Size([1000000, 3, 50, 40])”. Each tensor for the cnn is 3x50x40. Each pt file has 1MM of these tensors. I cannot combined them due to memory limitations and I do not want to save them as 11MM individual pt files. Can anyone help me understand how to get these into a DataLoade... | ptrblck | No, I wouldn’t use a ConcatDataset since you would need to preload all datasets, which wouldn’t fit into your RAM.
I was thinking about this simple approach:
for i in range(10):
data_tensor = torch.load('tensor_{}.pt'.format(i))
dataset = torch.utils.data.TensorDataset(data_tensor, targe… |
sidnetopia | Hi, I want to extend the torchvision’s Faster RCNN(vision/faster_rcnn.py at main · pytorch/vision · GitHub). My plan is to have an additional classification task where features from thefeature extractorare used to determine the class of the image. Then the classification loss will be computed and backpropagated to thef... | ptrblck | I assume you are interested in usingthese features. If so, you could try to return this features tensor additionally and use it directly in your new classification task or alternatively you could also try to store this tensor using a forward hook and pass it to the classificator after the forward p… |
maryma | Hi, I wanted to do the segmentation on kidneys dataset. For preprocessing data I tried to use cropforground and use labels so I could extract two kidneys. then for giving good dataset to training model I extract the left kidney and right kidney separably and I did these steps for labels. So I had left kidney images, le... | ptrblck | It seems the loss_function tries to call one_hot on the target tensor and failshere. Could you describe which loss function are are using as this seems to be a hard requirement? |
mahmood | Hello,I have declared twonn.Parameter()variables withrequires_grad=Trueand I am using those in a different function that’s being called inside the init method of the class where variables are declared.lparamandrparamare not getting updatedMy question is am I doing it the right way?if not how it should be done?here is t... | ptrblck | The .cuda() operation on the nn.Parameter is differentiable and will create a non-leaf tensor.
Remove the .cuda() operation and call it on the nn.Module instead or alternatively call it on the tensor before wrapping it into the nn.Parameter. |
FA321 | I’ve been trying to learn torchScript and have been running into some issues trying to apply it to a notebook I’m working on in Google Colab. Currently, I have a gaussian transformation function shown below:def gaussian(x,mu,sigma):
return 1-(sigma/(((x-mu)**2) + sigma**2) / np.pi)Ideally, I want to run this functi... | ptrblck | I don’t think TorchScript is able to understand the timer() function so you might need to remove it. |
HJX-zhanS | I am currently trying to build the following model.1658283160152982×573 83.7 KBMy code is as following shows:class CNN_1(torch.nn.Module):
def __init__(self):
super(CNN_1, self).__init__()
...
def forward(self, X):
...
return X
class CNN_2(torch.nn.Module):
def __init__(self):
super(CNN_2, self).__init... | ptrblck | Thanks! The shapes don’t work as you would be running into a shape mismatch in self.fc After fixing it by setting in_features=60 the model works correctly:
model = AssembleModel()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(params=model.parameters(), lr=1e-3)
X_1 = torch.randn(1… |
Entropy | Say I have a tensor liketest = torch.arange(16).resize(4, 4)This should look liketensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])Is there a way to implement a fixed sliding window along the rows that outputs the same number of tensors as the number of rows (by rep... | ptrblck | You should be able to expand the tensor and unfold it, but it depends on your actual use case if this would be faster than your loop as it also could add an additional memory overhead:
test = torch.arange(16).view(4, 4)
test = torch.cat((test[0].unsqueeze(0).expand(3, -1), test[1:]))
out = test.un… |
Cheul | I’ve tried and compared three different methods for convolution computation with a custom kernel in Pytorch. Their results are different but I don’t understand why that is.Setup code:import torch
import torch.nn.functional as F
inp = torch.arange(3*500*700).reshape(1,3,500,700).to(dtype=torch.float32)
wgt = torch.ones... | ptrblck | It’s not completely true that you are using int32 dtypes as the actual convolutions are performed in float32.
If you check the errors you would see that you start to diverge at the higher range and in particular you are running into the expected rounding in float32.This Wikipedia article on Singl… |
Apprehensive-oil-284 | Consider the following code:import time
import torch
if __name__ == '__main__':
seed = 0
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
x = torch.rand(32, 256, 220, 220).cuda()
t = (x.min() - x.max()).to(torch.device("cpu"), non_blocking=True)
prin... | ptrblck | Yes, you are right and you would need to synchronize the current stream e.g. via:
if __name__ == '__main__':
seed = 0
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
stream = torch.cuda.current_stream()
x = torch.rand(32, 256, 220,… |
hitbuyi | I need some help on parameters of torch.onnx.export(…)1, dynamic axes.what are backgrounds or application requirements for us to set dynamic axes? | ptrblck | No, usually you refer to a change in the actual shape. I.e. in one iteration the input shape could be [1, 1, 1] in the next it could be [2, 3, 4].
Dropping or adding an entire dimension would usually just fail at a layer input as a specific number of dimensions is expected. |
aseembits93 | Hi all, I noticed something perplexing in my experimentation with Pytorch. I work on time series data where I don’t always have the ground truth for all the time steps for a sequence. I’m having trouble doing gradient updates. Here’s the codeimport torch
rand_in = torch.rand((5,10))
loss_fn = torch.nn.MSELoss(reduction... | ptrblck | I guess you would expect to see valid gradients hoping that nan_to_num would avoid creating the NaNs in the backward pass.
If so, then I think your observation is expected as the loss is calculated using the already invalid targets.
You are replacing the invalid values afterwards, but the computat… |
AndreasH | Hello everybody,PyTorch seems to use the wrong cuda version.I create a fresh conda environment withconda create -n myenvThen in this environment I install torch viaconda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forgeAfterwards if I start python in this environment and import torch, to... | ptrblck | Thanks for the update.
So the install command seems to work as conda list shows the right binary:
pytorch 1.12.0 py3.9_cuda11.6_cudnn8.3.2_0
but you have multiple PyTorch binaries installed where the one installed via pip seems to use the CUDA 10.2 runtime and is an old… |
JohnPolo | Hi. I’m using torchvision 0.13.0.I had this problem:TypeError: Expected input images to be of floating type (in range [0, 1]), but found type torch.uint8 insteadWhen I was attempting to do this:import transforms as T
def get_transform(train):
transform = []
# converts the image, a PIL image, into a PyTorch Te... | ptrblck | Thanks for the explanation.
Import the torchvision.transforms and your local transforms as different modules and it should work.
E.g.
from transforms as det_transforms
import torchvision.transforms as transforms
and use these two names to separate the transformations. |
Omnia_Al-wazzan | Hi all.I’ve been working on a fusion model with two image and metadata modalities, CNN (image) and MLP (metadata).I tried merging two models using concatination in the same way that@ptrblcksuggested, but the torchsummary doesn’t work with it. Though the model trains and works fine.I’d like to see the parameters of the ... | ptrblck | The summary works fine if I use torchinfo and provide the batch dimension:
summary(model, [(1, 3, 224, 224),(1, 3)])
==========================================================================================
Layer (type:depth-idx) Output Shape Param #
===============… |
muammar | I have a custom dataset as shown below:class MyDataset(Dataset):
def __init__(self, X, y):
self.X = X
self.y = y
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
training_latent_dataset = MyDataset(
torch.cat(training_... | ptrblck | Yes, usually you would load the data on the CPU and push it to the GPU inside the training loop in order to overlap the data loading with the actual model training.
However, if you want to load CUDATensors directly, check theCUDA multiprocessing docsto avoid re-creating a CUDA context, which rais… |
erezinman | Hi,I’m been trying to use thetorch.nn.functional.conv1dfunction to perform multiple convolutions on the same input in parallel using thegroups=...parameter - so far to no avail. Unlike other questions I’ve seen answered, I intend to perform these operations on the entire batch (i.e. not 1 kernel per 1 item in batch). I... | ptrblck | I think increasing the number of output channels would just work unless I miss some details.
Your code is not executable as out_data has a wrong shape in dim3. After fixing it, a simple conv seems to work:
# Data Shape
n_batch = 7
n_in_channels = 5
n_time = 17
data = torch.rand(n_batch, n_in_chann… |
mathwseg | i tried to use those linemodel.eval()
device = torch.device("cuda")
model.to(device)but gotRuntimeError: CUDA out of memory. Tried to allocate 16.00 MiB (GPU 0; 5.80 GiB total capacity; 4.52 GiB already allocated; 4.56 MiB free; 4.53 GiB reserved in total by PyTorch)in this linemodel.to(device) | ptrblck | It seems to error now moved from the model.to() operation to the actual forward pass.
If the only data on the GPU are the model’s parameters and the input tensor, your model might be too large for your device. You could try to use e.g. torch.utils.checkpoint to trade compute for memory. |
ptinn | Hi,Is there a specific way to install or upgrade a higher version > 1.9.0 of PyTorch on Ubuntu 20 with CUDA? The standardinstallation commandon done my computer keeps the 1.9.0 version untouched:Requirement already satisfied: torch in ./.local/lib/python3.8/site-packages (1.9.0+cu111)
Requirement already satisfied: to... | ptrblck | Uninstall the PyTorch binaries and reinstall the latest stable ones or create a new virtual environment and install the latest release there. |
Liano | Can I finetune (in my case feature extracting) the pre-trained VisionTransformer model the same way as described in the pytorch Tutorial (Finetuning Torchvision Models — PyTorch Tutorials 1.2.0 documentation) ?In the tutorial only convolutional neural networks are used, so do I have to modify anything for the VisionTra... | ptrblck | The general fine-tuning logic would apply to all models, but you might need to change some model attributes (e.g. replacing the .classifier might look a bit different using other models depending how the internal modules are structured). |
maryma | Hi. I wanted to train model with different datasets based on a whole dataset, it is like k fold. My data is made based on custom datasets. Every time I have a list that contains the indexes that I want from my custom datasets. for example mylist is [0,1,2,3] that I need these indexes from whole dataset. My whole datase... | ptrblck | I’m not sure I understand the use case correctly, but it sounds as if you are looking for the torch.utils.data.Subset class, which would allow you to pass indices to it and only return samples from these indices. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.