user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
bqdeng | I’m using requires_ grad=true and false During repeated freezing and thawing, it is observed that a parameter v requires_ It is no problem for grad to change from true to false during training. Parameter v stops updating, but once it changes from false to true again, parameter v will always be updated, even if it requi... | ptrblck | Parameters can be still updated even if they are frozen if an optimizer with internal running states is used. E.g. Adam lazily initialized running estimates for each updated parameter and will use these to update the parameter even if their gradients are set to zero.
You could delete their .grad at… |
cat03 | import torch
x = torch.randn([100, 3, 28, 28])
device = torch.device("cuda:0")
x = x.to(device)I wanna trace the procedure tensor.to(device),research the function calls and how the cuda memory is allocated and tensor moved. But there are so many python tricks within the torch source code. I wanna ask where the Tensor.... | ptrblck | The .to() operation should eventually dispatch to any of the r.copy_(self, non_blocking) calls in_to_copyand then intocopy_kernel_cuda. |
Chedi_Morchdi | Hello, I’m trying to train this model:class Perceptron(nn.Module):def __init__(self):
super(Perceptron, self).__init__()
self.fc = nn.Linear(28,10)
self.relu = torch.nn.ReLU()
def forward(self, x):
output = self.fc(x)
output = self.relu(x)
return outputOn the MNIST dataset uploaded as follows:... | ptrblck | You are passing x again to self.relu instead of output, which makes the output non-differentiable, since no trainable parameters were used.
After fixing this as well as more issues in your code, which made it non-executable, the code works fine for me. |
Arupreza | Dear concern,I need help with calling the trained model and getting prediction results from it. I really appreciate any help you can provide.def get_prediction(model, dataloader):
with torch.no_grad():
model = model.to(device)
model.eval()
prediction = np.zeros(len(dataloader.dataset))
... | ptrblck | You are overriding the images tensor with its device attribute in:
images = images.device
and try to pass it to the model.
Pass the tensors instead and it should work. |
Tm4 | I need to use a pretrained model usingPyTorchVideolibrary that provides pretrained model for several models. The main problem of mine is that I could not find any information that for using the pretrained models for nference, what should be the spatial size of the input video/frame( I mean height and width)? To be clea... | ptrblck | Thetorchhub_inference_tutorialfrom the same repository might be a good starter and shows crop_size = 256. |
Kore_ana | I had a code that usedpin_memory = Trueand did transformations on images in the__getitem__of the dataset.I modified the__getitem__part of the dataset to be done on the GPU. This, as expected, when run withpin_memory=Truegave me the following error :-- Process 0 terminated with the following error:
Traceback (most recen... | ptrblck | Yes, you cannot ping CUDATensors, as pinned memory is located on the host to allow for a faster and asynchronous data transfer as also mentioned in the error message. |
BoKai | Here is the full error TrackBack图片914×299 12.5 KBThis happens in networkupdate()function, where it attempts to callforward()to compute Q values of the batch of state.Here’s my network and update() functionNetworkclass VDNNet(nn.Module):
def __init__(self,state_dim,rnn_hidden_dim,action_dim,num_layers) -> None:
... | ptrblck | Check the stacktrace as it should point to an invalid indexing operation. Once you’ve found which operation raises the error, make sure the values of the index tensor are in a valid range. |
janandd | I have modified thefclayer in a resnet18 model to output 4 logits in a classification problem. To test my model am using the following function.def test_model(model, test_loader, train=False):
with torch.no_grad():
_ = model.train() if train else model.eval()
labs_list, prds_list, test_corrects = []... | ptrblck | This could be expected if you are using e.g. batchnorm layers, which update their running stats in each forward pass in training mode. The eval() mode would then potentially return different outputs until the running stats converged. |
Aryan_Philip | I am running a U-net model, I am getting a Type Error when training the model, ``‘’'num_epochs = 30
#criterion = nn.BCEWithLogitsLoss()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-5)
scaler = torch.cuda.amp.GradScaler()
# Decay LR by a factor of 0.1 every several epochs
sch = ... | ptrblck | Check f_img and wf_img inside the __getitem__ method for valid objects, as I assume one of the transformations are raising this error.
Given the code, I guess self_wf_l is empty, the loop is never executed, and wf_img is still initialized as None. |
builder173 | We are using simulated training data and developed an IterableDataset for this task. When the dataset is wrapped with a standard DataLoader we can use it for training but suspect that the serial data simulation is severely rate limiting. (complex calculations) This seems to be the perfect scenario for using workers in ... | ptrblck | I don’t know (as I’m generally not using notebooks) but this might be an interesting idea to check.
Could you rerun the script in a terminal and see if the same output is seen? |
qiminchen | Suppose I have 4independentnetworks and only 1 optimizernetwork_1 = network()
network_2 = network()
network_3 = network()
network_4 = network()
optimizer = torch.optim.Adam(list(network_1.parameters()) +
list(network_2.parameters()) +
list(network_3.parameters... | ptrblck | Yes, independent computation graphs won’t have any effect on each other. |
VicFisher | I am establishing a model with pytorch and trying to use GPUs to test my model. However, there is an error occuring with the following warning:"/home/usrname/softwares/anaconda3/envs/torch12/lib/python3.7/site-packages/torch/cuda/init.py:83: UserWarning: CUDA initialization: CUDA unknown error - this may be due to an i... | ptrblck | Check if any other CUDA application is still executable and if not, reinstall the drivers as it seems your workstation is running into a setup issue. |
Vedant_Roy | I’m trying to figure out what settings were used to build a particular Pytorch wheel. Is there any way to tell?The reason is, I’d like to be able to build Pytorch from source, while closely following the official build configuration. | ptrblck | Thepytorch/builderrepository contains the code used to build the binaries so you might want to take a look at it. |
Sairam954 | Hi,I was trying to understand and mimic conv2D. However, I am not able to comprehend the output value of the conv2d.I am defining my input and also assigning the custom weights to the conv2d.Below is the code:import torch
m = torch.nn.Conv2d(1, 1, 3, stride= 1)
input = torch.randn(1, 1, 3, 3)
print(input.dtype)
inpu... | ptrblck | You are not considering the bias which will be added to your output activation. |
hubsiiiii | Hello,I wanted to ask whether there is a way to check if code is executed within awith torch.no_grad():block?I have the following problem: I am evaluating my model withinwith torch.no_grad():. However, my model executesloss.backward()in its forward pass since I want to adapt my deployed model on the unlabelled test dat... | ptrblck | torch.is_grad_enabled() should work:
print(torch.is_grad_enabled())
# True
with torch.no_grad():
print(torch.is_grad_enabled())
# False
with torch.inference_mode():
print(torch.is_grad_enabled())
# False |
hond86 | Hi all,I’m currently using the WeightedRandomSampler by passing a weights tensor with the same size of the number of samples, so one weight per sample and it’s working fine. I was wondering if there’s a way to specify weights per classes, since I’m currently working with millions of samples and the weights tensor is th... | ptrblck | No, I don’t think that’s currently possible. Note however, that 1 million float32 values take approx. ~4MB of memory, so unsure how much memory you would save in the end. |
SJoJoK | I got tensor C (of size N ) and tensor B (of size M), and I want to make a tensor A whichA[i]=B[C[i]],Actually I can use A = [B[x] for x in C], which create a list(of size N) of tensor(scalar) but not a tensor(of size N), and for-loop seems slow without vectorization.I think there must have a better way to do it, but i... | ptrblck | Direct indexing should work:
N, M = 4, 5
C = torch.randint(0, M, (N,))
B = torch.randn(M)
A_slow = torch.stack([B[x] for x in C])
A = B[C[torch.arange(C.size(0))]]
print((A_slow == A).all())
# tensor(True) |
harshitAgr | Hi, I tried to find the equivalent of torch.cuda.memory_reserved() for libtorch but could not find it. I tried torch::cuda::memory_reserved() but it gives error: ‘memory_allocated’ is not a member of ‘torch::cuda’ | ptrblck | You could try to use:
const DeviceStats stats =
c10::cuda::CUDACachingAllocator::getDeviceStats(device);
and then access its attributes:
stats.reserved_bytes;
stats.allocated_bytes;
... |
talmaashani2016 | Hi pytorch,I have a question regards a project that I am working on. Basically I am using this dateset to classify the age (Common Voice).I have use the provided train set and validate on the dev set, and then start testing on the test set based on the split provided in the kaggle website. When I use pretraiend models.... | ptrblck | Yes, the distribution will certainly have an effect on the final accuracy and often your would try to model the training and validation distribution after the “real world” set (i.e. the test set in your case). |
Jack_Shi | I’m trying to do some simple feature extraction using a pretrained ResNet50 on the CIFAR 100-20 dataset. It should be pretty straightforward, but after a certain number of batches the CUDA out of memory errors would appear. It seems very strange to me as something must have been accumulating across the batches and over... | ptrblck | You are storing the entire computation graph in each iteration in:
train_f.append(model(im).cpu())
If you don’t want to backpropagate through the model outputs, .detach() them before appending to the list. |
David1 | The linetorch.cuda.get_device_properties(0)gives me the output_CudaDeviceProperties(name='NVIDIA A100-PCIE-40GB', major=8, minor=0, total_memory=40396MB, multi_processor_count=108),buttorch.cuda.get_device_properties(0).total_memory / 1000000gives me the output42358.472704.Why is there a difference in ‘total memory’ he... | ptrblck | The difference would come from dividing by 1000 vs. 1024:
42358.472704 * 1000000 / 1024**2
# 40396.1875 |
TinfoilHat0 | I’d like to toggle off theshuffleattribute of a dataloader after certain point in my code. Can I do so without creating the dataloader again? | ptrblck | The shuffle argument determined which sampler will be created (RandomSampler or SequentialSampler as seenhere) and is not directly used as an attribute in the DataLoader. For this reason I would not recommend to try to replace the internal sampler, but to recreate the DataLoader instead. If you are… |
vogelstrauss | I am trying to add a softmax layer to avit-bmodel with 10 outputs.While it works callingtorch.softmaxdirectly on the model output, I do not get softmax output when adding the softmax as a fully connected layer:import torchvision
import torch
torch.manual_seed(1)
image = torch.rand(1,3,224,224)
model = torchvision.mode... | ptrblck | vit_b_16 doesn’t use a .fc module so you are creating a new attribute in:
model.fc = torch.nn.Softmax(10)
which is never used.
You could replace the model.heads.head with an nn.Sequential container containing the new nn.Linear as well as the nn.Softmax layer. |
ritas | Hi all,So, based on an existing implementation, I am trying to adapt it to my goal by changing the loss calculation, which is giving None for every grad after backward step.I believe the graph might be broken, based on similar topics I have read, but I am also in doubt if it has to do with the loss and the way the back... | ptrblck | You are detaching the computation graph by rewrapping the tensors as seen e.g. here:
return torch.tensor(np.stack(final_masks), requires_grad=True, device='cuda')
pred_label_bbox = torch.tensor(np.concatenate([item for sublist in final_labels.bbox_group_score.tolist() for item in sublist]).reshape… |
doyi_kim | How can I train a model with only fp16?the same operation with apex opt_level=“03” not mixed precision | ptrblck | The deprecated apex.amp opt_level="O3" was using “pure” FP16, so you can just call .half() on your model and input data in your training script. |
Debojyoti_Biswas | Hi,I am training a CNN model for extracting features for a dataset. I want to save all extracted features in a 2D tensor with the gradient information. The below code block is throwingtorch.cuda.OutOfMemoryError: CUDA out of memory. The batch size for the dataloader is 4 and the available GPU memory is 49GB.a= []
for ... | ptrblck | I assume you want to store all computation graphs to store the “gradient information”?
If so, then the large increase in memory would be expected. Detaching the tensor would reduce the memory usage, but won’t allow you to compute the gradients w.r.t. the previously used parameters anymore.
You cou… |
f3ba | Given a matrixA, say:A = torch.randn(5,5)What is the difference betweenA.TandA.t()? | ptrblck | From the docs:tensor.t:
Expects input to be <= 2-D tensor and transposes dimensions 0 and 1.
0-D and 1-D tensors are returned as is. When input is a 2-D tensor this is equivalent to transpose(input, 0, 1).tensor.T:
Returns a view of this tensor with its dimensions reversed.
If n is the nu… |
paulhofman | I am implementing a network and I have noticed a behaviour that I would like to understand.The following is my code; I removed all of the unrelated stuff.class ParameterisedNormal():
def __init__(self, mu, rho):
self.mu = mu
self.rho = rho
# self.sigma = self.rho
self.sigma = torch.l... | ptrblck | Your self.posterior_sample has an Autograd history and thus raises the error.
I’m not completely sure, but would assume you want to train self.mu and self.rho in both custom modules while the actual weight parameter is created via self.posterior.sample().
In your current code you are creating self… |
Ashish_Gupta1 | TypeError: expected TensorOptions(dtype=long int, device=cpu, layout=Strided, requires_grad=false (default), pinned_memory=false (default), memory_format=(nullopt)) (got TensorOptions(dtype=long int, device=cuda:0, layout=Strided, requires_grad=false (default), pinned_memory=false (default), memory_format=(nullopt))) s... | ptrblck | I don’t know where the code is coming from and if
But still not sure why i am not able to convert to floatTensor.
is a new issue or related to the device mismatch.
Your current code is unfortunately still not executable.
To debug further, check the stacktrace of the error message and narrow do… |
Ragnor | def compute_mask_loss(self, mask_predict, positive_gt_idx, box_predicts, targets):
mask_gt = targets['mask'].split(targets['batch_len'])
box_gt = targets['target'].split(targets['batch_len'])
loss_mask_predicts = list()
loss_mask_target = list()
for mg, bg, mp, pgi, bp in zip(mask_gt, box_gt, mask_p... | ptrblck | I don’t know, which operation is raising this issue, but it could be the indexing of mg_t, in case it has a single dimension as seen here:
mg_t = torch.randn(10)
mg_t[:, None, :, :]
> IndexError: too many indices for tensor of dimension 1 |
Giuseppe_Sarno | Hello,I am using a ResNet34 and retrained fully to recognize sines in a voice message. With relatively short train set I was able to achieve promising results (almost 100% accuracy - I split the signal in windows and then take the mel spectrogram images for training and inference - pretty standard approach).All this un... | ptrblck | Based on your description it seems the running stats of the batchnorm layers might not properly capturing the mean and stddev of your validation dataset which then causes the bad results. We have a few topics where similar issues were discussed and e.g. changing the momentum of the batchnorm layers … |
HamidGadirov | Hi, I have a customautograd.Functionfor correlation layer (that implements cost volume construction on cuda) in addition to the neural net that containsforwardwith its loss components. When I callloss.backward()there is an error:RuntimeError: function CorrelationFunctionBackward returned an incorrect number of gradient... | ptrblck | Yes, you need to return the gradient in your backward for all inputs in your forward. If some arguments do not have valid grads, return None for these. |
Yoo | I could not get through z.backward() as it showed “RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn”a0 = torch.FloatTensor([1]).clone().detach()a0 = a0.to(device)a0.requires_grad_ = True # create a leaf tensorz = a0 * 2opt = torch.optim.SGD([a0], lr = 0.01)z.backward()opt.step()I bel... | ptrblck | This call is wrong, since .requires_grad_ is a function and not an attribute, so you are overriding it.
Use:
a0.requires_grad_()
and it should work. |
IsCoelacanth | I’ve been seeing VERY high CPU utilization when using ToTensor in my transforms and its easily the slowest operation in my transformation compositions.system:torch: 1.8.1torchvision: 0.9.1been facing the same issue since 1.4.0, even tried building from source (tried 1.6.0 and 1.8.0)def to_tensor(img):
img = np... | ptrblck | Besides the additional checks for numpy array inputs, number of channels etc. in the torchvision implementations, you are not creating a contiguous output (TF.to_tensor does ithere) and would also see a performance penalty due to the needed copy after the permute operation.
You can check it via:
o… |
Jeff1 | Encounter Gradient overflow and the model performance are really weird.At about 1600 steps, the Mask language modeling loss became NaN, and after a few more steps everything crashed down to NaN. At first, I think it was a trivial coding problem and after a week of debugging I can’t really figure out how this occurs.Aft... | ptrblck | Note that it is expected to see invalid gradients in a few iterations when amp in float16 is used. If such an iteration is seen, the GradScaler will reduce its internal scaling factor and will skip the optimizer.step() call so that no parameters will be updated with these invalid gradients. It is n… |
Mkruger | Hey, I am not too sure what is going wrong with my code, however, I am using a categorical distribution and getting a fairly weird error and am uncertain as to why. I did look around for a while online but nothing I found seemed to explain what exactly this issue was and how to get around it.The error I am getting is a... | ptrblck | Based on the error message it seems the actor is creating NaN outputs after a few iterations of training. Are you seeing an increase in the value range of its output during training, which could then overflow after a while? |
cq_chu | when I read the cpp code of pytorch, some reference meterial are listed there but I cannot find, such as:pytorch/Dispatcher.h at master · pytorch/pytorch (github.com)and I cannot find theNote: Argument forwarding in the dispatcher. So where can I find these reference meterial? | ptrblck | Copy/pasting the posted text into the GitHub search points tothis section. |
SCUTVK | Our school’s slurm server’s device is v100 with cuda 10.1. Lack of root user, I can not upgrade nvidia driver. The code able to run successfully in my pc(tesla p4 with cuda 11.6) can not run in server. Besides, I have tried kinds of torch versions and cuda version (<=10.1), but it always hangs when running model.to dev... | ptrblck | Based on your output 3/4 GPUs seem to work while GPU0 reports an uncorrectable ECC error, so you might want to check the RAM of this device. |
Ziv_Tzur | hey!I’m trying to train a model based on BERT pre-trained model with two outputs for category and subcategory.problem is the model is not learning and I get the same statistical results every epoch…the training loop:for epoch in range(1, epochs + 1):
if epoch > 1:
train_dataloader = classifier.create_dynami... | ptrblck | Your model’s parameters don’t get any gradients and are not updated since you are detaching the computation graph by rewrapping the output tensor:
products_loss = criterion(torch.tensor(outputs[0], requires_grad=True), b_products)
actions_loss = criterion(torch.tensor(outputs[1], requires_grad=True… |
astra1234567 | Hi everyone ! Can someone explain me how use batch with RNN ?It is basic model from documentation:class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size + hidden_size, hidden... | ptrblck | This RNN tutorialmight be a good starter as it walks you through a classification use case. |
Xiaohao_Lin | Hi everyone, I am new to pytorch. And I would like to ask for resources/guides that teach you to transform ideas into code. Now, I get a bit overwhelmed when I try to implement complex neural network architectures, due to lack of experience, and can get quite frustrated. When I read others’ code, which are mostly spars... | ptrblck | Additionally to@srishti-git1110’s advice, you could also check some courses such asFastAI. |
Xiaohao_Lin | Dear all,I have two projects in Pycharm, both using the same interpreter. I have checked and ensured that the cuda, cuda driver and pytorch (GPU version) versions are right.Nvidia GEFORCE RTX 2080 TICUDA:DRIVER VERSION: 516.94cudatoolkit: 10.2python: 3.8The first project is able to use cuda, and torch.cuda.is_available... | ptrblck | Your IDE might use a different virtual environment or could set some env variables (e.g. CUDA_VISIBLE_DEVICES to a wrong values etc.), so check your PyCharm setup and which envs are used. |
emma_ng | Hi, sorry for the naive questions, I’m just started learning.I have a custom dataset to load image and its label, which is used with DataLoader with shuffle=True. My questions are:When DataLoader shuffle the batches, do they shuffle both images and labels or just images? Because the answer herehttps://stackoverflow.com... | ptrblck | That’s not completely right, since the answer correctly pointed out that the shuffled predictions (created via shuffling the inputs via the DataLoader) are compared to the unshuffled targets (which were not created by the DataLoader):
train_accuracy = sum(train_preds.argmax(axis=1) == y_train)/len… |
vince62s | Can someone explain why this in the code below ?as is with slen=24, dim=8, I have out=out2if I change slen to 25 or more, or dim to 9 or more, then it does not work, out and out2 are not equal.can’t get why.import torchimport timedef tile(x, count):“”"Tiles x on dimension 0 count times.“”"out_size = list(x.size())out_s... | ptrblck | Using torch.equal with floating point numbers is not a good idea due to the limited floating point precision and the expected small errors caused by a different order or operations.
If I change slen to 25 and dim to 9 I see an .abs().max() error of tensor(9.5367e-07) which is expected for float32. |
Miguel_Campos | Hello all,I need to train 3torch.nn.Moduleindividually. For this, instead of using 3 separatedtorch.optim.AdamI am concatenating their parameters in this way.models = torch.nn.ModuleList([net1, net2, net3])
optimizer = torch.optim.Adam(models.parameters(), lr=1e-3)As I need to train 3 models, I need to use 3 inputs for... | ptrblck | It depends on the use case and how each model should be updated. I.e. if you want to update models separately based on some conditions, I would create 3 separate optimizers and call them explicitly. On the other hand, if you are using a standard training loop where all models are used, get gradients… |
NoWay2Guess | Hi, I am wondering if it is possible to place self.fc = nn.Linear(hidden_size, x.shape[1]) in the forward(self,x). Because I use Time Series cross validation to split the dataset, which means the seq_len for train_dataset changes over time.class LSTM(nn.Module):definit(self, input_size, hidden_size, num_layers, p):supe... | ptrblck | You could recreate a module in the forward method but would then use this randomly initialized layer which won’t be trained which sounds wrong.
A common approach to allow for variable input shapes would be to use e.g. adaptive pooling layers which are creating a defined shape as their output. |
Jimut_Bahan_Pal | So, I was implementing a function in Pytorch, and was unable to compute the gradient of input vectorinput_vec. Here decoder is a normal autoencoder’s decoder, device is cuda, input vector isinput_vec = Variable(torch.zeros((1,16,16,16)), requires_grad = True)output is an image inimg = dataiter.next()[0].reshape((1,3,1... | ptrblck | In your latest notebook you’ve changed the logic and are now indexing the input_vec.
Access the .grad attribute first, then index it:
with torch.no_grad():
dx = input_vec.grad[0,1,1,1]
print("DX = ",dx)
DX = tensor(-0.0004, device='cuda:0') |
Elias_Vansteenkiste | Which template was used to build this PyTorch forum?I see it here and there around the web, e.g forums.fast.ai is using the same template. | ptrblck | The forum is based onDiscourse. |
sbht_sbht | I’m trying to add scheduler ReduceLRonPlateau, following instructions from documentation, but I get error “TypeError: step() missing 1 required positional argument: ‘metrics’” when I run itCan you please tell me what should I pass to the optimizer?learning_rate = 0.0001
num_epochs = 300
n_total_steps = len(train_loader... | ptrblck | The step() function of ReduceLROnPlateau expects a metric value as described in thedocs, which is used to determine if the learning rate should be decreased or not. |
Saswat | I’m working on a classification problem (100 classes) and my dataset has a huge class imbalance. To tackle this, I’m considering using torch’sWeightedRandomSamplerto oversample the minority class. I took help fromthis postwhich seemed pretty straightforward. Only concern with this is the nature of my dataset.In my case... | ptrblck | Since each sample contains multiple classes, I don’t think you can easily add a weight to it, since again each index will be drawn using the weight. You might need to apply a more advanced technique as describedhereor just return samples containing a single target. |
1chimaruGin | I haveModuleList(
(conv1): ConvKXBN(
(conv1): Conv2d(32, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
(conv2): ConvKXBN(
(conv1): Conv2d(64, 64, kernel_size=(3... | ptrblck | Creating a list directly should work:
modules = nn.ModuleList([
nn.Linear(1, 2),
nn.Linear(2, 3),
nn.Linear(3, 4)
])
print(modules)
# ModuleList(
# (0): Linear(in_features=1, out_features=2, bias=True)
# (1): Linear(in_features=2, out_features=3, bias=True)
# (2): Linear(in_featur… |
henrique | Hi guys,Is there a way to change the default extension path from ~/.cache/torch_extensions/ to something else?I couldn’t find anything on the documentation.Thank you, | ptrblck | You should be able to set this path via TORCH_EXTENSIONS_DIR. If this env variable is not set, the (system) default will be used. |
Giuseppe_Sarno | Hello,I am building a Sound classifier and using Torchaudio. The Wav file is loaded and then transformed this way:mel_spectrogram = torchaudio.transforms.MelSpectrogram(
sample_rate=SAMPLE_RATE,
n_fft=1024,
hop_length=512,
n_mels=64
)
size=224
transform_spectra = T.Compose([
mel_spectrogram,
T.R... | ptrblck | It depends on your use case, but generally normalizing the data helps in model convergence.
The Normalize transformation subtracts the passed mean and divides by the std so that the samples have a zero mean and unit variance, which helps even more than a normalization via scaling.
I would recomme… |
111466 | Example codes as followed:import torch
T = torch.rand(3,3)
print(T.H)
print(T.T)And the corresponding output:tensor([[0.9100, 0.4052, 0.8227],
[0.9101, 0.5563, 0.8068],
[0.5961, 0.8708, 0.0686]])
tensor([[0.9100, 0.4052, 0.8227],
[0.9101, 0.5563, 0.8068],
[0.5961, 0.8708, 0.0686]])
te... | ptrblck | From the docs:Tensor.T:
Returns a view of this tensor with its dimensions reversed.
If n is the number of dimensions in x, x.T is equivalent to x.permute(n-1, n-2, ..., 0).Tensor.H:
Returns a view of a matrix (2-D tensor) conjugated and transposed.
x.H is equivalent to x.transpose(0, 1).c… |
JYIJ_94 | I was trying to train a model and getting the following error. I am confused why I am getting this error.And the shape of all the variables are:Data shape: torch.Size([321, 20, 14])Mask shape: torch.Size([321, 20])Decay shape: torch.Size([321, 20])Redecay shape: torch.Size([321, 20])The code is given below -data = T.... | ptrblck | Python and PyTorch use 0-based indexing so a tensor with a shape [batch_size, 20] can be indexed with indices in [0, 19] in dim1 while you are passing 20:
x = torch.randn(6, 20)
x[:, 19] # works
x[:, 20] # fails
# IndexError: index 20 is out of bounds for dimension 1 with size 20 |
rfmiotto | Hi,I am modifying pre-trained models so that they accept 2 input images. I tested my code with thevgg11_bn,resnet50andvit_b_16nets and all of them worked pretty well. However, when using a similar approach with theinception_v3, I am getting the following error:RuntimeError: Given groups=1, weight of size [32, 6, 3, 3],... | ptrblck | You are right and I am able to reproduce the issue when using a pretrained model (my previous code snippet used a randomly initialized model).
The issue is caused by the built-in transformation, which normalizes and slices the first three channels.
Use model = models.inception_v3(pretrained=True, … |
SashimiDelicieux | I wanted to make a function that take any torchvision model as argument and output the same model with a different output size, but I realized that a simple but annoying problem prevented me from directly doing so : The prediction layers of those models have different names. For example, the last layer of Resnet and In... | ptrblck | I guess it would have been better to use a specific naming convention, but since the models were implemented in different releases, by different authors, each with (slightly) different coding styles, the layer names might differ and your check sounds like a good approach to check for the classifiers… |
Estabi | Hello,I am new to deep learning and using pytorch.I have gone through some codes and I always see examples of weight initialization.My questions are -When do I initialize weights and what is the intuition behind weights initialization for neural networks.Does random seeding have anything to do with weights iniitializat... | ptrblck | A proper weight initialization allows models to converge faster or to converge at all. A custom weight initialization is used if the default built-in initialization isn’t working for your use case.
Yes, since random values are usually drawn from a specific distribution, which use the pseudorandom… |
fabian_schutze | I occasionally like to inspect the gradients of a model but since I use amp I do not know anymore how to do that. Can you kindly help me how to obtain the scaled gradients?I usually do:grads = []
for p in model.parameters():
if (p.grad is None) or (not p.requires_grad):
c... | ptrblck | You can access the gradients in the same way as shown in your first approach after calling unscale manually as also shown in your second code snippet. |
Yoo | Suppose I have loss = w1loss1 + w2loss2, where I defined two learnable weights for each lossWeightloss1 = torch.FloatTensor([1]).clone().detach().requires_grad_(True)
Weightloss2 = torch.FloatTensor([1]).clone().detach().requires_grad_(True)
opt1 = torch.optim.Adam(model.parameters(), ...)
opt2 = torch.optim.Adam([Wei... | ptrblck | Yes, all trainable parameters will receive gradients which you could access via their .grad attribute. Using retain_graph=True is not needed in this case. |
Fra_Zuppi | Hi Guys,I hope you are doing great, I am well aware of all the github issues (RTX3090 performs no better than 1080ti · Issue #50328 · pytorch/pytorch · GitHub,Anyone has use it in 3090? It seems been slow... · Issue #276 · traveller59/spconv · GitHub, etc) about this topic.I’ve tried a lot of different containers from ... | ptrblck | Thanks for sharing. You could also check the performance for mixed-precision training (in channels-last memory layout), which might also show more speedups. |
Anna_Inberg | Good afternoon!I have questions about the following tutorial:https://pytorch.org/tutorials/beginner/data_loading_tutorial.htmlI have a similar dataset (images + landmarks). I’ve built the custom dataloader following the tutorial and checked the types of dataloader components (torch.float64 for both images and landmarks... | ptrblck | If the strings are not found anymore, images = images.to(device) wouldn’t be failing with AttributeError: ‘str’ object has no attribute 'to’, would it?
In case it’s still failing you, it seems you are hitting these issues now:
the data has definitely the correct dtype in the __getitem__ before th… |
Solaris001 | Hi everyone, just recently started to implement an autoencoder model using pytorch. My data is cleaned and ready to get worked with. For the start, I followed a tutorial on autoencoders in pytorch and could not find out where the error is coming from. It’d be great if anyone could help!data_loader = torch.utils.data.Da... | ptrblck | Based on the error message it seems your input data has 20 elements while you are expecting samples with 784 features. If your inputs are expected to have 20 features only, change the in_features value of your first linear layer to 20 too. |
Humza_Sami | I am trying to reproduce thiscodesnipped from PyTorch.When I pass the input to the model it returns the following warnings. Will it effect my outputs ?Warning[MAdd]: Dropout is not supported![Flops]: Dropout is not supported![Memory]: Dropout is not supported![MAdd]: LayerNorm is not supported![Flops]: LayerNorm is not... | ptrblck | In that case I would recommend to try to update to the latest release of torchinfo and to check if these warnings are still raised. If so, you might want to create a GitHub issue in their repository. |
rob-miller | Please pardon my pre-deep-learning graduate training. I am trying to understand whether I have a bug, or what the theoretical reason(s) is(are) for the behavior I am seeing (and suggestions for improvements).I am exploring multiple models and expect to see overfitting as I add more layers, but instead the deep nets ju... | ptrblck | TheResNet paperdiscusses the training issues with deeper models and also shows the same effect in Figure 1 directly which shows the deeper model to have a higher training error while the opposite might have been the expectation due to the increase in model capacity. |
grid_world | For PyTorch 1.12 and Python 3.10, I have a Convolutional Variational Autoencoder which accepts train, target sample as (90, 90, 3), (90, 90, 3). The sample is transposed to be (3, 90, 90) and then passed to the network as follows. I have access to 4 NVIDIA GTX TITAN X cards and I am trying to use all of them with the c... | ptrblck | In your shape_computation method you are creating a new x tensor from randn on the CPU and are overriding the old activation tensor:
x = torch.flatten(torch.randn((256, 2, 2)))
Remove this line of code or flatten the previously computed x tensor and it should work. |
JimW | I have a network that can generate predictions with shape [8, 32, 400]. The first number “8” is simply the batch size, and the 2nd number “32” is the length of my sequence, and the 3rd number “400” is the total number of classes for each element in my sequence.Basically, I want to perform per-element classification for... | ptrblck | You could use nn.CrossEntropyLoss and pass the model outputs as [batch_size, nb_classes, seq_len] to this loss function while the targets are fine in[batch_size, seq_len]. Make sure to .permute the model output to create the desired shape. |
Sam_Lerman | Right now,__getitem__implements 1 index at a time. Is it possible to have theDataLoaderfeed it multiple indices for retrieval at a time? | ptrblck | You could use a BatchSampler as describedhere. |
ximing | Based on what I know, in the Conv2D, padding has two value: 0 and 1. 0 equals to “valid” which is no padding while 1 equals to “same” which means add 0 as padding and make the output size the same as input size.However, when I tried using ''valid" and “same” in a 2D convolutional layer passing a input (36464), I found ... | ptrblck | That’s not generally true since the padding argument accepts different values and the “same” or “valid” option also depends on the kernel size, the stride, and other arguments.
In your use case you are using a kernel size of 1 which yields the same output size without any padding. |
nwe_lay | when I run this code on google colab. The following error occur.Please help me.if cuda:state_dic=torch.load(model_path[0])encoder.load_state_dict(state_dic)state_dic2=torch.load(model_path[1])decoder.load_state_dict(state_dic2)AttributeError: ‘list’ object has no attribute ‘seek’. You can only torch.load from a file th... | ptrblck | It seems model_path[0] and/or model_path[1] return a list instead of a file path or a buffer. |
XHH | Hi,My code is simple and as follows:import torchdevice = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)m = torch.nn.Linear(20, 30).to(device)input = torch.randn(128, 40).to(device)output = m(input)print(output.shape)In this code, it is expected to return an error due to shape mismatch on gpus. However, it... | ptrblck | Could you update PyTorch to the latest stable or nightly version, please?
This was a known issue which was fixed in a patch release a while ago if I’m not mistaken. |
fabiozappo | Hi everyone, this is my first post here so don’t be too mean please.I am struggling with a weird problem that consumes the double cuda memory of what I expected.Here is a quick snippet to replicate the problem:from torchvision.models import resnet50
import torch
# This loss consumes a lot of memory
class ZeroLoss(to... | ptrblck | Your ZeroLoss creates a new tensor which is not attached to the computation graph. Calling backward will not compute any gradients for the parameters of the model and will thus also not clear the computation graph and will not delete the intermediate forward activations needed for the gradient compu… |
JamesDickens | I’m thinking of applying the transformtorchvision.transforms.ColorJitterto a video,but I need to make sure the same transform is applied to each frame.I have a function like:#vid_t of shape [batch_size, num_channels, num_frames, height, width]
def rgb_vid_color_jitter(vid_t, brightness=0.4, contrast=0.4, saturation=0.4... | ptrblck | The transformations should be applied on each image separately and you could check it quickly by applying your code onto a static input tensor (e.g. just torch.ones). If you need to apply the same “random” transformation on multiple inputs you could use the functional API and create the random param… |
lukecage | Hi all!I have been trying to make Pytorch work with NVIDIA A100 - 80GB GPU .Following is thenvidia-smioutput :+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.203.03 Driver Version: 450.203.03 CUDA Version: 11.0 |
|-------------------------------+-----------------... | ptrblck | Try to disable MIG and rerun your script. |
jiapei100 | I successfully builttorchaudiobycmake, but it looks when I tried toTORCH_CUDA_ARCH_LIST="8.6" python setup.py build, it seemsmkl libraries are NOT found, which I’m sure are underLD_LIBRARY_PATH.Can anybody help please?➜ audio git:(main) TORCH_CUDA_ARCH_LIST="8.6" python setup.py bdist_wheel
-- Git branch: main
-- Git ... | ptrblck | LD_LIBRARY_PATH will search for shared libs during the runtime, so try to use LIBRARY_PATH. |
Chedi_Morchdi | I’m trying to get the gradient of a certain layer of my model, can somebody explain the difference between these 2 approachs ?1st approach is:current_grads=[ ]for param in net1.conv_layer[0].parameters():\indent current_grads.append(param.grad.view(-1))current_grads=torch.cat(current_grads)2nd approach is:current_grads... | ptrblck | The first approach will iterate all parameters of the layer (which is often the weight and bias parameter), will flatten the corresponding gradients, and will concatenate them to a single tensor:
layer = nn.Conv2d(1, 3, 3)
out = layer(torch.randn(1, 1, 24, 24)).mean()
out.backward()
current_grads … |
sev777 | I use a hook to store gradient information when I test, but this will cause CUDA out of memory, how do I release the information in the hook? | ptrblck | I assume storing the gradient information increases the memory usage and you are thus running OOM. You can delete tensors via del tensor. |
Samuel_Lewis | Hi,I am struggling to wrap my head around using the data loader.Currently I have a data loader which returns a dictionary for x1, x2 objects.I can call x1, x2 = next(iter(dataloader), which returns the two dictionary objects.However, my train script it is set up to run the following.for x1, x2 in dataloader:x1 = x1[‘im... | ptrblck | That doesn’t look right and you should iterate the DataLoader directly:
dataset = TensorDataset(torch.randn(10, 1), torch.randn(10, 1))
loader = DataLoader(dataset, batch_size=1)
for x, y in loader:
print(x, y)
Could you post the Dataset definition, please? |
RuoyuGuo | NetA = Model()
NetB = Model()
optimizer = optimizer.Adam(list(NetA.parameters())+ list(NetB.parameters))
scheduler = scheduler.somescheduler(optimizer)
for epoch in range(epochs):
NetA.forward()
NetB.forward()
#Calculate Loss...
optimizer.zero_grad()
Loss.backward()
optimizer.step()
... | ptrblck | I would probably use paramA.copy_(paramB) in a no_grad context, but it seems also loading the state_dict works as the parameters are still updated independently:
NetA = nn.Linear(1, 1, bias=False)
NetB = nn.Linear(1, 1, bias=False)
optimizer = torch.optim.Adam(list(NetA.parameters())+ list(NetB.par… |
zezimabig | Dear to whom it may concern,I have tried to install Pytorch on my instance but found that it is too big of a file (at ~700MB). Is there a minimal version of Pytorch (smaller size) that I could install for the main purpose of functioning in the production line (requires a few functions)?Below are the only imports that w... | ptrblck | Sure, you can create this feature request on GitHub and depending on the interest, someone might want to work on it. However, note that I don’t see which subset should be built if you depend on import torch directly. |
israRe | Hi, every one.I’m reading the docs in PyTorch vision but what is the meaning ofTop-1 errorandTop-5 errorpresent in thispage. | ptrblck | You would increase the Top-1 error if the “top-1” prediction, i.e. the prediction of your model with the highest score, does not match the target.
On the other hand, you would increase the Top-5 error if none of the “top-5” predictions, i.e. the 5 predictions with the highest score, matches the tar… |
JamesDickens | I’m reading the documentation for the Adamw optimizer. In the updates for the m_t and v_t terms, the beta values have a superscript of t. I thought these beta values are fixed. Any insights what this superscript means much appreciated. | ptrblck | Check thepaperreferenced in the docs in Algorithm 2:
beta_1^t is taken to the power of t
beta_2^t is taken to the power of t |
qiminchen | I have a model defined asclass Model(nn.Module):
def __init__():
super(model, self).__init__()
self.conv_0 = nn.Conv2d()
self.conv_1 = nn.Conv2d()
self.conv_2 = nn.Conv2d()
self.make_coordinates()
def make_coordinates(self):
xs = torch.arange(512, device="c... | ptrblck | self.coords will be on the CPU since you are explicitly creating its inputs via device="cpu" and since none of these tensors are a registered buffer or parameter and thus won’t be moved to the GPU via model.to(). |
guu | Hello,I’d like to ask, with my dataset and machine, if it is normal to see out of memory or if I might have some programming issue.RuntimeError: CUDA out of memory. Tried to allocate 260.00 MiB (GPU 0; 15.78 GiB total capacity; 14.02 GiB already allocated; 198.19 MiB free; 14.13 GiB reserved in total by PyTorch)I using... | ptrblck | Based on your description the OOM might be expected, since your spatial input size increases by 4x in the number of pixels. Did you check the used peak memory for the working solution using the 512x512 images?
Based on this value, you could try to estimate the memory usage if the number of pixels i… |
aditya-hari | I’m trying to understand how exactly TripletMarginLoss is implemented in PyTorch and while I get most of it, I am unable to figure where exactly epsilon fits in | ptrblck | The eps value is used in the pairwise_distance calls as seenhere. |
Maxim_Stuff | Hello, I’ve got a following error:RuntimeError Traceback (most recent call last)
<timed exec> in <module>
/var/folders/m8/5njk8q3d30v78xxjn6n610km0000gn/T/ipykernel_12796/1284205556.py in train(model, opt, n_epochs)
63 for epoch in range(n_epochs):
64 ... | ptrblck | The shape sounds wrong, since you were previously using a batch size of 32 based on your code.
You should also not use a linear layer in the features pat without flattening the activation unless you really want to apply the linear layer sequentially only on the width dimension of the forward activa… |
ryanbty | Letx = tensor([[[[0, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1]]]])if we do x.nonzero() we getx.nonzero() = tensor([[[0, 0, 0, 1],[0, 0, 0, 2],[0, 0, 0, 3],[0, 0, 1, 0],[0, 0, 1, 1],[0, 0, 1, 2],[0, 0, 1, 3],[0, 0, 2, 0],[0, 0, 2, 1],[0, 0, 2, 2],[0, 0, 2, 3],[0, 0, 3, 0],[0, 0, 3, 1],[0, 0, 3, 2],[0, 0, 3, 3]])... | ptrblck | Your desired output format won’t work as it’s a nested tensor. However, you could flatten x to get at least the desired output values in a flattened shape:
x.view(-1).nonzero()
# tensor([[ 1],
# [ 2],
# [ 3],
# [ 4],
# [ 5],
# [ 6],
# [ 7],
# … |
aRI0U | Hi. I have the model that I sometimes train on a single GPU and sometimes on multiples GPUs. In its architecture there are batchnorm’s so I decided to usemodel = SyncBatchNorm.convert_sync_batchnorm(model)to avoid performance loss when training on Multi-GPU.However, the thing is that now when I want to train on one GPU... | ptrblck | Try to use torch.distributed.is_initialized() in a condition. |
Fst_Msn | Given a 2d zeros tensor to fill:res = torch.zeros((4, 3))a 2d tensor with the values to fill and the same dim 0 of res (e.g. 4, 5):fill = torch.tensor([
[0.1, 0.2, 0.3, 0.4, 0.5],
[0.6, 0.7, 0.8, 0.9, 1.0],
[1.1, 1.2, 1.3, 1.4, 1.5],
[1.6, 1.7, 1.8, 1.9, 2.0],
])and an index tensor of the same shape of fill (4, 5) and ... | ptrblck | scatter_ should work:
res = torch.zeros((4, 3))
fill = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5],
[0.6, 0.7, 0.8, 0.9, 1.0],
[1.1, 1.2, 1.3, 1.4, 1.5],
[1.6, 1.7, 1.8, 1.9, 2.0],
])
index = torch.tensor([[0, 2, 2, 2… |
Sudu | Hello, I am attempting a binary segmentation problem. I am confused about what output dimensions are expected for loss functions. ForBCELoss()should the network and labels both have a shape ofnBatchx1xhxw? And forCrossEntropyLoss()should the network output benBatchx2xhxwand label benBatchxhxw? It would be great if some... | ptrblck | Yes, your explanation is correct and the difference would be:
nn.BCEWithLogitsLoss treats your use case as a binary segmentation use case directly where the labels indicate the negative (0) or positive (1) class. “Soft” labels are also allowed, but it depends on your actual use case how you want … |
Megh_Bhalerao | Hello,The following is a minimum working example of the problem that I have come across:import torch
import os
import numpy as np
import random
torch.use_deterministic_algorithms(True)
os.environ["CUBLAS_WORKSPACE_CONFIG"]=":16:8"
os.environ["CUBLAS_WORKSPACE_CONFIG"]=":4096:8"
import torch.nn as nn
seed = 0
torch.ma... | ptrblck | PyTorch uses float32 (i.e. floating point numbers stored in 32 bits) as its default and allows users to use also wider types with more bits (and thus range and precision) such as float64 as well as smaller types such as float16 or bfloat16.
E.g. take a look atthis Wikipedia article about float32 w… |
awais980 | Is it possible to train few neurons in last fully connected layers of any mode in PyTorch? For example, if the last two layers are 256,128 in size and output has 10 nodes. Then, is it possible to train last 128 neurons of 256-size layer, last 64 neurons in 128-size layer and all 10 neurons of the output? | ptrblck | You could manually zero out the weights which you do not want to train.
Note however, that weight decay (or other regularization terms) could still update parameters with a zero gradient. |
qiminchen | Hi, I happened to find this repo (`flip` when sampling features from plane · Issue #4 · ChrisWu1997/SingleShapeGen · GitHub) and was having questions about flipping the coordinates in F.grid_sample. Here is the code snippet from the issue. Is this a bug or am I missing something? Whyflip(-1)solve the issue in this case... | ptrblck | I guess the confusion might arise from the standard “x/y” coordinate system in image processing and the “row/column” layout used for general tensors/matrices as explained here:[SOLVED]Torch.grid_sample? - #13 by ptrblck |
milan_kalkenings | For adversial training, I want to perturbate word embeddings. Oversimplified, the problematic part of my code looks like this:optimizer.zero_grad()
emb = embedder(token_ids)
emb = Variable(emb, requires_grad=True)
logits = cls_head(emb)
loss = loss_func(logits, target)
loss.backward()
optimizer.step()
print(emb.weight... | ptrblck | emb is an intermediate forward activation and doesn’t have a weight attribute.
If you want to check the gradient from this activation, call .retain_grad() on it:
embedder = nn.Embedding(10, 10)
cls_head = nn.Linear(10, 10)
token_ids = torch.randint(0, 10, (10,))
loss_func = nn.MSELoss()
emb = em… |
qsj287068067 | I want to add gradient accumulation feature to my DDP + amp training program for constant batch size when training large models. The model is wrapped bytorch.nn.parallel.DistributedDataParallel.Refer to2nd case ofalbanD’s reply;pytorch document ofamp working with gradient accumulation,I implemented my code likeoptimize... | ptrblck | No, it shouldn’t as given in the amp tutorial. TheGradScaler.stepfunction calls optimizer.step() internally after unscaling the gradients and making sure no Infs/NaNs were found. |
Z_Huang | I am thinking to ensemble 2 UNets into one ensemble model.Inspired by this linkCustom Ensemble approach - #4 by ptrblck, I think I might know how to do that. However, for UNet the last layer is a different story.The output of each UNet are in different format as mentioned in the above link.Let’s say the input is:x = to... | ptrblck | @rasbtexplains some ensemble methods inthese slideswhere a few of these might be easily applicable to your use case e.g. via majority or soft voting. You could also take a look at some sklearn modules e.g.VortingClassiferand try to use these.
No, it doesn’t stop the training or backpropagatio… |
Tm4 | I have a tensor with the size of(batch_size= 16,channels= 192,H=7,W=7). I want to decrease the number of channels to 160 channels but having the same height and width. Themyclass is the main class that I use for running the experiment and thex(the mentioned tensor), is the input to themyclass:class MyConv2d(nn.Module):... | ptrblck | The error message doesn’t point to the kernel size and padding, but to a mismatch in the number of input channels. Your current input seems to have 192 channels while 768 are expected. Use in_planes=192 and it should work. |
cxv0519 | Literally, is there any way to profile backward time of relu layer automatically? (I mean by code itself, not by torch profiler)I want to know elapsed time for backward computation at ReLU layer.I’m using ReLU with in-place false.but with just code like below# forward
start = time.time()
output ... | ptrblck | To call backward() on an output tensor a computation graph with trainable tensors must be created. Set .requires_grad_(True) on the input and it should work. Also, synchronize the GPU before starting the timers, too. |
Alphonsito25 | Hi!I would like to randomly split my dataset between training and test, but also I want to make it balanced in my 2 classes, and save this split to future trainings.This is because I want to perform several trainings with different pretrained models under the same conditions (test images always the same in each trainin... | ptrblck | You could try to extract the targets directly from the CSV file based on your description or alternatively you could also iterate your dataset once and store the target in a new numpy array. |
ryanbty | What to do when there are multiple values in the kernel that equals to the max? For example, for these values when we use torch.argmax :torch.tensor([[1., 1.],
[1., 1.]])The max is simply 1. What should max indices look like? should it be True’s foralloccurrence of max:torch.tensor([[ True, True],
[ True... | ptrblck | Yes, you should be able to get the max. value and get the indices of all duplicates afterwards:
x = torch.ones(1, 1, 2, 2)
x[0, 0, 0, 1] = 0.
max_val = x.max()
print((x == max_val))
# tensor([[[[ True, False],
# [ True, True]]]])
print((x == max_val).nonzero())
# tensor([[0, 0, 0, 0],
… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.