user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
ArtmZhou | hello๏ผiโm a beginner of pytorch.today,i run my code with CIFAR10 dataset,but this error happended!but,when i use another oneโs computer to run it,it goes well. i dont know whether if itโs my pytorch environmentโs problem.also,i find when i use โconda listโ in anaconda prompt ,it shows cudaโs version is 10.0ๅพ็1203ร26 2.... | ptrblck | I cannot reproduce this error locally using bool tensors for class_correct or class_total.
However, based on your code I assume that class_correct is a list containing BoolTensors.
If thatโs the case, you could cast these tensors to float() before dividing them by class_total[i]. |
zhi_Li | I found a case InCUDA Automatic Mixed Precision examples โ PyTorch master documentation.If your network has multiple losses, you must call [scaler.scale] on each of them individually.โฆscaler.scale(loss0).backward(retain_graph=True)scaler.scale(loss1).backward()It seems that the gradients back propogated from the two lo... | ptrblck | Ah OK, thanks for the follow-up.
Yes, the scaler will unscale the gradients before accumulating them. |
bulb | Please look at the network code below:class CNN(nn.Module):
def __init__(self, vocab_size, embedding_dim, n_filters, filter_sizes, output_dim,
dropout, pad_idx = 0):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.convs = nn.ModuleLi... | ptrblck | Thanks for the information.
Iโm able to sent the model to the GPU using your setup on a Windows machine, so I would recommend to restart the machine just in case?
Also, could your GPU be fully used at the moment or did you make sure itโs empty? |
wangmyde | I create a custom image data set like:from torch.utils.data.dataset import Dataset
from PIL import Image
import torchvision
from torchvision import datasets, models, transforms
import numpy as np
class MyCustomDataset(Dataset):
def __init__(self, df, transforms=None):
"""
Args:
df (pa... | ptrblck | The 16 classes should be mapped to the range [0, 15], while your target uses sparse values between 0 and 45.
You would have to remap these target values, as they are used to index the model output to calculate the loss. |
vainaijr | What is the fastest way to compare all the elements of a matrix, with all other elements of the matrix?for example,x = torch.randn(5, 5)
y = x.unfold(0, 3, 1).unfold(1, 3, 1)now if I want to compare every element in these 9 3x3 blocks, with every other 8 elements, without using for loop, then how do I do this? | ptrblck | Thanks for the update.
I came up with another approach, but you will only see a slightly performance benefit for larger sizes.
Your code seems to be alright for this workload:
def fun1(a, b):
c = torch.cat((a, b), dim=0)
idx = c.nonzero()
res = torch.zeros(c.size()[1:])
res[idx[:,โฆ |
jako | Hi everybody!I am new to PyTorch and attempting to implement and train aVGG16-based FCN8s architecture for binary semantic segmentationfrom scratch, based on the FCN paper by Long et al. I have successfully done so in Keras+TF before and I canโt figure out why the loss is not decreasing in this case (constantly around ... | ptrblck | One issue with the code is that you are re-initializing some layers on your forward method.
You would usually initialize all modules in the __init__ method and assign them to internal attributes, as you have done with self.block1 etc.
However, all nn.Conv2d and nn.ConvTranspose2d calls in your forโฆ |
bulb | Iโm new to NLP. Iโm trying to use the Torchโs nn.Embeddings and nn.RNN().I noticed a strange thing while doing this. For some reason, my model trains on CPU. But I cannot send it to GPU for training.Here is the Model architecture:#singlelayer RNN.import torch.nn as nnimport torchclass RNN(nn.Module):definit(self, ip_di... | ptrblck | Were you able to use the GPU in the past?
If so, are you able to create a simple tensor on the device via: torch.randn(10, device='cuda')? |
lifeblack | Hello!I am a newbie to deep learning world.I donโt know haw to code Conv p1,p2,p3.SR is lower than one.would you mind helping me code this? | ptrblck | You are using a kernel size of (1, 1, b*b), so the width dimension will be reduced since you are not using any padding.
The last error is raised, because based on the information youโve provided,I assumed that n is the depth dimension, which expects a 5D input tensor as given in my previous post. |
John_Wales | DataLoader produces an error.image1325ร85 10.9 KBThe code for DataLoader is below:class PandaDataset(Dataset):
def __init__(self, path, train, transform):
self.path = path
self.names = list(pd.read_csv(train).image_id)
self.labels = list(pd.read_csv(train).isup_grade)
self.transform ... | ptrblck | Since all images have the same shape, the torch.stack call should work:
list_of_images = [torch.randn(3, 128, 128) for _ in range(10)]
x = torch.stack(list_of_images, 0)
print(x.shape)
> torch.Size([10, 3, 128, 128])
Also, a Dataset with equal shapes works fine:
class PandaDataset(Dataset):
dโฆ |
olisp | I am writing custom dataset but it returns type error when I am merging root directorypathwith pandasilocof image name in csv file:img_path = os.path.join(self.root_dir, self.annotations.iloc[index,0])error:TypeError: join() argument must be str or bytes, not 'int64'I have tried converting the annotation.iloc to string... | ptrblck | What kind of error message do you get, as this should be working? |
Antonio_Serrano | I want to train an LSTM neural network similar to how I do it in Keras withstateful = True. The goal is to be able totransmit the states between the sequences of the same batch and between the sequences of different batches. This is the class I use for the LSTM module:class LSTMStateful(nn.Module):
def __init_... | ptrblck | Instead of resetting the states, try to detach them via:
model.lstm._hidden_state = model.lstm._hidden_state.detach()
model.lstm._hidden_cell = model.lstm._hidden_cell.detach()
to keep the state values, but to detach them from the previous calculations. |
IsCoelacanth | I was doing a GPU memory usage study for deployment and I noticed by default PyTorch is blocking out ~800mb of VRAM. I thought it might be model specific so I tried moving a Linear(1,1) layer to gpu and it took the same amount of memory, but moving another Linear(1,1) didnโt take any memory.happens in 1.4 and 1.5 | ptrblck | This memory is most likely allocated by the CUDA context and not parameters or tensors.
Depending on the CUDA version, used device etc. you might see an allocation of ~700+MB. |
xuesongwang | Hi everyone,suppose I have a tensor: x: [0, 1, 4, 5, 6]and I want to index elements in any of this list: [4, 5, 6],similar to: np.where(x in [4, 5, 6], True, False) (this also doesnโt work),Expected outcome: [False, False, True, True, True]Are there any solutions? Thanks. | ptrblck | PyTorch doesnโt have the same isin implementation, but you might take a look at thenumpy implementationand maybe use their method?
Alternatively, you could of course use a list comprehension as:
x = torch.arange(7)
y = torch.tensor([4, 5, 6])
ret = torch.stack([y_ == x for y_ in y]).sum(0).boolโฆ |
Bauke_Brenninkmeijer | Hi Guys, Iโm trying to run MobileNetv3 on pytorch (1.4.0+cpu and 1.5.0+cpu), but Iโm getting the errorAttributeError: 'SelectAdaptivePool2d' object has no attribute 'flatten'.Is this just an unavailable instruction for PyTorch CPU or am I doing something wrong? If so, is there any comprehensive list that shows which mo... | ptrblck | I assume you are using@rwightmanโs implementation of this model?
If so, note that the flatten argument seems to have been added 13 days agohere.
Are you using different versions of the repository? |
lepoeme20 | Hi,Recently, I studied graph and learned that torch has torch geometric.Iโm using CUDA 10.2 on ubuntu 18.04 and I tried installed using conda, but it failed.How can I use torch geometric with CUDA10.2? | ptrblck | Based onthis information, their binaries should be available with CUDA10.2 for Windows and Linux.
What kind of error did you get? |
KoushikSahu | I am trying to solve a text classification problem. My training data has input as a sequence of 80 numbers in which each represent a word and target value is just a number between 1 and 3.I pass it through this model:class Model(nn.Module):
def __init__(self, tokenize_vocab_count):
super().__init__()
... | ptrblck | nn.CrossEntropyLoss uses F.log_softmax and nn.NLLLoss internally, so it expects raw logits as the model outputs.
Remove the F.softmax at the end of your model and pass the output of self.lin(3) directly to the criterion.
Let me know, if that helps. |
maamli | I have coded up a basic CovNet from scratch (1 conv, 1 pool, and 2 fc) and it is running too slow. I was looking to verify if I am doing it right here and what can be done to speed it up:The individual functions of conv_forward and pool_forward works in numpy.class ConvNet(nn.Module):
def __init__(self, _filters, bia... | ptrblck | Nested loops are expected to be slow.
You could use an im2col approach and matrix multiplications for the manual convolution approach.
What id your use case for this code?
If itโs a demo code to show the underlying operations of conv layers (to students) I wouldnโt care too much about the performโฆ |
Umair_Javaid | How to load a model when the layer names are not the same?model7.load_state_dict(torch.load(path)["state_dict"], strict=False)output:_IncompatibleKeys(missing_keys=['features.26.weight', 'features.26.bias', 'features.28.weight', 'features.28.bias', 'features.30.weight', 'features.30.bias'], unexpected_keys=['features.2... | ptrblck | The state_dict is an instance of an OrderedDict, so you could iterate all keys and change their name as donehere. |
Mah | I am beginner. I want to do a clustering my image dataset. How can I get the data from dataloader so I do it?tfms = transforms.Compose([transforms.Resize((sz, sz)), # PIL Imagetransforms.ToTensor(), # Tensortransforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])train_ds = datasets.ImageFolder(trn_d... | ptrblck | The fit() methods expects a numpy array of the complete dataset, so you would need to get all samples of the DataLoader before feeding them to KMeans().fit().
You could useMiniBatchKMeansand use the partial_fit method, if you want to feed each batch to it. |
AmirHusain | hi how are you ? thanks for helpingi wrote my network but im having difficulty in plotting the results by helper module as View_classify is not defined . can you please help me to solve the problem ?i downloaded helper and copied to work place and it didnt workimported everything neededtransform = transforms.Compose... | ptrblck | This fileshould contain the view_classify method. You could either download it again and import the method or copy-paste it to your script. |
Kiran_Ikram | Hi,I was using this snippet of code to load my finetuned GPT2 and it was working absolutely fine:tokenizer = GPT2Tokenizer.from_pretrained(โgpt2-mediumโ)model = GPT2LMHeadModel.from_pretrained(โgpt2-mediumโ)model_path = โ/content/drive/My Drive/PREDICTION/POETRY/EDset3_trained_models/gpt2_medium_SET3_ED.ptโmodel.load_s... | ptrblck | Hi Kiran,
is this issue solvedherealready or are you still running into these issues? |
jwillette | I have realized that the negative log likelihood function in pytorch has a reduction argument which can be used instead of my method below but I still cannot justify why this doesnโt work when it looks like it should.In this caseywas a vector with all of the integer class labels in it. I verified that the answers wer... | ptrblck | You would get approx. the same results assuming your indexing is right (I had to use [torch.arange(y.size(0), y] if y has the shape [batch_size]).
However, you might run into numerical stability issues, as you are applying torch.log and F.softmax separately.
You could try to use loss = -F.log_softโฆ |
krishneel | The following code snippet from the documentation except I changed the target to be out of bound.loss = nn.CrossEntropyLoss().to(device)
input = torch.randn(3, 2, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(15)
output = loss(input, target)Ondevice = cpuit raises the correct error# example
Inde... | ptrblck | It triggers this error on my system:
device = 'cuda'
loss = nn.CrossEntropyLoss().to(device)
input = torch.randn(3, 2, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(15)
output = loss(input, target)
> IndexError: Target 13 is out of bounds. |
Neofytos | Given a model, say resnet18 from torchvision, we may have a collection of pretrained weights weโd like to load. However, in some cases, that model may have been subject to modifications, say the removal of fc and avg_pool of resnet18, and as such it is now seemingly not possible to load the weights due to the rise of โ... | ptrblck | You could filter out the unnecessary parameters in your state_dict.
Have a look atthis post. |
SwapnanilHalder | I am trying to create an ANN Deep Learning model with PyTorch, and separated functions for calculate loss, and evaluate the model on the validation set. I am having an error RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn.my code is :model = MNISTModel()
def accuracy(outputs, label... | ptrblck | You are calling loss_batch(model, loss_fn, x, y, metric) in val_evaluate inside the torch.no_grad() block, which is the correct thing to do.
However, loss_batch expects the arguments: model, loss_fn, x, y, opt = None, metric = None, so you are currently passing metric as the opt argument.
Inside lโฆ |
lepoeme20 | Hi,Iโd like to get label which has only gender information from torchvision.datasets.CelebAMy code snippet is as follows:trainset = torchvision.datasets.CelebA(..., download=True, split='train', target_type='attr', ...)
trainloader = torch.utils.data.DataLoader(trainset, ...)
for idx, (imgs, labels) in enumerate(train... | ptrblck | If Iโm not mistaken, the default target_type="attr" should yield various attributes including the male attribute, so you could slice the target for this attribute only. |
sait | I need a clarification of code written for some code in FastAI2 library.this is the code WeightDropout written in FastAI2 library.class WeightDropout(Module):
"A module that warps another layer in which some weights will be replaced by 0 during training."
def __init__(self, module, weight_p, layer_name... | ptrblck | I donโt think it will be recorded, as the .data attribute is used, which will prevent Autograd to track this operation.
This is generally not recommended and the block should probably be wrapped in a with torch.no_grad() block. However, Iโm not familiar with the detailed implementation, and you migโฆ |
KenW | How do I use nn.CrossEntropyLoss() for seq2seq where my predication is of size (BS, seq_len, vocab_size) and truth of size (BS, seq_len), for examplepredication = torch.randn(2, 3, 5, requires_grad=True) # (BS, seq_len, vocab_size)
target = torch.empty(2, 3, dtype=torch.long).random_(5) # (BS, seq_len)predication: # si... | ptrblck | Try to permute the dimensions in your predication tensor to [batch_size, nb_classes, seq_len], i.e. [2, 5, 3] and it should work. |
rzhang63 | Hi@ptrblckIโm implementing a custom loss function, which has a term that involves the gram matrix of a Gaussian RBF kernel.Say, for each training iteration, I get a mini-batch (batch size 128) of predicted probabilities for K=5 classes. So the predicted probability tensor has shape=(128,5). Now I wish to compute the Gr... | ptrblck | You could add a dummy dimension and use broadcasting for this use case:
a = torch.randn(128, 2)
b = torch.randn(128, 2)
res = torch.norm(a.unsqueeze(1)-b, dim=2, p=1)
res_manual = []
for a_ in a:
for b_ in b:
res_manual.append(torch.norm(a_-b_, dim=0, p=1))
res_manual = torch.stack(resโฆ |
nameless | I am solving token classification problem. There is a huge class imbalance in data. Some of the classes have a million samples, others several hundred thousands. I saw many recommended to assign class weights to do 1/amount of samples per class. But this way gives me very small numbers.Does it make sense or I have to ... | ptrblck | You could multiply the weights, if you are suspecting rounding errors or any other numerical issues.
The weights are used relatively, so you should be able to add a constant offset to the tensor. |
Ge0rges | In my training loop what would the affects of truncating the model output and target vectors as so:action_output = model(inputs)
# The effects of the below two lines
action_output = action_output[:, tasks] # Tasks is an array of 1*"target size"
action_target = action_target[:, tasks]
action_loss = criterio... | ptrblck | Yes, that should be the case, which would create a zero gradient for the last linear layer:
model = models.resnet18()
data = torch.randn(2, 3, 224 , 224)
target = torch.randn(2, 1000)
criterion = nn.MSELoss()
output = model(data)
output = output[:, :100]
target = target[:, :100]
loss = criterion(oโฆ |
sunsunsun | Hello! Cant recognise, how to clear gpu memory and what object are stored there. Code sample below. I added comments with my 2 gpu usage after every line of code. As you can see del objects +torch.cuda.empty_cash()works well (not so well, because where is anyway 0.5gb more used, then beforeโฆ) , but during my evaluation... | ptrblck | Try to wrap your validation loop in with torch.no_grad() as this will avoid storing intermediate tensors, which are required to calculate the gradients during the backward pass.
Currently you are neither deleting loss, which holds a reference to the computation graph and thus all intermediates, norโฆ |
hfdp | Hello,I am running a CNN and trying to train it later on, however i get the errorRuntimeError: element 0 of tensors does not require grad and does not have a grad_fnThe error appears when I cal โloss.backward()โ in the validation step.Here is my code, help would be appreciated> import torch.nn as nn
> import torch.nn.f... | ptrblck | You wonโt be able to call loss.backward() inside a block, where gradient calculation is disabled via with torch.set_grad_enabled(False).
You could of course enable it, but calculating gradients in the validation set (and updating the model) is a bad idea, as you are leaking the validation dataset iโฆ |
oezguensi | Hi am usingthisimplementation of DeepLab for PyTorch and would like to perform hyperparameter optimization by training multiple models at the same time.This implementation usesnn.DataParallelto train a model on multiple GPUs.I start one training process after executingexport CUDA_VISIBLE_DEVICES=0,1. When I want to sta... | ptrblck | Yes, I would recommend to use a single script with the DataLoader, create multiple model, push each one to the desired device via to('cuda:id') and just pass the data to each model.
Since the training is done on different devices, it should be executed in parallel.
Your approach of running multipโฆ |
HaziqRazali | How can I get the output at the 2nd block of a resnet i.e. the layer that puts out a tensor with 128 channels?The code below converts the model into a list then uses torch.nn.Sequential which destroys the residual connections in the resnet.self.encoder = models.resnet18(pretrained=True)
modules = list(self.enco... | ptrblck | The residual connections wonโt be destroyed, as they are implemented in the BasicBlock and Bottleneck layers. However, while wrapping the model in an nn.Sequential container might work for your use case, I would recommend to use forward hooks and return the desired activation.Hereis an example ofโฆ |
sudddddd | I am using a nested for loop to get outputs from my model for 1000 images compared with themselves. model takes 2 images and outputs a scaler. A is a tensor of size (1000,3,128,128) and B=A. But, it is taking a long time to get the output.out=[]
for i in A:
temp=[]
for j in B:
temp.append(mo... | ptrblck | Iโm not sure if there is another way to optimize this.
Assuming you are dealing with N images, your model would have to calculate
N + N-1 + N-2 + ... + 1 = (N+1) * N / 2 comparisons.
You could speed it up using batches, but if I understand your explanation correctly, you are avoiding unnecessary โฆ |
nasant | Hello,Does the tuple of ints size (3,) correspond to a tensor of size 3?If so, why for example in thetorch.randint(3, 5, (3,))I cannot call it liketorch.randint(3, 5, 3)?What exactly does the (3,) represent?Thanks | ptrblck | It does stand for a tensor of torch.Size([3]).
I think it makes it a bit easier in the backend to always pass tuples in unpacking the dimensions. |
andreasceid | Hello,I am relatively new to deep learning with PyTorch. I tried to build a multi-layer feed-forward neural network that takes a tf-idf vector of a news title and outputs 0 or 1 whether the title is fake or not. The dataset used for the task was theoniondataset. Unfortunately, the part of preprocessing cannot change. S... | ptrblck | If you want to reduce the model capacity, you could lower the number of hidden neurons in the model.
Also note that nn.BCELoss is expecting a single neuron with a sigmoid applied on it for a binary classification use case.
So you would have to change the last linear layer to nn.Linear(512, 1) and โฆ |
Er_Hall | When we use WeightedRandomSampler for a mutliclass problem, we set reduction of the loss to mean? (always?) and what this โmeanโ means? | ptrblck | WeightedRandomSampler is used to provide weights to each sample, which is used during the sampling process of selecting the data samples for each batch.
The higher the weight assigned to a particular index, the more likely this data sample will be used in a batch.
To created batches of balanced clโฆ |
sgaur | It is discuss on many platforms but I am still not getting full understanding of this code.Below are the inputs.Number of classes = 5 (0,1,2,3,4)Input Size = torch.Size([8, 3, 512, 512]) ## 8 is a batch-size**Actual Labels size = torch.Size([8]) **predicted labels = torch.Size([8, 5])epoch = 1from torch.autograd impo... | ptrblck | Try to swap the labels and y_pred tensors when passing them to your criterion.
If that doesnโt help, could you post the complete stack trace?
Also, Variables are deprecated since PyTorch 0.4, so you should use tensors now. |
sudonto | Hi experts, I am new to Pytorch. I am fine tuning ResNet50 model using my own dataset. At first, I optimize only paramaters in โlayer4โ block + fc layer by passing only these parameters to SGD(). After several epochs, I want to optimize parameters in โlayer3โ + โlayer4โ + fc. Notice that I add โlayer3โ block. I accompl... | ptrblck | No, the order doesnโt matter, since all param_groups will be sequentially updated as seenhere. |
lucastononrodrigues | Iโm having trouble trying to fine-tune a model.My main problem is that I cannot verify if the data is being correctly interpreted by the code.The model will not advance and have a significant result, so I suspect the labels are messed up.To set the data for training and validation I used the following code found in the... | ptrblck | The DataLoader does not interpret or create the targets, but creates batches of samples using the Dataset.
ImageFolder, which you have used as the dataset, will sort the folders and assign a class label to each folder.
You could check some samples by trying to visualize a few random indices:
x, yโฆ |
Abueidda | Hi Pytorch community,I am experiencing weird behavior while dealing with the following scenario. tne is the batch size, while N is the total number of possible locations for each example. Each example has exactly 24 scalar outputs, where their locations are stored in dof tensor (size of dof is (tne X 24)). Fint_e has a... | ptrblck | This should be the case when using scatter_, and I guess I had some intermediate results stored in Fint_MAT.
After rerunning I get these results:
tensor([[-0.8591, 0.8688, 1.2835, 0.9208, 0.1976, 1.0741, -1.4244, 0.9609,
1.0544, 0.2955, -2.0284, 2.2574, 0.2363, -0.5887, 0.4460,โฆ |
acoder_acoder | I have a special dataset and images in the dataset are with channels more than 3.So I want to chage the code in torchvision.transforms. I do not know how many images will be produced after the transform.For example, I input one image with the shape 256 256 30, and I want to crop the input image to size 224 224 ... | ptrblck | Adding transformations to your Dataset does not increase the number of images, but applies these transformation on each sample.
The number of samples is defined by the return value in Dataset.__len__.
E.g. if you are dealing with 1000 images, youโll now get 1000 (randomly) transformed images.
Theโฆ |
Stacie_Davis | Hi,Apologies if my model itself is downright trash, please correct in that case. I am just learning pytorch.So, I am trying to do sentiment analysis on imdb dataset. 1-gram, sending the word index to the embedding-bag, then single fc layer.class ffn(nn.Module):
def __init__(self):
super().__init__()
... | ptrblck | Itโs usually better to remove the sigmoid and use nn.BCEWithLogitsLoss or F.binary_cross_entropy_with_logits.
However, your model might be too small, so I would recommend to add a relu and another linear layer to it.
Let me know, if that helps. |
sail | I am playing around with pre-trained models. In this case, VGG19. After training the full model and running model.eval(), I input a single image into the model to see what the output returns. If I run it for a second time, the output has completely changed for the same image.Now I am wondering, is the dropout layer not... | ptrblck | You are using classify_img, which uses TRANSFORM_IMG, which uses random transformations:
TRANSFORM_IMG = transforms.Compose([
transforms.RandomResizedCrop(size=256, scale=(0.8, 1.0)),
transforms.RandomRotation(degrees=15),
โฆ |
whitesimian | Hi!Iโm using pre-trained models from ImageNet available for my own dataset. I usedthe exact same codefor resnet50 and it worked just fine. I just switched to vgg19_bn and this error appeared.The error message traceback to โloss.backward()โ under train() function.Can someone please help me?# (...)
train_transform = tra... | ptrblck | vgg19_bn uses the model.classifier attribute for the last classification block, while ResNets use model.fc.
You are currently freezing the complete model and assign a new attribute named fc with the nn.Sequential block.
Change it to
transfer_model.classifier = nn.Sequential(nn.Linear(25088, 500),โฆ |
Sarra_Bouzidi | en tapant :biasRestaurant = to_np(m.ib(V(topRestIdx)))#convertingthe torch embedding to numpy matrixjโaurai cette erreur :AttributeError Traceback (most recent call last)in ()----> 1 biasRestaurant = to_np(m.ib(V(topRestIdx)))#convertingthe torch embedding to numpy matrix2 frames/usr/local/li... | ptrblck | Hi Sarra,
could you use a translation service, please, as my French is quite bad?From Deepl:
โor I add ( tensor = torch.from_numpy(array)) ? in the source code please ?โ
If I understand it correctly, you would like to know, where to add this line of code?
Try to add it right before the .cudโฆ |
KevinFan | Hello!I have a tensor of size ([128,3,64,64])lets say this tensor is called testBatchtestBatch[127:].size()โ> torch.Size([1, 3, 64, 64])testBatch[:1].size()โ> torch.Size([1, 3, 64, 64])Could someone explain the differences of these two index methods | ptrblck | Indexing uses the pattern [start:stop:step].
In the first approach you will get all samples from the start index 127 to the end (so just the last sample), while the second approach will give you all samples from the beginning to index 1, excluding index 1 (so just the first sample):
x = torch.randโฆ |
numpee | Hi all,Iโm trying to resume training on a model with a stepLR scheduler, and I keep getting the warning from the following link:https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rateUserWarning: Detected call of 'lr_scheduler.step()' before 'optimizer.step()'Basically, the issue is that Iโve saved the l... | ptrblck | I think you can ignore the warning, as you are calling this method before the training to get to the same epoch value.
The warning should be considered, if you are seeing it inside your training loop. |
sigma_x | I started looking into the state_dict of Adam optimizer, found this:d['optimizerG']['state'].keys()returnsdict_keys([140266712220800, 140266712220224, 140266712159432, 140266712219792, 140266712162168, 140266712220008, 140266712158784, 140266712219864, 140266712162096, 140267508645536, 140266712160656, 140266712220584,... | ptrblck | These should be the ids of the parameters.
This small code snippet demonstrates this behavior:
x = torch.randn(10, requires_grad=True)
x_id = id(x)
y = torch.randn(10, requires_grad=True)
optimizer = torch.optim.Adam([x, y], lr=1.)
param_id = optimizer.state_dict()['param_groups'][0]['params'][โฆ |
ianweb100 | Hi all,Just (UPTADED) got rid of one error but now I got a new one:), playing grown-up lego is hard.I am just starting my deep learning journey, and I am trying to fit an ( i believe 1d problem ) to a CNN,I have a dataset which I already manipulate a little bit, so the signals are in equal length and on a correct forma... | ptrblck | Iโm not sure about the model architecture.
Based on your description you are dealing with inputs of [batch_size, 1024] and are unsqueezing this input tensor to create a fake temporal dimension to [batch_size, 1024, 1].
If thatโs the case, the nn.Conv1d with a kernel size of 1 will be a linear layeโฆ |
acoder_acoder | Hi, there!I argued with my friends whether it was necessay to keep the gradents of VGG net to obtain the perceptual loss.loss_total = loss_net + loss_vgg.I thought there was no use to update the parameters of the VGG net, so there was no reason to keep the gradients.Any suggestions? Thank you! | ptrblck | Could you link to a reference implementation, which shows the desired behavior?
If Iโm not mistaken, the perceptual loss is calculated by using a norm between the intermediate activations between two input images, and summing it to a final loss.
If my understanding is correct, I donโt see where thโฆ |
jmandivarapu1 | I build an autoencoder similar to VGG 19. But my decoder is throwing some error. Using it on CIFAR10 datasetmode WRN(
(encoder): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(... | ptrblck | It looks like this part of the model is wrong:
(decoder): Sequential(
(0): ConvTranspose2d(512, 320, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
Since the transposed convolution will โฆ |
Sac_dev | Hi,Iโm implementing a CNN-VAE with skip-connection layers in encoder and decoder, to implicitly optimize the information flow from input data and latent representation.I am aware that ResBlock use identity short-cut mapping if the resolution (HxW) and the channel depth is kept unchanged, and otherwise use a convolution... | ptrblck | You could permute the activation, treat the channels as a spatial dimension, apply F.interpolate on it, and permute the activation back to its original layout. |
shahy | This is a weird cuda error that I get. If someone could just explain what it means or what is causing it, that would be awesome!Traceback (most recent call last):File โmain.pyโ, line 40, intrain_correspondence_block(root_dir)File โ/home/jovyan/work/correspondence_block.pyโ, line 82, in train_correspondence_blockloss.ba... | ptrblck | Thanks for the update.
Could you check the target min and max value before passing it to nn.CrossEntropyLoss or nn.NLLLoss?
The expected values are in the range [0, nb_classes-1], while you might pass out of bounds values.
You could also run the code on the CPU, which should give you a better staโฆ |
Abueidda | Hi,I am trying to parallelize the following function:def assemble(u):
Fint=torch.zeros((ndof,1))
Fext=torch.zeros((ndof,1))
for iel in range(tne):
elnodes=elems[iel,:].long()
xcel=nodes[elnodes,0]
ycel=nodes[elnodes,1]
zcel=nodes[elnodes,2]
dof=torch.tensor([3*elno... | ptrblck | Thanks for the update.
Would Stress_Strain and KEL accept batches or only the current input shapes? |
ptrblck | Oh, you are right. I havenโt checked the compute capability of your device.The PyTorch binaries ship for GPUs with compute capability >= 3.7, while your GTX 770 has 3.0, so you would need to build PyTorch from source.You can find the instructionshere. | ptrblck | It youโve installed a PyTorch binary, the local CUDA version will not be used.
Uninstall all binary installations and try to rebuild PyTorch with your local libs.
Let me know, if you still see the cudnn error and weโll try to reproduce it. |
apsod | If i have a pytorch moduleMwith a constant matrix buffer T, where M.forward(x) = x @ T, If i apply this moduleMat several points in a deep model, will autograd save one copy of the (constant) matrix T per invocation, or will it โrealizeโ that the matrix T is constant and just have one copy? | ptrblck | Yes, Autograd should figure this out.
Here is a small example, which shows that leaf variables are treated in a special way. I.e. inplace modifications are now allowed, if the value of the variable is needed to calculate the gradient:
# Both require gradients
x = torch.randn(1, requires_grad=True)โฆ |
sigma_x | This is just to confirm my understanding on how autograd works, as I found the solution neitherherenorhere.In the following setupm1, m2 and m3are Pytorch Sequential models,l1is a loss function,labare labels. Parts of m2 haverequires_grad=False:input = torch.randn(10)
o1 = m1(input)
o2 = m2(o1)
o3 = m3(o2)
l=l1(o3,lab)
... | ptrblck | Yes, thatโs what I meant. |
dachosen1 | I created an LSTM model and rented a GPU and CPU in the cloud for training. The problem is that the model isnโt using all the available resources. My CPU utilization is less than 5% and my GPU is at ~20%. The GPU utilization does follow a sin wave pattern. Which I suspect is due to turning my GPU for validation.Is ther... | ptrblck | Instead of loading real data you could initialize random data, push it to the GPU and profile the training loop without the data loading:
# for a multi-class classification
data = torch.randn(batch_size, channels, height, width, device='cuda')
target = torch.randint(0, nb_classes, (batch_size,), dโฆ |
nieyan | I test task1โs acc after resume model. And accuracy value match to resume file at first. But after some iterations of training , task1โs accuracy has changed. Donโt know whatโs wrong about training. I think fix backbone and task1 parameters should get always the same task1โs accuracy .code of fix backbone and task1 par... | ptrblck | Besides setting the requires_grad attribute to False, you might need to call .eval() on the layers involved for โtask1โ.
This will make sure to disable dropout and use the running stats of batchnorm layers.
If you keep the model in train() mode, the batchnorm stats will be updated and might thus cโฆ |
Anshumaan_Dash | HiWhile loading a pre-trained model, I am getting the same runtime error for every layer.E.g.size mismatch for conv_batchnorm.weight: copying a param with shape torch.Size([1, 32]) from checkpoint, the shape in current model is torch.Size([32])Kindly help me figure out how to solve this problem.Thanks | ptrblck | Is conv_batchnorm an nn.BatchNorm layer?
Was the state_dict saved in another PyTorch version than the one you are using to reload it? |
nbravo | Hello everyone,Iโm a little confuse about the correct use of Variable or tensor.requires_grad=True for an intermediate Tensor created between a trainable layer and the loss function. For example:import torch
import torch.nn as nn
x = torch.rand((5, 10))
l1 = nn.Linear(10, 10)
y = l1(x)
first_two = Variable(torch.zer... | ptrblck | Variables are deprecated since PyTorch 0.4 so you should use tensors in newer versions.
That being said, I would just slice y directly and pass it to the loss function:
y = l1(x)
first_two = y[:, :2]
loss = dummy_loss(first_two)
loss.backward() |
welp | Suppose I have this module. If the first node of the output of fc_type is higher than the second node, I want to forward pass through fc_1, else I want to forward pass through fc_2. Currently, my implementation requires me to put a for loop over each input in the batch. Is this sequential or does it get automatically p... | ptrblck | Instead of iterating each row in out, you could split out before into both inputs, call fc_1 and fc_2, and create the output tensor using the results.
Depending on the batch size, the performance difference might be insignificant. |
jacobatpytorch | Folks, I downloaded the flowerโs dataset (images of 5 classes) which I load with ImageFolder. I then split the entire dataset using torch.utils.data.random_split into a training, validation and a testing set.The issue I am finding is that I have two different transforms I want to apply. One for training which has dat... | ptrblck | Since ImageFolder will lazily load the data in its __getitem__ method, you could create three different dataset instances for training, validation, and test and could pass the appropriate transformation to them.
You could then create the sample indices via torch.arange(nb_samples) (or the numpy equโฆ |
Patrice | Dear engineers,I am sorry if my question might seem silly, but I would like to learn. I am quite new to programming and segmentation tasks. In effect, I am having a dataset with labels that are not in the form of [0,1] as It should be for a binary segmentation task. The readme of the data says that the probability of t... | ptrblck | Thanks for mentioning it again.
The dice loss is used for discrete data, so I doubt it can work for a regression task.
Since your labels are in the range [0, 1], I would again recommend to use nn.BCEWithLogitsLoss.
Alternatively, since you are already rounding the targets to 0 and 1 to be able tโฆ |
Homa | Hi all.I want to change the input so it minimizes the loss (rather than changing the trainable variables ). in other words i want update input instead of weight and bias.I use this code for iteration:data_batch = Variable(data_batch, requires_grad=True)prediction = model(data_batch)loss = loss_function(prediction, fitn... | ptrblck | Variables are deprecated since PyTorch 0.4 so you should use tensors now.
You would have to pass the input tensor to an optimizer, so that it can update the input (similar like you pass the model.parameters() to an optimizer).
The same work flow applies as usual, i.e. you would zero out the gradieโฆ |
mich | Hi, I am quite new to pytorch and have difficulties with some understanding of channels.I am doing binary segmentation with deeplab, my input image channel is [N, 3, H, W], my mask input is [N, 1, H, W] (where the values is either 0 or 1). The output, before doing any accuracy or loss, the image channels are [N, 2, W, ... | ptrblck | I assume your last layer is a convolution layer with a single output channel.
In that case your model will return logits, which are raw prediction values in the range [-Inf, +Inf].
You could map them to a probability in the range [0, 1] by applying a sigmoid on these values.
In fact, nn.BCEWithLoโฆ |
cheng | According to my understanding, whenais ndarray,torch.from_numpy(a)is same astorch.as_tensor(a), and they donโt copy the data just share the same memory, so I think they are same speed when applied, but I test thatfrom_numpyfaster thanas_tensor. Could someone explaine for me? Thanks a lot first | ptrblck | Yes, both approaches share the underlying memory.
torch.as_tensor accepts a bit more that torch.from_numpy, such as list objects, and might thus have a slightly higher overhead for these checks. |
Bruno_Oliveira | Iโm working on a project and I need the output of a truncated ResNet. Taking ResNet18 as an example, if I do the following changesimport torch
import torch.nn as nn
import torchvision.models as models
resnet = models.resnet18(pretrained=False)
resnet.avgpool = nn.Identity()
resnet.fc = nn.Identity()The output gets fla... | ptrblck | Itโs expected, as ResNet uses a functional call to torch.flatten in the forward pass inthis line of code.
You could either derive a custom ResNet class and reimplement the forward method or use forward hooks to get the desired activation.
Alternatively, you could also create an nn.Sequential contโฆ |
Yongqiang_Chen | Hi Everyone,I converting a 10GB CT scanning images to an array and then transformed to torch tensor. I intend to do some mathematical operation with GPU parallelization on this big tensor. It is too large to move to the GPU memory. Is there any method to do this operation in Pytorch?Thanks, everyone. | ptrblck | If you could split the operation into chunks of data, itโs possible.
E.g. if you would like to sum a tensor, you could slice the original tensor, push this slice to the device, sum the values, and transfer the result back to the host.
Once all slices are done, you could sum all temporary results.
โฆ |
erm | Hi, I am trying to reproduce a NN in Python, using PyTorch. I set in my codenp.random.seed(3)andtorch.manual_seed(3)(the numpy seed being the same as the one used for the NN without Pytorch, and the torch seed, being whatever value).I know the results are different with different initial seed because the optimizer will... | ptrblck | The loss curve of GD is usually less noisy and the loss should decrease in each step.
Using SGD on the other hand gives you more noise, but also the final accuracy is often better than in GD. One might claim that the noisy updates add some regularization, but Iโm not sure what the current theory iโฆ |
Shanto_Islam | As far as my knowledge, when we makenn.LSTM(.. hidden_dim, bidirectional = True)we tend to make the next fully connected layerself.fc1 = nn.Linear(hidden_dim*2..), with this I believe we make this fully connected layer bi-directional as well. If so, then could we makeself.fc2bi-directional as well?Please rectify me if ... | ptrblck | You are doubling the number of input features, as the preceding LSTM gives you num_directions * hidden features.
The linear layer itself is not โbirirectionalโ in the sense as an LSTM. The incoming activation wonโt be processed in a sequential/directional manner.
You could of course increase the nโฆ |
chetan06 | I am working on Dog Breed Classification problem. I am using pretrained model for training.# Creating a model
model = models.resnet50(pretrained=True)
for param in model.parameters():
param.requires_grad = False
num_features = model.fc.in_features
fc_layers = nn.Sequential(
nn.Linear(num_features, 4... | ptrblck | I would recommend to remove the last ReLU and dropout layers and directly return the logits.
Also, whatโs the reason you are implementing the loss manually instead of using nn.CrossEntropyLoss? |
abhinavankur | Iโll keep this brief. These are the shapes for the input I am passing to my network.print(images.shape)print(images.view(images.shape[0], -1).shape)print([len(image_datasets[key]) for key in image_datasets.keys()])torch.Size([32, 3, 224, 224])torch.Size([32, 150528])[6552, 818, 819]The first layer in my classifier, wit... | ptrblck | The error in cell20/21 is created by the wrong usage of the labels tensor:
img = img.to(device)
log_ps = model(img.unsqueeze(0))
test_loss = criterion(log_ps, labels)
While you are loading a single image and unsqueeze the batch dimension, which is fine, you are reusing labels from previous cells (โฆ |
pmeier | Suppose I performmy_awesome_cuda_training()and I want to determine the maximum amount of memory that was used. Is that as simple as usingtorch.cuda.memory_stats()?import torch
def my_awesome_cuda_training():
torch.empty(2, *[1024] * 3, dtype=torch.uint8, device="cuda")
my_awesome_cuda_training()
stats = torch.... | ptrblck | Yes, the .peak stats will give you the maximum. You can use torch.cuda.reset_peak_memory_stats() to reset this peak if you need to monitor another peak usage. |
CarlosHernandezP | I am trying an approach to solve a specific problem that requires me to addnneurons to the last layer of a pre-trained model. The tricky part is that it has to be on the same layer. I found an example in the forums here:older questionI want to keep the pre-trained weights intact and addnrandomly initialized ones.In sai... | ptrblck | To make sure the old weights are present, you could simply print the old and new weight tensor and compare them or use a proper comparison via old_weight == new_weight[:, :old_weight_num].
Iโm not sure how ix etc. is defined, so cannot see, if the creation is correct.
I would recommend to avoid usโฆ |
Mike2004 | Iยดm trying to loading a image, and then i get this error: img=torch.view(img,(1,-1))AttributeError: module โtorchโ has no attribute โviewโThis is the program to load the model:import osimport cv2import torchimport torch.nn.functional as Fimport numpy as npfrom scipy.spatial import distanceimport torchvisionimport torc... | ptrblck | Your model returns three tensors in its forward method:
return self.decode(z), mu, logvar
Assuming you would like to visualize the first returned tensor, this should work:
o = out[0].view(out[0].size(0), -1) |
ArneNx | Hey all,I narrowed my problem down to the following:I set a random seed and create a new model (this should call the standard init for every parameter)I save this model (to look at those parameters later on)I again set the original random seedI reset the model parameters viadef weight_reset(m):
if (
isinsta... | ptrblck | The order of the layer initialization seems to be different, so that resetting the seed wonโt yield the same results.
After removing theinit methodsand resetting the seed before each layer creation (in the ResNet class as well as in BasicBlock, conv1x1, and conv3x3) I get the same results.
That โฆ |
DrHB | Suppose I have this model:class DummYmodel(nn.Module):
def __init__(self, x, m):
super().__init__()
self.x = torch.nn.Parameter(torch.tensor(x))
self.m = torch.tensor(m)
def forward(self, x):
passI will init and put it onCudadummy = DummYmodel(2.0, 3).cuda()>dummy.x
Par... | ptrblck | All nn.Parameters, nn.Modules and buffers will be transferred to the specified device.
To push self.m to the device, you should register it as a buffer via:
self.register_buffer('m', torch.tensor(m)) |
salvolpe | Hey everyone! I am working on a binary classifier with simulated data. The dataset monitors COVID related symptoms. Originally the whole dataset was simulated, but then I found real-world data. However, I still needed to generate testing statuses, as these are not readily available to the public. Regardless, neither da... | ptrblck | Sorry for not seeing it earlier, but _, predictions = torch.max(outputs.data, 1) wonโt work if your output only contains a single output unit.
If your model is defined as:
binaryClassifier(
(linear): Linear(in_features=26, out_features=1, bias=True)
)
you should get the prediction from the logiโฆ |
SU801T | Hi,I would like to add GPUs to different parts of my code.I am extracting features from several different magnifications of the same image, however using 1 GPU is quite a slow process. I was wondering whether there is a simple way of speeding this up, perhaps by applying different GPU devices for each input? Iโm unsure... | ptrblck | I would recommend to setup the model before wrapping it into nn.DataParallel.
The new creation of resnet via:
modules = list(resnet50.children())[:-1]
resnet = nn.Sequential(*modules)
might have side effects and Iโm not sure how this would interact with nn.DataParallel. |
Jiajun_Chen | How can I delete the fc7 layer in Faster RCNN?And the following is part of the model structure(roi_heads): RoIHeads(
(box_roi_pool): MultiScaleRoIAlign()
(box_head): TwoMLPHead(
(fc6): Linear(in_features=12544, out_features=1024, bias=True)
(fc7): Linear(in_features=1024, out_features=1024, bias=Tru... | ptrblck | I havenโt checked the shapes, but I assume the memory might blow up, since the flatten operation is missing, which is defined in TwoMLPHead inthis line of code.
Replace it with:
model.roi_heads.box_head = nn.Sequential(nn.Flatten(start_dim=1), model.roi_heads.box_head.fc6)
and it should work finโฆ |
Ameen_Ali | Hello All,Letโs say I have a dataloader which returns video samples where each video sample is of the following shape : [number_of_frames X 2048] (number of frames can vary from the following set : [60 , 80 , 100 , 120].I want in each batch returned from the dataloader to have samples with the same number of frames.for... | ptrblck | You could probably write a custom sampler, which could yield the data indices based on the condition of the data length, but Iโm not sure how complicated that would be.
Maybe the easier approach is to create separate DataLoaders, one for each length, use their iterators, and call randomly next on tโฆ |
Ameen_Ali | Letโs say I have a list of tensors ([A , B , C ] where each tensor of is of shape [batch_size X 1024].I want to merge all the tensors into a single tensor in the following way :The first row in A is the first row in the new tensor, and the first row of B is the seocnd row in the new tensor, and the first row of C is th... | ptrblck | This should work:
a = torch.arange(0, 6).view(3, 2)
b = torch.arange(6, 12).view(3, 2)
c = torch.arange(12, 18).view(3, 2)
ret = torch.cat((a.unsqueeze(1), b.unsqueeze(1), c.unsqueeze(1)), dim=1).view(9, 2) |
Umair_Javaid | I have a very large tensor of shape(512,3,224,224). I input it to model in batches of 32 and I then save the scores corresponding to the target label which is2. in each iteration, after every slice, the shape ofscoreschanges. Which leads to the following error. What am I doing wrong and how to fix it.label = torch.ones... | ptrblck | Iโm not sure if a condition will save you, since you expect targets to have at least the length b+batch_size, while it seems to have a single element.
I would recommend to take another look, how targets is defined and why itโs smaller than you expect. |
sgaur | I need to know what is the correct input dimension of Input images some discussion forum tell me its channelHeightWidth other telling me HeightWidthchannelWhich one do I need to chose while doing training of Model and for Visualization. | ptrblck | PyTorch expects inputs as [batch_size, channels, height, width] for the โusualโ layers in CNNs.
If you want to visualize numpy arrays via e.g. matplotlib, then you should remove the batch dimension and permute the array to a channels-last format.
However, this is matplotlib specific and other visuโฆ |
harrycb | Iโm trying to create a model takes two images of the same size, pushes them through an affine transformation matrix and computes a loss value based on their overlap.I want the optimiser to change the affine transformations so that they are overlapping.It doesnโt seem that the gradient is being computed back through to ... | ptrblck | You are recreating the theta tensor in the forward, which will detach the parameters.
You could either create theta in the __init__ method as:
self.theta = nn.Parameter(torch.tensor([
[self.scalew, 0, self.transX],
[0, self.scaleh, self.transY]
])[None])
orโฆ |
kiru883 | Hello, thank for attention I ran into the following problem, the weights before and after did not change, here is the code:class fastRCNN(torch.nn.Module):def __init__(self, params):
super(fastRCNN, self).__init__()
# roi pooling size
self.rsize = params['roi']['output_size']
#######################... | ptrblck | Have you checked the input to torch.log? As mentioned before, negative inputs will give you Nan outputs.
This will also detach your tensors and your model wonโt get valid gradients. You should not recreate tensors, but use them directly.
See 2. |
blenderender | HiI have a loss function that looks something like thisloss = logits + lambda * get_value_of_random_fc_neuron(neuron_index)I use forward hooks to get the random neuron value in get_value_of_random_fc_neuron()The issue is the gradients are same ifloss = logits orloss = logits + lambda * get_value_of_random_fc_neuron(neu... | ptrblck | Thanks for the update!
Your forward hook detaches the output.
Could you remove the detach() call and try it again? |
tcsn_wty | Hi all, I am writing a simple neural network using LSTM to get some understanding of NER. I understand the whole idea but got into trouble with some dimension issues, hereโs the problem:class NERModel(nn.Module):
"""
Encoder for NER model.
Args:
- vocab_size: vocabulary size, integer.
- embe... | ptrblck | If you want to keep F.log_softmax(x, dim=1), then yes.
Otherwise use dim=2, if you want to permute the tensor afterwards.
Yes, since it will be applied twice at the moment (in your forward and inside nn.CrossEntropyLoss). |
John_Minou | Hello,I am doing the Udemy course on Pytorch and trying to run the MNIST example on the GPU. Even though I activated CUDA, training is slow and GPU usage is at 0%.Here is my code :device = 'cuda'
model.to(device);# number of epochs to train the model
n_epochs = 30 # suggest training between 20-50 epochs
model.train(... | ptrblck | Could you return the round operation and check the memory again?
If the GPU is not being used, then
device = 'cuda'
model.to(device)
should raise an error.
For small models and workloads, you might see a low GPU utilization. |
syc7446 | Hi,I am working on regressing a score (positive real value) from images, and thus, the structure is almost identical to pytorchโstraining a classifier exampleexcept for a few parts including the change fromCrossEntropyLoss()toMSELoss(). The input size to CNN is [4, 2, 240, 240] where 4 is the batch size, 3 is the chann... | ptrblck | If you are using nn.MSELoss, the output and target shape should be equal.
Currently your target has an additional dimension.
You could remove it via target = target.squeeze(1) or target = target.squeeze(2).
What do the dimensions mean in the target? |
Sam_Lerman | I want to reuse the weights in my linear layer but with the weights transposed. Unfortunately, it seems that using a functional linear layer and passing in the weights during the forward call of my module is inefficient. Is there another way to do it?Specifically, what Iโve done so far looks like:class Bla(nn.Module):
... | ptrblck | The nn.Linear module calls into F.linear in its forward pass as seenhere.
How did you profile it to come to the conclusion the functional call is slower than the modules?
Usually all modules call into their functional equivalent. |
sh0416 | I use dataset and dataloader for my training script.Is it OK to change dataset parameter during the traininng??For example,dataset = CustomDataset()
loader = DataLoader(dataset, num_worker=8)
for i, data in enumerate(loader):
dataset.x = new_xI saw that DataLoader use multithread and dataset is copied to other th... | ptrblck | No, if you are using multiple workers, the changes wonโt be reflected.
What is your use case?
Maybe you could useshared arrays? |
Umair_Javaid | I have a tensor of shape(2,2,2,2):tensor([[[[ 5., 5.],
[ 5., 5.]],
[[ 10., 10.],
[ 10., 10.]]],
[[[ 100., 100.],
[ 100., 100.]],
[[1000., 1000.],
[1000., 1000.]]]], device='cuda:0')I want to transform it such that the tensor along a... | ptrblck | This should work:
x = x.repeat(1, 1, 3, 1)
print(x.view(-1))
> tensor([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
5., 5., 10., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 100., 100., 100., 100., 100., 100.,
โฆ |
JWL | So I have a vector of 2D points of sizeBxNx2. I want to linearly interpolate the points such that I get the middle point between each point while also preserving the other points, which would effectively double the number of points toBx2Nx2. Does anyone know how I can do this efficiently in a batch? | ptrblck | Wouldgrid_samplework?
You might have to use a width dimension of size 1 to match the expected shapes. |
George_Papanikolaou | I would like to ask if it is possible to do something I have in my mind. I have cifar10 dataset, say (x:images,y:labels). I use an encoder for x, which last layer is a Conv2d(1024, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) and batchnorm. Can I use the new x from the encoder and original y, to run for example... | ptrblck | An input of [batch_size, 1024, 1, 1] wonโt work for a standard resnet, as the conv layers use kernels with more than a single pixel and you are also using pooling layers, which wonโt be able to decrease the spatial dimensions.
You could try to
reshape the encoder output, and create โfakeโ spatialโฆ |
kpprasa | Hello,I am working on a project where we are trying to modify the data every n epochs. I have two questions related to this:Can we use a single dataloader and dataset to do this?ie every 5 epochs jitter the images in the trainsetWould it be better from a computational standpoint to perform these custom transforms in a ... | ptrblck | If your use case allows to manipulate the dataset after a full epoch, I would recommend to perform the manipulations directly on the data inside the Dataset and just recreate the DataLoader.
Instantiation of DataLoaders should be cheap, so you shouldnโt see any slow down.
Also, manipulating the daโฆ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.