user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
ironicoxidant | I would like to be able to fill in elements of a tensor recursively, and then compute the gradient w.r.t. an element for backpropagation. Currently, my code (using Python looks something like this:def function(length: int, idx: Tensor):
_dummy: Tensor = torch.empty(0)
x: List[Tensor] = [_dummy for _ in range(le... | ptrblck | Are you getting an “inplace error” or is this just a concern?
If inplace operations are disallowed in your code, PyTorch will raise an error, so you could still try to execute your code given that t is a newly initialized tensor. |
nxag | Hi guys,I need help!I have been trying to use pytorch_forecasting with a script of mine and I keep getting the same error when calling the TimeSeriesDataSet function from python_forecasting:SystemError: CPUDispatcher(<function _find_end_indices at 0x0000012AD9E7FAF8>) returned a result with an error setAfter spending a... | ptrblck | Maybe you are hitting the same error as describedherein the repository.
Could you check if using the mentioned numpy and pandas versions would work? |
deepfailure | What is the maximum seed one can use with:torch.manual_seed(seed)Is it the same maximum seed as with CUDA set seed operations?Thanks for the answer. | ptrblck | From thedocsof torch.manual_seed:
seed (int) – The desired seed. Value must be within the inclusive range [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeError is raised. Negative inputs are remapped to positive values with the formula 0xffff_ffff_ffff_ffff + seed.
So the … |
Eddous | Hello,I want to install an older version of lightning-flash, which would run with cuda 10.1. I know there is an option for torch described athttps://pytorch.org/get-started/previous-versions/. But I couldn’t find instructions anywhere for lightning-flash.Thank you very much!PS: I hope that this forum is also for lightn... | ptrblck | I don’t know which dependencies lightning-flash uses, but based on your description it seems a CPU-only PyTorch version is installed. Maybe pip install --no-dependencies ... would help to skip replacing PyTorch with the CPU binary. |
Mari | I am doing parallel NN in PINN and I need to use transfer learning but I do not know how I can use it? Can someone please guide me on how to use different pre-trained networks in parallel NN?``class Net2_kc(nn.Module):
def __init__(self):
super(Net2_kc, self).__init__()
self.k3 = nn.Seq... | ptrblck | The error is raised since your current k3 or k4 modules use a different structure (i.e. they are nn.Sequential containers) while the state_dict contains a main module, which seems to use an nn.Sequential container internally.
You could either change the state_dict keys to match the newly create sub… |
Allan_Jie | I’m working on multi-task learning. Task A and Task B share the encoder, but decoders are different.So I have to differentiate the dataset A and dataset B in each iteration.It seems if I simply dodataset = ConcatDataset([datasetA, datasetB])The batch during the enumeration will contain samples from both A and B. But I ... | ptrblck | You could use two DataLoaders, create the iterators using loader_iter = iter(loader), and grab the next batch in each iteration as from the loader you want via next(loader_iter).
This approach would give you the flexibility to apply complicated conditions when to use which dataset.
On the other ha… |
cbd | My model consist of convolution operations with skip connection. I trained model for 128x128 input dimension. During testing i give image of dimension 256x256. Results are differ in both the cases. | ptrblck | No, I was referring to flattening the activation before feeding it to a linear layer, e.g. as seen in theResNet example.
Yes, I think using linear layers at “the end” of the model is commonly used for classification/regression use cases where either class logits or floating point regression valu… |
Scott_Hoang | Is there a way to stop the model’s forward function early using forward hooks without modifying the original forward function? | ptrblck | No, I don’t think you can use forward hooks to stop the model execution. |
neel_g | Hi,I was looking to implement U-Net Like long skip-connections across the encoder as well as the decoder. Thissnippetillustrates my problem.blocks.extend( [nn.BatchNorm2d(self.channel), nn.ReLU(inplace=True)] ) #adding BatchNorm2d
self.blocks = nn.Sequential(*blocks)
def forward(self, input):
return self.blocks(i... | ptrblck | The common approach would be to store the output activations of the encoder layers and reuse them in the decoder path directly. If you are seeing issues using this approach due to the large number of layers, I would suggest to store the outputs in e.g. a list and use a loop to execute the blocks of … |
TARUN_BHATIA | I have my model as described below. While I was trying to check the gradient flow using this pytorch post (Check gradient flow in network) , i discovered that some of my parameters gradients still have NONE value. After little debugging, I got to know that following layers have None value : bert.pooler.dense.weight, be... | ptrblck | Could you check if bert.pooler.dense.weight and bert.pooler.dense.bias have their .requires_grad attribute set to True?
If so, then I guess these parameters are not (always) used and you could check the forward method of your model to see, if some conditions are used to skip these parameters. |
Mona_Jalal | I am reading aGitHub codethat uses a pretrained version of Inception V3. I am confused by this linemodel.load_state_dict(torch.load(args.model_loc))in the code:# define the model
model = models.inception_v3(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 2)
# load the m... | ptrblck | I guess the author of the first code snippet is loading a pretrained state_dict for the manipulated model (note that model.fc is changed)? |
MHSA | Hello,I have a dataset consisting of large images. I only need to look at a specific area in each image, so I have converted the entire dataset into an hdf5 file and I plan tolazily loadthat specific area per image.However, since these areas are different between images, I end up withinputs of different sizes. The sugg... | ptrblck | That’s correct in the default use case. However, you could use a BatchSampler, which would allow you to get all indices of the current batch in the __getitem__ and apply your resizing logic as described e.g.here. |
denexo | What is the advantage of usingnn.ModuleDictversusOrderedDictordict(in case the order doesn’t matter)?self.activations = nn.ModuleDict([
['lrelu', nn.LeakyReLU()],
['prelu', nn.PReLU()]
])vsself.activations = OrderedDict([
['lrelu', nn.LeakyReLU()],
['prelu', nn.PReLU()]
]) | ptrblck | nn.ModuleDict will properly register the modules to the parent as seen here:
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.module_activations = nn.ModuleDict([
['m_lrelu', nn.LeakyReLU()],
['m_prelu', nn.PReLU()]
]… |
saluei | HiThis Problem reported inAccuracy decrease after load the saved modelvisionMy guess is here model accuracy was depend on the batches that go through the testing phase so instead of performing once test for 5 time and average it then save the model and then redo itHowever, does not solve.I have the same problem,validat... | ptrblck | Could you compare the outputs of the model for a static input (e.g torch.ones) and after calling model.eva() before saving the state_dict and after loading it?
If the result is equal (up to floating point precision) then I would recommend to check the data loading and make sure both scripts use the… |
gonzrubio | I am currently going over various architectures for object detection and came across theFeature Pyramid Network (FPN)which at first glance looks incredibly similar to theUNet architecturewhich made me wonder if it had any major differences other than implementation details to reduce memory footprint or inference/traini... | ptrblck | I can’t speak for the author of the linked question, but would guess
But, where U-net only copy the features and append them, FPN apply a 1x1 convolution layer before adding them. This allows the bottom-up pyramid called “backbone” to be pretty much whatever you want.
means that the FPN implemen… |
fike | Hi all,I am trying to use ConvNeXt models in my implementation, but everytime I call the model (either it’s the tiny, base, or whatever) I get the following error:self.model = models.convnext_tiny(pretrained=True)AttributeError: module 'torchvision.models' has no attribute 'convnext_tiny'The last torch installation I h... | ptrblck | It seems this model just landed 28 days ago inthis PRso you would need to install the nightly release, not the stable one. |
peria1 | I am using torch 1.9.0 in Python 3.7.6 on Windows 10.I am finding that each DataLoader worker, when starting up, imports the script from which the DataLoader is being called. I tried to make a minimal example below.Is this the expected behavior? It really surprises me, since it seems to assume the caller script can be ... | ptrblck | Yes, I think this is expected as Windows uses spawn instead of fork as described in theWindows FAQ:
The implementation of multiprocessing is different on Windows, which uses spawn instead of fork. So we have to wrap the code with an if-clause to protect the code from executing multiple times. Ref… |
Mona_Jalal | I am using the following code snippet for focal loss for binary classification on the output of vision transformer. Vision Transformer in my case throws two values as output. So, I used a sigmod of difference of the two outputs as follows below. Could you please confirm if it is correct?class FocalLoss(nn.Module):
... | ptrblck | I can’t comment on the correctness of your custom focal loss implementation as I’m usually using the multi-class implementation from e.g.kornia.
As described in the great post by@KFrankhere(and also mentioned by me in an answer to another of your questions) you either use nn.BCEWithLogitsLoss f… |
Ziyu_Huang | Hi! I am interested in how at::mm works, and I can not find its source code….especially when using GPU, does mm uses cublas directly? Or how to… parallelly computes?Thank you!!! | ptrblck | You can fine the mm definition in native_functions.yamlhereand follow their GPU dispatching to mm_out_cuda and eventually to addmm_out_cudahere. |
yutanagano | Hi all,I was reading through the pytorch documentation for the DataLoader class and I noticed that it recommends against DataLoaders returning CUDA tensors in distributed training.It is generally not recommended to return CUDA tensors in multi-process loading because of many subtleties in using CUDA and sharing CUDA te... | ptrblck | I don’t think the quoted recommendation targets a distributed training setup, but the usage of multiprocessing e.g. via num_workers>0 in a DataLoader.
The main issues in such a use case is to avoid re-creating the CUDA context in each process, which will fail. |
Roua_Rouatbi | I’m trying to normalize the intensity of the images in the dataset that I have and crop the images to 32 by 32 pixels. The image dataset shape is (36, 2152, 2552, 3) and I want it to be something like (x,32,32) | ptrblck | I don’t know which range your data values are in, but T.Normalize using the current stats would expect an input with values in [0, 1], so you might need to normalize the raw data before applying the transformation. |
Paritosh | Hi all,I want to optimize only some variables. For example, create a Tensor, and then pass only a part of it to the optimizer. However, I am gettingcan't optimize a non-leaf Tensorerror. Is there a way to do what I am trying to do?I have attached a minimal example below. In this case, I want to optimize thesourcevector... | ptrblck | You could directly assign zeros to the .grad slice e.g. via lin.weight.grad[2:4, 2:4] = 0., but you would have to be careful about this approach. If you are using an optimizer with running stats (such as Adam) and these parameters were already updated before (i.e. the running stats contain valid val… |
Oussama_Bouldjedri | I was wondering if my loss function calculation is wrong :def train(model, optimizer, train_loader, epoch,writer):
model.train()
train_loss=0
train_accuracy=0
correct=0
train_predicted=[]
train_target=[]
for data, target in train_loader:
... | ptrblck | Yes, due to the large gap between the training and validation accuracy your model would overfit to the training dataset. |
Mona_Jalal | I found this implementation offocal lossin GitHub and I am using it for an imbalanced dataset binary classification problem.# IMPLEMENTATION CREDIT: https://github.com/clcarwin/focal_loss_pytorch
class FocalLoss(nn.Module):
def __init__(self, gamma=0.5, alpha=None, size_average=True):
super(FocalLoss, s... | ptrblck | Thanks for the links. I took a quick look at the posts and they seem right for nn.BCELoss. However, I’m not a huge fan of single dimension inputs to nn.BCELoss (but this might be my personal pet peeve).
In any case, your focal loss implementation expects the same inputs as nn.CrossEntropyLoss if … |
XTROLLERX | I was wondering why my Google Colab is running out of ram when generating an output for my model. Here is the source codeimport os
import tarfile
import torch
from torch.utils.data import random_split
import torchvision.transforms as tt
from torchvision.transforms import Compose
from torchvision.datasets.utils import d... | ptrblck | Your validation loop seems to store all losses in a list and is not executed in a with torch.no_grad() context. In this case, each loss tensor will still be attached to the computation graph and you will thus store the entire graph with each loss.
Wrap the validation loop either in the no_grad guar… |
S_M | Hello I have a pre-trained vgg11 network with its weights the structure of this network is as follows:VGG((features): 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(inplace=True)(3): MaxPool2d(... | ptrblck | Assuming the output is created by the last linear layer, out would already contain the logits. |
aaroswings | I’m imagining a scenario where I want to apply a learnable convolution layer to multiple Tensor inputs in a module. I would want the layer to learn from all inputs using the average of the gradients of the shared convolution filter w.r.t. each input.I see this question has beenasked before, so let me expand on it a bit... | ptrblck | No, optimizer.step() will just update the passed parameters using the .grad attribute of each parameter.
The gradients will be accumulated in the .grad attribute if you are reusing the shared_weight parameter. |
Samuel_Bachorik | Hello i have this example, how to reshape output from linear layer if i want to put it inside conv2d ?import torch
import torch.nn as nn
x = torch.rand((32,1,28,28))
real_inputs = x.view(-1, 784)
linear = nn.Linear(784, 784)
conv = nn.Conv2d(784, 64, kernel_size=9, stride=1, padding=9 // 2)
x = linear(real_inputs)
... | ptrblck | You would need to add the missing spatial sizes.
The output of linear would have the shape [batch_size=32, features=784].
The conv layer expects an input with 784 channels, so if you don’t want to repeat the activation you would only be able to unsqueeze the missing dimensions since reshaping won’… |
Oussama_Bouldjedri | I have a data with a single channel so the shape is numpy array of 250,164 as I want to use it as a gray scale image what would be the difference of :method 1: add a dimension in numpy arraydata_numpy = np.expand_dims(data_numpy, axis=2)and once on the training loop flip the dimensions to get the proper shape:data=d... | ptrblck | Here is a small example showing the unsqueeze is differentiable and won’t break the computation graph:
x = torch.randn(1, 1, requires_grad=True)
y = x.unsqueeze(0)
y.mean().backward()
print(x.grad)
# > tensor([[1.]])
However, this boils down to the differences between PyTorch and numpy.
Assuming … |
enmanuelmag | Hi! I’m trying to train a YOLOv3. I have RTX 3060Ti. I can performance all the training but the use of GPU is ~0%. The source code of my model, training and dataset logic ishereI found some reference to change the load of items, but I can’t understand entirely how to make the changes. Thanks for your helpimage555×725 ... | ptrblck | I don’t think your current outputs show the wanted utilization and you should be able to select a “Compute” tab in task manager (I’m not deeply familiar with Windows). Alternatively, use nvidia-smi to check the GPU util. |
TARUN_BHATIA | For each of my sentence the 0 labels are very less as compared to the 1’s (for token level classification). I use batches and calculate loss(CrossEntropy) after each batch. How should i create the class weights vector and use it in the loss calculation. Please suggest ! | ptrblck | Yes, a per-batch weighting would work, but you should also consider checking the class distribution of the entire dataset and set the weights once before training to see which approach would be better. |
GuillaumeTong | Here is a small code snippet demonstrating a case where torch.equal does not behave like the == syntax:import torch
t1 = torch.tensor([1])
t2 = torch.tensor([[1,2,3]])
print(t1==t2)
# tensor([[ True, False, False]])
print(torch.equal(t1,t2))
# FalseI was trying to use torch.equal because the output of == syntax gets in... | ptrblck | torch.eq(t1, t2) should work. |
Valentin_Fontanger | Hi,I have a model for super resolution (ESRGAN) and I have the following error :> Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=... | ptrblck | Maybe call .detach() on predicted_true as I assume you don’t want to use it to calculate the gradients in the discriminator again. |
jan_biel | Lets say i have a tensor and apply unique to itt1 = torch.tensor([2,2,3,3,5,1,1,1])
u = t1.unique(dim=0, sorted=True, return_counts=True, return_inverse=True)
->
(tensor([1, 2, 3, 5]), tensor([1, 1, 2, 2, 3, 0, 0, 0]), tensor([3, 2, 2, 1]))
how can i map the counts back to the original tensor like to
t1 = [2,2,3,3,5... | ptrblck | This should work:
print(u[2][u[1]])
# > tensor([2, 2, 2, 2, 1, 3, 3, 3]) |
Xanthan | I want to make a model (which takes batches of images as input) in pytorch and there seems to be this unexpected issue. Pytorch version: 1.7.1 Python version: 3.8.12Code to reproduce:class ABC(nn.Module):
def __init__(self):
super(ABC, self).__init__()
self.out_channels = 64
self.conv1_1 = nn.Conv2d(in_c... | ptrblck | I cannot reproduce the issue in a recent nightly or 1.7.0 so unsure where the error might be coming from since your usage looks correct.
Are you sure you are using this model definition or could you be mixing up model definitions? |
CarlosDanielBez | Hi, sorry for the inconvenience, I’m new to pytorch.I would like to build a custom network that integrates two types of data (tabular and image). In this network, the output of a fully connected layer (tabular data input) multiplies the output of a convolutional network layers. For this, the number of neurons in the ou... | ptrblck | You would need to unsqueeze the missing dimension so that PyTorch can broadcast the smaller tensor:
conv_output = torch.randn(32, 16, 111, 111)
a = torch.randn(32, 16)
out = conv_output * a
# > RuntimeError: The size of tensor a (111) must match the size of tensor b (16) at non-singleton dimension… |
indrajitsg | I am trying to sample from a mixture density:import torch
from torch.distributions.mixture_same_family import MixtureSameFamily
from torch.distributions.categorical import Categorical
from torch.distributions.normal import Normal
# Set values for the mixture
alphas = [0.6, 0.3, 0.1]
means = [30, 60, 120]
sigmas = [5, ... | ptrblck | Pass the means and sigmas as floating point values:
means = [30., 60., 120.]
sigmas = [5., 3., 1.]
and it should work. |
Jose_Garcia | class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.linear_relu_stack = nn.Sequential(
# input of 28*28 and output of 512
nn.Linear(2,10),
nn.ReLU(),
nn.Linear(10,10),
nn.ReLU(),
... | ptrblck | I guess you might not be shuffling the dataset and, since the learning rate is quite low, you might see very similar losses.
Increase the learning rate and shuffle the dataset and the results should differ:
model = NeuralNetwork()
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters… |
ivolis | Hi everyone!Im trying a new approach on nodule recognition in chest x-rays with JSRT dataset where I concatenate a filtered image but i’m having problemas as my dataset is SMALL (247 images) and IMBALANCED (154 images with nodules and without).I have something like thisoriginal_transformation = transforms.Compose([
... | ptrblck | Based on the output it seems balancing might be working. To make sure, you could increase the batch size as it would smooth the random sampling a bit and might create more balanced batches.
Yes, it’s expected to get duplicates in the sampling as the WeightedRandomSampler is randomly sampling the da… |
Dadatata-JZ | Hi folks,I am wondering if there is any existing generations of ResNet (or any architecture) taking large image inputs, such as 1000 by 1000 without resizing to 224 by 224. I have a few high resolution images and fairly sufficient GPU resources, so I want to train the model on them directly. Please share some thoughts.... | ptrblck | The current ResNet implementaions are flexible regarding the spatial input size (as long as it’s not too small) and would accept the 1000x1000 input images (assuming your GPU has enough memory).
I’m not aware of any pretrained models using this resolution so you might want to train the model from s… |
ashesh-0 | I’m trying to optimize specific channels of the input. So, my network weights are fixed and I just want to update select channels of the input. I was able to narrow down the issue to following bits of code. In my understanding following two pieces of code should be identical:parameters = []
for i in range(nTot):
pa... | ptrblck | Your first approach won’t work as you are trying to optimize a non-leaf tensor by slicing it and this error is raised:
ValueError: can't optimize a non-leaf Tensor
If you want to optimize parts of a parameter, either zero out the gradients of the frozen part or create separate parameters and use e… |
Torcione | Hi everyone,I have necessity, starting from a dataset, to divide it in subgroups and define for each of them a corresponding dataloader; is it possible to group them in a dictionary of dataloaders? | ptrblck | Yes, you should be able to create a dict containing DataLoader instances. |
Ninnamon12 | I am attempting to create an encoder/decoder model with mini-batch. I continue to encounter an errors stating:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [32, 6]], which is output 0 of AsStridedBackward0, is at version 2; expected vers... | ptrblck | In your training loop you are adding the current loss (with its computation graph) to loss via:
loss += criterion(predicted,y_train_in[t])
Assuming this addition is only needed for range(target_len) and not for x_train in x_train_data reset the loss value after the backward call. |
Mona_Jalal | How should I fix this error? This model ckpt is built by torch lightning and can be downloaded fromhttps://github.com/ozanciga/self-supervised-histopathology/releases/tag/tenpercentimport torch
def get_model_ciga(path='_ckpt_epoch_9.ckpt'):
"""Model downloaded from: https://github.com/ozanciga/self-supervised-histo... | ptrblck | You are not pushing the input tensor to the GPU, which is why your code fails with the device mismatch. |
Nimrod_Daniel | I try to do automatic mixed-precision, but unfortunately I get an error that says that all tensors are not on the GPU. When I check the model and all variables it seems ok.Any idea why it fails during the forward pass, and how to fix it?(I chopped a lot of code so it’d be the shortest to reproduce the error)(torch 1.10... | ptrblck | Your new module should still be on the CPU since you are:
creating the inception_v3` model
push it to the GPU
replace model.fc with a new nn.Linear on the CPU
don’t push it to the device |
Sam_Lerman | I have modules composed of modules composed of modules. Some of these modules might not be compatible with DataParallel, I’m not sure, because they don’t return tensors (for instance, they return distributions). I would like to enable parallelization for as much of the architecture as possible… is there any downside to... | ptrblck | Yes, I would think so as the scatter/gather ops would be called on each submodule. Check the linked blog post, which describes this, and apply the same logic for each submodule to visualize how this approach would work. |
tobiaaa | I have a Batched Audio Signal with the Shape [N, C, L] with e.g. N=4, C=4, L=2048, which I want to apply aSliding Window with Overlapto, and later I want to reconstruct the original shape by usingoverlap and add.Example:Input Shape → [4, 4, 2048]After Sliding Window with Window Size 256 and Overlap 128 → [4, 4, 15, 256... | ptrblck | nn.Unfold would return the same output if you reshape it accordingly:
x = torch.arange(0., 16384).view(2, 4, 2048)
# shape: (2, 4, 2048)
x_framed = x.unfold(-1, 256, 128)
# shape: (2, 4, 15, 256)
# module approach
unfold = nn.Unfold(kernel_size=(256, 1), stride=(128, 1))
out_ref = unfold(x.unsque… |
mrityu | Hey,Please refer to the below custom model class’s forward method:def forward(self, x):
x = self.layer1(x)
temp = self.layer2(x)
x = self.layer2(x)
x = self.out(x)
return x, tempI am trying to extract an intermediate layer’s output using this(layer-2 output). I am aware of the forward hooks and that... | ptrblck | Depending on the implementation of self.layer2 your new code snippet might change the behavior e.g. if batchnorm layers are used. In this case you would update the running stats twice since two forward passes are used in the new code. |
samin_hamidi | I was wondering if the parameters of batch_norm layers are considered when computing the L2_norm of weight decay in Pytorch’s implementation? | ptrblck | The weight_decay argument will be applied to the current parameter group. I.e. if you are passing the batchnorm parameters to this group (or re just using a single group and are passing all parameters) weight decay will also be applied on them. |
nicozhou | Is there any way to Splitting tensor into sub-tensors in overlapping fashion? My input is video frames B x T x C x H x W. I want to split it become sub-tensors for example, frame1~5, frame 2~6, frame 3~7,… . Is there any built-in pytorch function to do that? | ptrblck | Yes, you can use tensor.unfold:
x = torch.arange(10)
y = x.unfold(dimension=0, size=5, step=1)
print(y)
> tensor([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8],
[5, 6, 7, 8, 9]]) |
nicozhou | Hi, I have read a lot of thread regarding contiguos tensor, I know some may say that it affect the speed when forwarding, but I am curious, does it affect network training result? for e.g accuracy, loss, etc.It may seem that when usingtorch.reshape, there is no need to use contiguous tensor right? | ptrblck | If an operation expects a contiguous tensor, it’ll make the memory contiguous explicitly since otherwise the indexing might be wrong which would influence the training in a bad way.Yes, reshape combines a view and contiguous op. As described, PyTorch will either raise an error if a contiguous te… |
oasjd7 | I want to make two images which are applied with different strong augmentations.I gave up configuring two datasets to which each augmentation was applied. Because the dataset is too large and the CPU failed to process it.So, I tried compose only one dataset and make two versions of augmentations in each mini-batch. Bel... | ptrblck | You could apply both transformations inside the Dataset.__getitem__ and return both transformed samples to avoid the additional transformation with the for loop in the DataLoader loop. |
Mat_Hopps | Hi all,I am implementing part of the code for Federated Matched Averaging (full code found here:https://github.com/IBM/FedMA/blob/master/language_modeling/language_fedma.py)An error occurs when the following line runs:batch_weights_norm = [w * s for w, s in zip(weights_bias, sigma_inv_layer)]And, the runtime error isR... | ptrblck | Yes, if s is a numpy array create the tensor via torch.from_numpy(s). Otherwise w * s will try to convert w to a numpy array and thus the error message will be raised. |
nbansal90 | Hello All,I am looking to define a model, which is a subset of existing models such asResNet18,ResNet34orResNet101. In this context i know that pytorch already provides these (pretrained) models throughimport torchvision.models.In my case I was looking for a specifc scenario, where supposing I selectResNet34as my base ... | ptrblck | You could write a custom model, derive from Resnet34 as its base class, and assign the wanted modules to your new Base and Head submodules.
To do so, check the torchvision implementation and make sure e.g. all original functional API calls are used in your new forward method as well (assuming you d… |
julianolm | Hello, I was happy to find pytorch dataset support for theDescribable Texture Dataset (DTD)onthe docs.However, after I’ve failed trying to import it in my google colab instance (using torch v1.10 and torchvision 0.11) I noticed that it was only available on the main (0.12) unstable version of torchvision.So what should... | ptrblck | Alternatively, you could also install the nightly binaries instead of building from source. |
chinmay5 | I am running into a strange issue when using the mixed precision, grad_scaling function. The Pytorch version is 1.9, CUDA is 11.1 and I am usingtorchiofor augmentation. I am not exactly sure what this error indicates and what should be done for debugging. If I remove the mixed precision training, I do not see the error... | ptrblck | The general steps for debugging an illegal memory access would be:
update PyTorch to the nightly version and check, if this might have been a known and already fixed issue
if that doesn’t help: rerun the code with CUDA_LAUNCH_BLOCKING=1 and check which operation is failing to narrow down if it’s c… |
OBouldjedri | I want to calculate the top k accuracy using the sklearn implementation:I was wondring if using this is correctoutput = model(data)target_top_numpy=target.cpu().detach().numpy()predicted_top_numpy=output.cpu().detach().numpy()top2=top2+top_k_accuracy_score(target_top_numpy, predicted_top_numpy, k=2,normalize=False,labe... | ptrblck | From thedocs:
y_score array-like of shape (n_samples,) or (n_samples, n_classes)
Target scores. These can be either probability estimates or non-thresholded decision values (as returned bydecision_functionon some classifiers). …
If you copy/paste their example and e.g. scale or shift y_score,… |
Matteo_Ciotola | I have tried to implement a “complicated” (for me…) loss function (a porting from MATLAB repo).Strangely it compiles, but when I try to call the.backward()function it returns to me a NoneType.I’m analyzing the code but, even if there are many things that I’m not understanding, I don’t find the real cause of the problem... | ptrblck | You are manually creating a new tensor with requires_grad=True inside your module:
values = torch.zeros((bs, dim3, stepx, stepy), device=self.device, requires_grad=True)
which is not attached to any computation graph (and thus also not to the input to the criterion).
Unrelated to this particular … |
SemiSimon | The following minimal code prints the GPU memory usage in bytes after each evaluation of the network.The GPU memory usage increases at every iteration at an alarming rate. System RAM usage stays constant.I have two questions: why there is a memory leak in the first place? I’ve settorch.no_grad()(andself.eval(), but thi... | ptrblck | You are not seeing a memory leak, but an expected increase in memory usage since you are appending the output of your model with its entire computation graph to estimates in each iteration.
If you don’t want to store the entire computation graph, .detach() the output or call item() on a scalar tens… |
Ju_Jeremy | I’m using p4d-24xlarge instance(NVIDIA A100) on AWS with CUDA/drivers showing installed correctly, but torch.cuda doesn’t load up. The instance has been setup using the step here.Can anyone please tell me what might be causing this? Here are more info about my set up. Thanks in advance!Errorconda install pytorch torchv... | ptrblck | I would generally recommend to update to the latest PyTorch release and, if possible, also the NVIDIA drivers.
If this error is raised randomly, it could point towards a setup issue where the GPU is dropped.
This could indicate either a broken driver or e.g. overheating of the GPU, which will shut… |
amin_p | Hello,I’m new to the PyTorch, and I’m trying to build a network with some additional trainable variables.#===============================================================================
# Nnet
#===============================================================================
class Nnet(nn.Module):
def __init__(self,... | ptrblck | The error is raised since torch.nn.init.xavier_uniform_ expects a tensor as its input, not a list of sizes.
Use:
W = nn.Parameter(torch.nn.init.xavier_uniform_(torch.empty([layers[l], layers[l+1]]), gain=1.0))
and the error should be solved.
However, since you are using plain Python lists to sto… |
Valentin_Fontanger | Hi,I am trying to implement SRGAN, I have looked at many implementation on Github and none of them used the retain_graph = True option.I have the following error :RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when ... | ptrblck | You are accumulating the losses in:
d_loss += fake_loss + true_loss
...
g_loss += content_loss + g_bce_loss + pixel_loss
which will keep the computation graphs alive and Autograd will thus try to backpropagate through the computation graphs from all iterations.
I guess this behavior is not inten… |
PiTorch | Hi,Suppose you have a convolution layer (C), max pooling layer (MP), and dense layers (Ds) in an architecture that follows:Input → C1 → C2 → MP → Ds → outputYour input is a 10x2 matrix (rows x columns). Your C1 and C2 kernel is a 3x1. So after the C1, you get a 8x2 matrix, after C2 a 6x2. The MP is a (1,2), so you get ... | ptrblck | Yes, Autograd will track the flip operation as seen in this small example:
x = torch.randn(2, 2, requires_grad=True)
print(x)
> tensor([[-0.6456, 1.6832],
[ 0.3877, 1.0371]], requires_grad=True)
grad = torch.tensor([[1., 0.],
[1., 0.]])
x.backward(grad)
print(x.gr… |
yolo | miniconda3/envs/smr_env1/lib/python3.7/site-packages/torch/cuda/init.py:106: UserWarning:NVIDIA GeForce RTX 3050 Ti Laptop GPU with CUDA capability sm_86 is not compatible with the current PyTorch installation.The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_61 sm_70 sm_75 compute_37.If you w... | ptrblck | I don’t think that’s the case, as the 1.10.0+cu113 pip wheel ships with these compute capabilities:
>>> import torch
>>> torch.__version__
'1.10.0+cu113'
>>> torch.cuda.get_arch_list()
['sm_37', 'sm_50', 'sm_60', 'sm_70', 'sm_75', 'sm_80', 'sm_86']
while yours returns:
sm_37 sm_50 sm_60 sm_61 sm_… |
meshghi | Hi, for calculating my loss function, I’m using torch.squeeze to change the dimension of the output from [N,1,H,W] to [N,H,W]. I was wondering if this action breaks the computation graoh and cause failure of autograd? | ptrblck | No, squeeze won’t detach the tensor and Autograd will properly calculate the gradients for the original tensor as seen here:
x = torch.randn(2, 1, 2, 2, requires_grad=True)
y = x.squeeze(1)
y.mean().backward()
print(x.grad) |
thatdario | Hello, I am new to Pytorch (third day using it) and I am finding some trouble converting a model I had in keras. The model is the following:X_input = Input(shape = (resized_image_size, resized_image_size, 3), name = ‘X_input’)X = Conv2D(8, (3, 3), strides = (1,1) , padding = 'valid')(X_input)
X = MaxPooling2D(pool_size... | ptrblck | The first conv layers look alright (your code is a bit hard to read and you can post code snippets by wrapping them into three backticks ```).
You could either calculate them manually, print the activation shape in forward before passing it to the first linear layer and adapt the in_features bas… |
zhenkai | import torchvision.models as modelsbase_model = models.densenet161(pretrained=True).featuresHow can I insert additional layers into the pre-trained model above? In densenet, the input will go through conv0 layer, followed by denseblock1, …, denseblock4 before outputting 2208 channels feature maps. I would like to inser... | ptrblck | You could try to manipulate the model initializationhereand add your custom modules. However, this would of course disallow loading the pretrained state_dict directly, and you could either use the strict=False approach (I wouldn’t recommend it without a proper verification as it could easily break… |
torchimport | Hi,I have a question about controlling the batchnorm.As I know, if we apply eval() mode,the batchnorm stops tracking the running stats and uses the tracked running stats that is registered in the buffer.However, I would like to stop tracking running stats but use the stats of a given batch in the forward pass.Is there ... | ptrblck | I don’t know if you still want to use the running stats later or not. In the former case, call model.bn.train() to use the input activation stats and reload the state_dict on these layers afterwards (or manually reset the running stats). In the latter case, you should be able to replace the pretrain… |
etrommer | Hi, I am running into a slightly odd problem when using a Dataloader (wrapped in PyTorch Lightning DataModule). I’m trying to train a VGG network using the TinyImageNet data set. I have reorganized the validation set to have the same file structure as the training set. If I load my dataset like this:def setup(self, sta... | ptrblck | I assume your ds_full contains 100000 samples and you are basically applying random_split on ds_full to get df_train back.
In this case, random_split will shuffle the indices which would make a difference in the model convergence (if you are not shuffling in the DataLoader). |
gonzrubio | What would make one implement a custom loss as a class instead of as a regular function?For instance, this implementation of theYOLOv1loss function is done by expandingnn.Module. Whereas thisMSE lossis implemented via a function.I guess my question is, why isevery lossimplemented as a class in PyTorch if one can simply... | ptrblck | The advantage of using classes (as nn.Module in this case) is that they can store internal states without explicitly passing all arguments. E.g. if you want to get the unreduced loss you could use the module via:
x = torch.randn(10, 10)
y = torch.randn(10, 10)
# module
criterion = nn.MSELoss(reduc… |
cyjung | I am trying to run multiple processes that shares the same GPU. I need to release GPU memory so that another process can use it.By reading the docs I understand that pytorch does not release GPU memory right away, and I need tocuda.empty_cacheBut I found that nvidia-smi stays high even afterempty_cache.cuda.memory_summ... | ptrblck | The first CUDA call will create the CUDA context, which will take some memory on the GPU (depending on the compute capability of the device, CUDA versions, number of loaded kernels etc.) and will not be reported by PyTorch but is visible via nvidia-smi. |
ptrch_c_m | Hello,I have 2D tensors, where each row starts with1and continues with a variable length of1s followed by0s.I want to turn the first and the last1of each row to0.For instance, for a tensor withtorch.Size([3, 7]), that initially istensor([[1, 1, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0... | ptrblck | This should work:
x = torch.tensor([[1, 1, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0]])
tmp = (x == 1).cumsum(dim=1) - 1
idx_start = tmp[:, 0]
idx_stop = tmp[:, -1]
idx = torch.stack((idx_start, idx_stop), dim=1)
x[torch.arange(x.size(0)).unsq… |
Olivier-CR | Hi,I have a situation with a vision training DataLoader taking a long time (T) and memory (M) to load at the beginning of each epoch. I notice that when we reduce num_workers by a factor of 4, T’=T/4 and M’=M/4.I’d like to better understand how num_workers and getitem are connected: is num_workers the number of paralle... | ptrblck | Approach 1 is used currently. I know there was a feature request for 2 but I don’t know what the status of it is. |
kshitijs | I am new to Pytorch coding and recently have been working on a project on Pycharm, where the main goal to achieve is, my LSTM based neural network would classify an activity based on video input. The way this works is, my video input is first converted to individual image frames. Now based on the difference between eac... | ptrblck | I would try to narrow down which part of the code tries to allocate the mentioned 32GB and then check how to avoid it. As previously described, you might want to append the tensors to a list first if this line of code is indeed creating the issues. |
OBouldjedri | I working on classification problem with 11 possible labels (classes)when I use the sklearn implementation of top k accuracy (in my case I use k=2).I get this error:top2=top_k_accuracy_score(target_top_numpy, predicted_top_numpy, k=2)Number of classes in ‘y_true’ (10) not equal to the number of classes in ‘y_score’ (11... | ptrblck | Since your target_top_numpy doesn’t contain all unique labels, you have yo provide the labels argument as described in thedocsof sklearn.metrics.top_k_accuracy_score:
top2 = top_k_accuracy_score(target_top_numpy, predicted_top_numpy, k=2, labels=np.arange(11)) |
zetyquickly | Hello,During experiments came across the following issue.I have custom convolution class that based ontorch.nn.Conv2dimplementation.class FastConv(object):
@staticmethod
def forward(x, w, b, conv_param):
# print(x.shape, w.shape, b.shape, conv_param)
N, C, H, W = x.shape
F, _, HH, WW = w.shape
stri... | ptrblck | Both approaches work in my setup:
class FastConv(object):
@staticmethod
def forward(x, w, b, conv_param):
# print(x.shape, w.shape, b.shape, conv_param)
N, C, H, W = x.shape
F, _, HH, WW = w.shape
stride, pad = conv_param['stride'], conv_param['pad']
layer = torch.nn.Conv2d(… |
Hamster | To my knowledge there isn’t an official way from libtorch to use CUDA Graphs like on the latest PyTorch release. In this case, is it still possible (& safe?) to use “vanilla” CUDA Graphs from the CUDA API as described here:Getting Started with CUDA Graphs | NVIDIA Developer Blog? What would be safe to record using such... | ptrblck | I don’t know how exactly you want to use CUDA graphs directly, but would claim it’s prone to error due to the strict memory requirements. The better way might be to try out to use the backend API directly as definedhere. |
Pia_Ludemann | I wonder if there is a way to prevent the DataLoader from callinggetitemso often, so as to say something like:Do only load 5 sequences in advance (and not plenty as it does now, which has problems with cuda out of memory).Has anyone tried this before? | ptrblck | You can change the prefetch_factor, which is defined as:
prefetch_factor (int, optional , keyword-only arg) – Number of samples loaded in advance by each worker. 2 means there will be a total of 2 * num_workers samples prefetched across all workers. (default: 2) |
Bar_Lerer | Hi all, I have been doing some reading on this issue online and tried the suggested solutions but with no success,For some context, I am using a pre-trained model, and I want to use my modified classifier.This is how I create the model:model = torchvision.models.vgg11(pretrained=True)
flag = 0
# We want this to happen ... | ptrblck | This line of code:
pred = (pred > 0.5).float().squeeze()
will detach pred as the comparison is not differentiable.
Pass the probability directly to nn.BCELoss (or better: remove sigmoid and use nn.BCEWithLogitsLoss for better numerical stability) and it should work. |
Mona_Jalal | I am getting this warning without any line number so I am unsure which line of code it relates to. Could you please shed some light on this?UserWarning: size_average and reduce args will be deprecated, please use reduction='mean' instead.I would like to know where I am expected to used the following?reduction='none'Ful... | ptrblck | This warning is raised if you use the deprecated reduce or size_average argument in a criterion.
Based on your last posts (e.g.this one) you are using:
``python
self.criterion = nn.BCEWithLogitsLoss(reduce=False) |
Ilker_GURCAN | Hello pytorch devs and users,My training runs in a distributed environment and I have to ensure that each parameter is initialized to the same value by calling the following instructions before spawning my processes:def setRandomSeeds(randomSeed=0):
torch.manual_seed(randomSeed)
torch.backends.cudnn.determinist... | ptrblck | You might have forgotten to call the sampler.set_epoch() method. From thedocs:
In distributed mode, calling the set_epoch() method at the beginning of each epoch before creating the DataLoader iterator is necessary to make shuffling work properly across multiple epochs. Otherwise, the same orderi… |
Orcun_Deniz | Im pretty new to PyTorch and working on my first training. I noticed that after an epoch of training when I did validation without going into eval mode and using the no_grad, GPU memory consumption goes sky high until there is no GPU memory left. It would be awesome if somebody could explain what is happening under the... | ptrblck | If you don’t use with torch.no_grad(), Autograd will create the computation graph, which is needed to calculate the gradients in the backward pass.
Now if you store a tensor, which is attached to this computation graph, such as the loss or model output, in e.g. a list, the whole computation graph w… |
Valentin_Fontanger | Hi,I am trying to build a model that does super-resolution based on this idea :GitHub - david-gpu/srez: Image super-resolution through deep learningIt is almost like a DCGAN, but instead of having a noise of size (100,1,1) as input for the generator, you provide the 16x16 downscaled true image (from my understanding). ... | ptrblck | The error is most likely caused in these lines of code:
# training the generator
generator.zero_grad()
true_labels = fake_labels.fill_(1.0)# tricking the discriminator
dg_out = discriminator(generated_images)
generator_bce_loss = bce_criterion(true_labels, dg… |
Dazitu616 | I’m training a network (say it’s consisted ofmodule1andmodule2) with two lossesloss1andloss2. Forloss1, I only want to BP it tomodule1, while forloss2I want to BP it to the whole network. Can I do something like this to achieve so? Is there any more elegant way to do so?optimizer.zero_grad()
loss1.backward(retain_grap... | ptrblck | Instead of zeroing out some gradients, you could also pass the inputs argument to backward to calculate only the gradients for these tensors.
Yes, I don’t see any issue with using the approach in amp (once you’ve verified it’s working without amp). |
NicoAdamo | Hi all, a bit of a basic question here - I am trying to work with a somewhat small dataset, and apply augmentation techniques to increase my training set size. My DataLoader is currently very basic, of the form:class Dataset(torch.utils.data.Dataset):
def __init__(self, images_path):
super(Dataset, self).__ini... | ptrblck | You could transform the img multiple times and just return all of them. Inside the DataLoader loop you could then reshape the additional images to the batch dimension and reduce the batch_size of the DataLoader by the same factor. |
AntMorais | Greetings,I get this error when I train a resnet18 model from Torchvision on a custom dataset. It only happens on the 2nd epoch after a few dozen iterations.---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-in... | ptrblck | The image decoding is failing and torchvision seems to reraise the error. Are you able to load the file with another library and if so, could you save it using a different file name, and try to load it again via torch.ops.image.decode_image? |
asura | Hi,I had a very noob question:I want to change my tensor shape from[5, 3, 84, 84]to[5, 1, 28, 28]That is, change image size from 84x84 to 28x28, and convert RGB to GrayScale.P.S. I don’t want to make use of transforms, as I want to keep the original tensor[5, 3, 84, 84]for a different operation.Thank you! | ptrblck | You could still use transformations and keep the original tensor alive as seen here:
trans = transforms.Compose([
transforms.Grayscale(),
transforms.Resize((28, 28)),
])
x = torch.randn([5, 3, 84, 84])
out = trans(x)
print(x.shape)
# > torch.Size([5, 3, 84, 84])
print(out.shape)
# > torch… |
hjung | In Windows 10, my computer has NVIDIA driver 456.71 and I installed PyTorch usingconda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorchThen, I checked whether PyTorch used CUDA by typing the followings:import torch
torch.cuda.is_available()And it returnedTrue.It’s pretty weird to me because I’ve heard... | ptrblck | Yes, you are right and don’t need to install a local CUDA toolkit (just the drivers) unless you want to build PyTorch from source or a custom CUDA extension. |
OBouldjedri | I was wondering on what size of ImageNet, the pretrained models of torch vision were pre-trained ?ImageNet 1KorImageNet21KorImageNet22K | ptrblck | Based on this older post:
they are pretrained on 2012 version of it and I would assume on the 1K classes version, since all pretrained classification models have 1000 output logits. |
Mona_Jalal | I have two machines that I need to check my code across one is Ubuntu 18.04 and the other is Ubuntu 20.04.In Ubuntu 18.04 I have:$ python
Python 3.8.0 (default, Dec 9 2021, 17:53:27)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.__version__
'1.9.... | ptrblck | You have to “call” the decorator as given in the docs and examples:
with torch.cuda.amp.autocast():
... |
cllfwmc | I have implemented a simple network with nn.Module and I encountered the problem about regularization. The optimizer provides ‘weight_decay’, but it includes all the parameters. I want to do L2 excluding bias with which may cause underfitting.I calculated the regular cost and separated the weight and bias. However when... | ptrblck | You could check, if the parameters are updated using the current approach, as I’m not sure if your approach of using the state_dict to separate the weight and bias parameters would work.
Directly accessing the parameters would work:
weight_list = [p for n, p in model.named_parameters() if 'weight'… |
Mona_Jalal | So, my class 0 is 20% and class 1 is 80% of the entire data and I have stratified 5 fold train/val/test with division of 60/20/20.However, my predicted labels for test set are stuck at 1.Any thoughts how to fix this? I used the weighted loss suggested inUnclear about Weighted BCE LossIf you would like to use the weight... | ptrblck | The error message explains why your code is failing:
RuntimeError: torch.nn.functional.binary_cross_entropy and torch.nn.BCELoss are unsafe to autocast.
Many models use a sigmoid layer right before the binary cross entropy layer.
In this case, combine the two layers using torch.nn.functional.binary… |
Sai_Kishore | I am trying to convert a Tensorflow Code to Pytorch. I am stuck at implementing this line.Conv3DTranspose(nb_channels, kernel_size=(3, 3, 3), kernel_regularizer=l2(0.001), strides=_strides, padding='same')(y)How to add a kernel_regulariser in pytorch. | ptrblck | No, you would have to add all layers which should be regularized to the loss calculation or to the optimizer’s parameter list containing the weight_decay. |
Hasan_Khan | Hello, can anyone explain me this error and help me to resolve it. I am trying to get the predictions for my RNN trained model. However, while generating the predictions I’m having this error.embedding(): argument ‘indices’ (position 2) must be Tensor, not builtin_function_or_methodHere is the code and error snippet.im... | ptrblck | Based on the error message the second argument (prediction_loader) is passed as the input to the model, which is a DataLoader instance and will thus fail.
Pass tensors to the model by iterating the DataLoader instead. |
Yuv | Hey,I have an image with the size (1,32,32) and I’m using Conv2D with kernel size of 5x5 and stride 1, which means it gives (28,28) after the convolution.I want to get the values of multiplication between the kernel weights(5x5) and the inputs(5x5 in every step of all 28x28 steps) before the method sums up all the 25 ... | ptrblck | Unfolding should work and you could use an elementwise multiplication which wouldn’t apply the reduction. |
FelGC | In Pytorch, when analyzing the color histogram e.g. of the MNIST dataset using the pytorch data loader, it yields different results when shuffle is True/False. In fact, setting shuffle==True returns the correct result, whereas shuffle==False does not. Both versions (True/False) are supposed to return the set of data ob... | ptrblck | The difference is caused in the large number in hist[0] and hist2[0].
The default float32 dtype can represent integers between 0 and 16777216 exactly but starts to round for larger (or smaller negative integers) as:
Integers between 2**24=16777216 and 2**25=33554432 round to a multiple of 2 (even… |
AdePommereau | Hello guys,I have a problem with a list of modules. I have coded a module called BranchRoutingModule. I would like to create a list from this module.I have the following code:def _branch_routings(self):
# structure = [nn.ModuleList([BranchRoutingModule(in_channels=self.in_channels) for j in range(int(pow(2, i)))]) ... | ptrblck | Your code works fine:
class BranchRoutingModule(nn.Module):
def __init__(self, in_channels=512, epsilon=1e-12):
super(BranchRoutingModule, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=1)
self.l2norm = lambda x: torch.nn.functi… |
jasperhyp | Hi, I accidentally forgot to putmodel.train()within each epoch, and yet in each epoch my evaluation function callsmodel.eval(). Weirdly, the train & evaluation losses and metrics are all improving as training proceeds (which makes me omit this issue for a month), but when I extract the final node embeddings (I’m trai... | ptrblck | model.train() will change the behavior of some layers, such as enabling dropout and using the batch stats in batchnorm layers while also updating the running stats. Depending on the model architecture and which layers are used, model.train()/.eval() might or might not have any effect (you should sti… |
Gaborandi | i’m working on distilbert for text classification, and want to save the tensors into a data frame so i can use it again as feature generatorto illustrate my question more:below are token IDs for one sentence in a row in csv file i’m working on :Token IDs: tensor([ 101, 11113, 2080, 25876, 2542, 15009, 11290, 22291, ... | ptrblck | 1 To convert a tensor to a numpy array use a = tensor.numpy(), replace the values, and store it via e.g. np.save.
2. To convert a numpy array to a tensor use tensor = torch.from_numpy(a). |
Ilyes_hm | Hello,I want to take the output of the forward pass and detach it to generate a matrix (that is similar to the input) using an external function (not a pytorch function), then create a loss function based on this generated matrix and the input matrix.does this cause a problem for the gradient?Thank you | ptrblck | Yes, using other libraries or explicitly detaching the tensors won’t allow Autograd to track these operations and will thus detach the tensor from the computation graph (parameters used in previous operations also won’t gradients).
To use other libraries you could write a custom autograd.Function a… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.