user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
wxystudio | I have n points as tensor(n, 2), the second dimension is x and y coordinate on an image, I want to convert them to tensor(n, W, H), the W and H are x and y coordinate on the image.How can I do itwith no for loop?thanks | ptrblck | If you want to set a specific value for these coordinates into the image, this code should work:
img = torch.zeros(4, 5, 5)
x = torch.randint(0, 5, (4, 2))
img[torch.arange(img.size(0)), x[:, 0], x[:, 1]] = 1.
print(img) |
Coder1221 | how i can get the orignal image back?Screenshot from 2020-10-13 11-15-071366×768 207 KB | ptrblck | The usage of reshape is wrong as it will interleave the image.
Use permute to permute the dimensions of the tensor instead.
If you want to get the original pixel values back, you would have to “denormalize” the image such that the values are again in the original range (most likely [0, 255]) inste… |
makeastir | Hi.I suffering from cuda version issues.In my case likes below :A case : pytorch 1.5, cuda 11.0B case : pytorch 1.0, cuda 9.0To run A case project, then i correct my cuda local path to 11.0.Likewise B case project also correct my cuda local path to 9.0.It’s really inconvenient job.But someone said that if i installed c... | ptrblck | If you’ve built PyTorch using different CUDA versions (local installations) in different conda environments, you wouldn’t need to change the CUDA path as long as you are not rebuilding PyTorch or CUDA extensions.
I.e. running PyTorch operators alone would work in your conda environments using the l… |
Ravi_Raju | Hi I’m trying to linearly interpolate between two models but it doesn’t seem to be working. Here is my function to do the interpolation. I have the output attached below.`def interpolate_models(model, model1):
alphas = np.linspace(0,1,10)
acc_array = np.zeros(alphas.shape)
iter = 0
tic = time.perf... | ptrblck | The manipulation of the .data attribute is not recommended as it might yield unwanted side effects.
Could you try to “interpolate” the models by using their state_dicts and load the new one into a model instead? |
add023 | TLDR: I am unable to fully utilize GPU because a lot of time is spent loading images. What are some strategies to always keep the GPU utilized?Say I have a batch of size 8. Each element in the batch is a video folder with Y number of frames, where Y is between 90 and 400. The number of frames differs in each video fold... | ptrblck | If you use num_workers > 1 you are already creating multiple workers, where each worker will load a batch and push it to the queue.
If you are still seeing a slowdown in loading the data, it would mean that your current data loading pipeline is still not fast enough.This postgives some insights … |
DenisDiachkov | Hello, I want to implement Conv2d with different kernels for each pixel. Is there any way to make it in pytorch and keep it as efficient as regular convolution? | ptrblck | Yes, you could start by implementing the desired work flow using e.g. nested for loops and once it’s working use unfold to apply a matmul to speed it up, if that fits your use case.
That won’t be straightforward, but you could e.g. write a custom CUDA extension for your convolution to get another… |
peepeepoopoo | I’m a little confused as to how PyTorch would keep track and update the weight matrix (point multiplication to the input matrix), should the weight matrix be fed to the network itself where it will be kept track of manually by the user after each update, or its going to be updated and track automatically by the PyTorch... | ptrblck | Generally you could use nn.Modules, which will keep the parameters as internal attributes, or use the functional API where you can keep track of all parameters manually.
I would recommend to take a look at sometutorialsto see different work flows and use cases. |
enterthevoidf22 | hi,so i saw some posts about difference between setting torch.cuda.FloatTensor and settint tensor.to(device=‘cuda’)i’m still a bit confused. are they completely interchangeable commands?is there a difference between performing a computation on gpu and moving a tensor to gpu memory?i mean, is there a case where i want t... | ptrblck | Changing the type to torch.cuda.FloatTensor would not only push the tensor to the default GPU but would also potentially transform the data type.
The to('cuda:id') operation would only transform the tensor to the specified device as seen here:
x = torch.tensor([1])
print(x.type())
> torch.LongTens… |
sunyoung | VGG((features): Sequential((0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(0_linear_quant): LinearQuant(sf=None, bits=8, overflow_rate=0.000, counter=20)** (1): ReLU(inplace=True)**** (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))**** (2_linear_quant): LinearQuant(... | ptrblck | It seems to work using this small example:
act_in = {}
act_out = {}
def get_hook(name):
def hook(m, input, output):
act_in[name] = input[0].detach()
act_out[name] = output.detach()
return hook
model = nn.Sequential(
nn.Conv2d(3, 6, 3, 1, 1),
nn.ReLU(),
… |
K_steven | Hi everyone!I am newbie for PyTorch.i try to rewrite my network from keras to pytorch. keras can decrease loss to 500 but pytorch stuck at 1000.[keras]Seq_deepCpf1_Input_SEQ = Input(shape=(34, 4))Seq_deepCpf1_C1 = Convolution1D(80, 5, activation=‘relu’)(Seq_deepCpf1_Input_SEQ)Seq_deepCpf1_P1 = AveragePooling1D(2)(Seq_d... | ptrblck | I can’t find any obvious differences.
Sometimes an unwanted broadcasting takes place in the loss calculation, if you don’t pass an output and target in the same shape to nn.MSELoss, which should raise a warning but if often overlooked.
Could you double check it in your PyTorch code? |
shashank_gupta1 | I have a input with dimension (Batch Size * MAX_NUMBER_SENTENCES * MAX_SENT_LENGTH). Basically a list-of-list-of token indices.I have initialized an embedding layer asself.query_embedding = nn.Embedding(len(word_lookup_table), inp_dim)I have initialized it with pretrained word embeddings. Now when I pass an input of th... | ptrblck | Yes, that’s the expected output as shown in thedocs.
nn.Embedding layers are adding the embedding_dim dimension as the last additional dimension to the output tensor. |
pregenRobot | I am working on a multilabel text classification task with Bert.The following is the code for generating an iterable Dataset.from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
train_set = TensorDataset(X_train_id,X_train_attention, y_train)
test_set = TensorDataset(X_test_id,X_tes... | ptrblck | No, since class labels are expected.
Use target = torch.argmax(target, dim=1) to create the expected target tensor. |
over9k | I am using the Resnet18 model (https://pytorch.org/docs/stable/torchvision/models.html#id10) for 2D image classification, with 2 output classes. The final layer is the fully connected (fc) layer according to the model descriptions.How would I go about getting the probabilities of the output classes? For example, now I ... | ptrblck | Yes, just use F.softmax outside of the model:
output = model(data) # output contains logits
# you can calculate the loss using `nn.CrossEntropyLoss` and the logits output
loss = criterion(output, target)
# and you can calculate the probabilities, but don't pass them to `nn.CrossEntropyLoss`
probs… |
Bahaa_Kattan | I’m working on text classification problem.here is all the codeimport torch.nn as nn
import torchtext.data as data
import pandas as pd
import torch
import torch.nn.functional as F
Text = data.Field(batch_first=True, include_lengths=True)
LABEL = data.LabelField(dtype=torch.float, batch_first=True)
feilds = [('text', ... | ptrblck | hidden has the shape [num_layers * num_directions, batch, hidden_size].
Since you are slicing it in dim0 and concatenating in dim1 here:
x = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1)
the output shape of x will be [batch_size=32, 60], so you would need to increase the in_features of s… |
Joe1Chief | When I use DataParallel(), the maximum batch size can be set to512(cudnn.benchmark is disabled.), but DistributedDataParallel only supports setting batchSize to128.Could cudnn cause such a problem?This is the main structure of my code.if __name__ == '__main__':
...
# Multi GPU
print(f'Running DDP on rank: {... | ptrblck | AMP shouldn’t use more memory and I assume you are trying to use the global batch size in each process and thus GPU.
As explainedhereyou should set the batch_size for each GPU as the local batch size (by dividing the global batch size by the number of GPUs). |
peepeepoopoo | I was trying to implement an MLP layer that takes a 3-dimensional data, but only process data on one axis only (so the other two dimensions are considered channels in this case). I’ve done a quick look around on the documentation page and couldn’t seem to find anything similar to what I want. Granted, I could just call... | ptrblck | It seems to work for me in 1.7.0.dev20200830:
x, y, z, channels = 2, 3, 4, 5
input = torch.randn((x, y, z, channels))
lin = nn.Linear(channels, 6)
out = lin(input)
print(out.shape)
> torch.Size([2, 3, 4, 6]) |
enterthevoidf22 | i’m trying to write a simple image generator as follows:def class_visualization_update_step(img, model, target_y, l2_reg, learning_rate):
########################################################################
# TODO: Use the model to compute the gradient of the score for the #
# class target_y with re... | ptrblck | As the warning explains you are trying to access the .grad attribute of a non-leaf tensor, which won’t be populated by default.
You can call .retain_grad() on the non-leaf Tensor to access the gradient after the backward call.
Also note that the usage of the .data attribute is not recommended, as … |
seyeeet | I have a Class like this, I want to freeze Net1 and Net3 during my training.Would it be possible?class MyNetwork(nn.Module):
def __init__(self, a, b, c, d):
super(MyNetwork, self).__init__()
self.a = a
self.b = b
self.c = c
self.d = d
self.Net1 = nn.Line... | ptrblck | model.eval() does not freeze the parameters, but changes the behavior of some modules.
E.g. dropout will be disabled and the running stats in batchnorm layers will be used.
To freeze trainable parameters, you would have to set their .requires_grad attribute to False.
E.g. this would freeze all pa… |
wmpauli | I would like to update WeightedRandomSampler.weights between epochs, e.g. for curriculum learning. A look at its class implementation suggests that I can just update the class field “weights” in b/w epochs, because the__iter__method simply draws from the multinomial distribution - with self.weight as input. Is that cor... | ptrblck | It might work if you manipulate the weights attribute, however I also think you shouldn’t see any performance regression if you create a new sampler and a new DataLoader after the epoch, as it should be relatively cheap compared to the iterations. |
spadel | I want to make some transformations outside the Dataloader withtorchvision.transforms.ColorJitter. However, when I usehue!= 0, I receive:a = torch.randn(3, 128, 128)
a_T = torchvision.transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0)(a) # works
a_t = torchvision.transforms.ColorJitter(brigh... | ptrblck | The code works using torchvision==0.8.0.dev20201006 and it seems the functionality was added inthis PR.
You could update to the latest nightly binary, build from source, or wait for the next stable release. |
kenenbek | I am building a sequnce-to-sequence model.For MWE, I have one learning example: [0, 1, 2, 3, 4] --> [0, 1, 2, 3, 4]How can I create a dataloader from it? I triedx = torch.arange(5)
y = torch.arange(5)
test_dataloader = torch.utils.data.dataloader.DataLoader((x, y))But it gives me:for data in test_dataloader:
print... | ptrblck | Try to use a TensorDataset and pass the data in the shape [batch_size, features] to it.
Once this dataset is created pass it to the DataLoader. |
Emil_Hovad | When I follow the tutorial “https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html” and I make the number of predictions it is only 100? is that due to the setting in pytorch/torchvision, it is not the model?img, _ =dataset_test[1]# dataset[0]put the model in evaluation modemodel.eval()with torch.no_grad(... | ptrblck | That might be the case and you could try to change these threshold withthese arguments. |
Ahebwaed | Thank you for the observation@ptrblck, its true the the first conv. is raising the error, how should i go about it? | ptrblck | Thanks for the code.
I’m not sure, if you would need this workaround and why you are replacing the self.model.conv1 with a conv layer accepting a single input channel.
The default resnet18 model already accepts RGB images, so you could just remove the self.model.conv1 line of code as well as self.… |
peepeepoopoo | I’m currently trying to load datasets that have separate sub-folders( as video sequences), and the number of images under each sub-folder varies. I assume that _len_ is for the length of the entire datasets. But since the images under training are separated in sequences under different folders, would this effect how th... | ptrblck | It depends how you are loading each sample.
The __len__ method returns the length of the complete Dataset and thus also defines the used indices (passed into __getitem__).
E.g. if you are loading single images via the passed index in __getitem__, the length should define the total number of images… |
Julien_Guegan | Hello, I am implementing a segmentation task with masks and images in input and one class in output. I am trying to use the binary cross entropy from pytorch but I have this error :> RuntimeError: “binary_cross_entropy” not implemented for 'Long’Indeed, I have formatted my mask as a long type, otherwise this message ap... | ptrblck | You can
use a single output unit without any activation function at the end and lass this logit to nn.BCEWithLogitsLoss. For this the targets should have the same shape as the model output and be FloatTensors. To get the predicted label you can apply torch.sigmoid and use a threshold via preds = o… |
Aptha_Gowda | My single fold model performed well(unseen test data) with a train validation slit of 80%,20% respectively.Here are more details about the single fold model.Seed = 42, batch_size = 16, Epoch = 15, StepLR (step_size=5,factor=0.1), TTA = 6,Image_shape( 320x320), LR = 0.0005.Now I want to implement StratifiedKfold with n... | ptrblck | I think averaging uncorrelated outputs could yield a performance gain. Generally you could take the average of a lot of weak models, if their performance is at least better than a random guess.
For 2. and 3. I would refer to@rasbt’s post oncross validation. |
Sosom_Park | I just wonder when the next CUDA version is availableappreciate your replyThanks | ptrblck | I would assume “soon”, as the 1.7 branch is already created:https://github.com/pytorch/pytorch/tree/1.7However, I don’t know the exact schedule. |
blackberry | I have some models trained in PyTorch 1.5 and saved bytorch.save(filename, model), instead oftorch.save(filename, model.state_dict()).Now, I am not able to load them in PyTorch 1.6.I gettorch.nn.modules.module.ModuleAttributeError: 'BatchNorm2d' object has no attribute '_non_persistent_buffers_set'What is the correct w... | ptrblck | The recommended way of storing the state_dict should be working fine or are you seeing any issues with it? As explained in theSerialization semantics, storing and loading the model directly could be breaking in various ways due to the way Python pickles the model. |
uertenli | Hello,I am currently working on HoughNet (https://arxiv.org/abs/2007.02355) paper which has its code publicly available. I tried to changeConvTranspose2din (https://github.com/nerminsamet/houghnet/blob/master/src/lib/models/networks/houghnet_large_hourglass.py#L280) with Conv2d. However, I get this error message:Runtim... | ptrblck | As shown in my minimal code snippet, the weight shape is wrong in your code, so you would have to permute it to the expected shape, i.e. swap dim0 with dim1. |
hughperkins | Does AMP work in TorchScript? | ptrblck | If you could trace the model, all operations should be recorded (thus also the transformations) and amp should work. This would also mean that you don’t need to run the traced model in an autocast region anymore.
However, scripted models are currently still WIP. |
hughperkins | AMP: How to check if inside autoscaling region? | ptrblck | You can if autocasting is enabled via torch.is_autocast_enabled(). |
vishalthengane | I have an MLP model and I want to save the gradient after each iteration and average it at the last. How I can do that?model:class MyModel(torch.nn.Module):
def __init__(self, layers_size, input_size=784, num_classes=10):
super(MyModel, self).__init__()
# create input layer
self.layers = ... | ptrblck | Each backward() call will accumulate the gradients in the .grad attribute of the parameters.
You could thus accumulate the gradients in your data loop and calculate the average afterwards by iterating all parameters and dividing the .grads by the number of steps.
Alternatively you could also use t… |
M_Tu | For example,model = nn.Sequential()
model.add_module('conv0', conv0)
model.add_module('norm0', norm0)Is there a way to get the names of these added modules? Thanks | ptrblck | You could print all names and sub-modules using:
for name, module in model.named_modules():
print(name)
If you want to directly access these modules, you can just use:
print(model.conv0) |
111229 | There is a variable ‘tmp’ (3 dimension).type(tmp) -> <class 'list'>
type(tmp[0]) -> <class 'torch.Tensor'>
type(tmp[0][0]) -> <class 'torch.Tensor'>I want to convert ‘tmp’ into torch.Tensor type.But, when I run this code below, an error occurs.torch.Tensor(tmp)
>> ValueError: only one element tensors can be converted t... | ptrblck | Nested tensors(WIP) might be usable.
Since this feature is not implemented yet, you might need to keep the list.
Depending on your use case, you might be able to create tensors using padding or slicing. |
5had3z | I’m trying to add random scaling augmentation to my training loop. I tried to do this by adding a member function that selects a random scaling factor on each iteration so that all the images in the batch are changed at the same scale, as to keep the dimensions all the same for that batch. However when using the debugg... | ptrblck | If you want to apply a new scaling for the complete batch you could either resample the data inside the training loop or use an approach, where the sampler might pass the index as well as the new scaling to the Dataset.
I haven’t tested this approach so let me know, if you get stuck. |
univ | I’m trying to build a loss function which will calculate the mean squared error of 2 tenors of the same size. In other words I need a function that calcualtes the difference of every 2 cells (with the same row and column) cell on matrix A and matrix B, squares it and calculate the mean of the differences.As far as I un... | ptrblck | You would have to create an object for the loss function and use it afterwards:
criterion = nn.MSELoss()
loss = criterion(stack_3[0, :], stack_7[0, :]) |
SriAnu | I’m using CNNs to predict the gender of people. The shape before passing my data through my CNN is ([23705, 48, 48]).class neural_network(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 64, 3),
nn.ReLU(),
nn.BatchNorm2d... | ptrblck | It seems that train_y is smaller in one iteration for some reason.
Could you check the shape of X and y and make sure they contain the same number of samples?
What’s your use case btw.? |
Harshit_Pandey | I have created a custom layer in which i have initialized a glorot uniform weight given input_shape = (1,3,299,299).class CustomLayer(torch.nn.Module):
def __init__(self, input_shape):
super(CustomLayer,self).__init__()
zeros = torch.zeros(input_shape)
self.weights = torch.nn.Parameter(zeros... | ptrblck | Your custom layer contains the weigth parameter printed by this code snippet:
class CustomLayer(torch.nn.Module):
def __init__(self, input_shape):
super(CustomLayer,self).__init__()
zeros = torch.zeros(input_shape)
self.weights = torch.nn.Parameter(zeros)
torch.n… |
yqian | Hi, I wonder if loss will backward successfully when using feature maps obtained by forward hook. | ptrblck | Yes, that should be possible as long as you don’t detach the output activations. |
Elidor | Hello everybody,I’m training a fairly complex model on Colab. After adding a positional embedding to the various embedding (word, character, tag, etc.), I received the following error:/pytorch/aten/src/THC/THCTensorIndex.cu:361: void indexSelectLargeIndex(TensorInfo<T, IndexType>, TensorInfo<T, IndexType>, TensorInfo<l... | ptrblck | If the indices are defined by the vocabulary, I don’t think it’s a good idea to cut them somehow as this part of the vocabulary wouldn’t be used during training.
Instead of changing the input I would recommend to adapt the num_embeddings in the emnedding layer to match the number of words (indices)… |
anotherone_one | Hello everyone! I wanted to clarify a doubt I have regarding the vgg16 network. I am currently using the pre-trained vgg16 network for a classification problem with 2 labels. I already have the best weights for tthis problem, using as a criterion the nn.CrossEntropyLoss and I can get a prediction by doing:outputs = vgg... | ptrblck | To get the probabilities, you should probably use probs = F.softmax(outputs, dim=1), since you are using nn.CrossEntropyLoss as the criterion which means your output should have the shape [batch_size, 2] (used in a multi-class classification). |
satbek | Hi there,It is possible tologactivation values of neurons in a model, or evenchangethem in theforwardmethod.Is it possible to(i) logand(ii) changeactivation values of neurons without modifying the underlying code of a model (without modifying theforwardmethod)?Thanks! | ptrblck | Yes, you can use forward hooks as describedhereto inspect and manipulate the output activations. |
marcelwa | Hi!I am moving tensors between the CPU and GPU memory with.to(device)and.cpu().I found out that all tensor that get in or out of thenn.Linearlayer are locked in GPU memory.That is why I created my ownLinearlayer and I found out that ifrequire_grad=FalseI get the expected use of memory in the GPU.Ifrequire_grad=True, t... | ptrblck | PyTorch doesn’t free these tensors because they are needed for the backward pass to work properly, since they are part of the computation graph.
In your example you are creating new tensors x, w, and l, which doesn’t delete the computation graph. I.e. l.mean().backward() would still work.
You won… |
nzinc | I have data set in folderdata.tar.gz. That archive contains two folder with female face images and male face images. Uncompressed size of this data set is 150 gb (archive size 1.9 gb). I work on Google Colab with GDrive, so i couldn’t allocate this huge data set. There is a binary classification task for training. The ... | ptrblck | Based on your description you could most likely usetorchvision.datasets.ImageFolderto lazily load the data. |
alanzhai219 | There are some images inhttps://hub.docker.com/u/pytorch. Is PyTorch installed in such image? If so, how to use it. If not, what is the purpose of such images.[It ishttps://hub.docker.com/u/pytorchofficial docker instead of official nvidia-docker.]BTW: what is pytorch/dockerfile designed for?That confuses me a lot. | ptrblck | Sorry for not being clear. Some of these containers are used as the base e.g. to build the binaries etc.
The framework is installed in pytorch/pytorch using the latest stable version (1.6.0). |
skerlet_flandorle | I want to delete some of the elements of the tensor arrayIs there a function that can bechanged from[1,2,3,4,5,6,7,8,9]to[6,7,8,9]? | ptrblck | I think you could just slice the tensor via tensor[5:]. |
Y_Y | Hi all,If I want to use a function2 norm of matrixthat’s already finished developing. But it’s not in a stable version. So I followedhttps://pytorch.org/and installed the preview nightly version. Under this situation, I still can’t import and use this functiontorch.linalg.norm. The error isAttributeError: module 'torch... | ptrblck | No, you should see 1.7.0.devYYYYMMDD.
E.g. torch.linalg.norm is available in my local nightly installation using 1.7.0.dev20200830, which is approx. a month old by now.
I guess your nightly installation wasn’t working properly, so you might to reinstall it. |
Harshit_Pandey | On running the code snippet below I get the following error: RuntimeError: Expected 4-dimensional input for 4-dimensional weight [192, 768, 1, 1], but got 2-dimensional input of size [2, 1000] insteadimport torch
import torchvision.models as models
from torchsummary import summary
inception = models.inception_v3(pretra... | ptrblck | Wrapping all modules in an nn.Sequential container might work for a simple model definition.
In your case the inception model is failing, since inception.children() will return the child modules in the order they were initialized. model[15] would thus contain the InceptionAux module (which is used … |
nuhpiskin | My model pre process is 500 fps and model fps is 1000 but post process model is stack 30 fps one line. Total fps is down. But this code line is very fast normaly. If ı change this line with under. Then this code is tack same location. I didint find anything like that. I treid every possibilities but same location is sl... | ptrblck | If you are using the GPU you would have to synchronize the code before starting and stopping the timer.
Otherwise the time will be accumulated in a blocking operation.
Could this be the case for the different timings you are seeing? |
meeraone | How can I do the same thing with pytorch?local right = nn.Sequential()
right:add(nn.Narrow(2, 1, output_size)) | ptrblck | You could write a custom module and pass add it to nn.Sequential.
Something like this might work:
class Narrow(nn.Module):
def __init__(self, dim, start, length):
super(Narrow, self).__init__()
self.dim = dim
self.start = start
self.length = length
def … |
NicoAdamo | Hi there, I’m new to Pytorch and struggling to understand GPU memory management. I have a model which, during training, takes up slightly more memory than my GPU can handle - so I’ve gone ahead and trained it on an AWS server with more virtual memory.I’m wondering whether I will need the same amount of memory to evalua... | ptrblck | Your assumption is correct. During evaluation you don’t need to calculate the gradients, which would take memory, and also don’t need to store intermediate activations, which would be needed to calculate the gradients.
To lower the memory usage and not store these intermediates, you should wrap you… |
Ajinkya_Ambatwar | Hi it’s a small problem I am facing with respect to model saving and loading.I am training a simple classification model in Google Colab. As per the instructions fromhttps://pytorch.org/tutorials/recipes/recipes/saving_and_loading_models_for_inference.htmlI am saving the model astorch.save(net.cpu().state_dict(),"/fold... | ptrblck | Are you using different PyTorch versions in Colab and on your local machine?
If so, I guess your local installation might be older so could you update it? |
fsh | Hi,I am running the code below on multiple GPU mode. When I take thex,yvariables either to cuda() or not, I can not get the whole network running on the same device. Depending on the device, I get this error.RuntimeError: expected device cuda:1 but got device cuda:0
RuntimeError: expected device cuda:0 but got device ... | ptrblck | Are you using any cuda() or to() calls inside your model (__init__ or forward)?
If so, could you remove them as they might create the device mismatch.
nn.DataParallel will automatically create model replicas for you and you don’t need to push internal model parameters to a specific device manually… |
Bahaa_Kattan | I’m trying to solve Cat VS Dog classification problem using pytorch. So I started by creating a DataSet class using the following code:import torchvision.transforms as transforms
import torch
from torch.utils.data import Dataset, DataLoader
import cv2, os
torch.manual_seed(0)
class dogVScat(Dataset):
def __init... | ptrblck | The indentation of __getitem__ and __len__ is wrong, as both methods are defined inside the __init__ function.
Move them one level to the left and it should work. |
satbek | Hi there,Say, I download a trained model (g.e.http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/mnist-b07bb66b.pth, it’ll download if you click).It contains the state_dict of the model. The question is, how do I run the model without having access to its code definition as in herehttps://github.com/aaron-xichen/pytor... | ptrblck | You won’t be able to run the model as the state_dict only contains its parameters and buffers.
In PyTorch “eager” mode the model definition is the source code of it, which thus would need to be accessible.
You can script the model and store the scripted model, which would be executable without the… |
Eiphodos | I have trained several models with amp in FP16 separately and saved all state dicts for both models and amp.Now as a continuation of that training, I would like to load those models into an ensemble, freeze all gradients and train a new model with a few final layers that learns based on the output from those models and... | ptrblck | This wouldn’t be necessary, if you are not planning to finetune the pretrained models.
We recommend to use the native amp implementation viatorch.cuda.ampinstead of apex/amp. Since there is no amp.initialize method, it should just work, but let us know if you encounter any issues.
The amp sta… |
Tahsin_Mostafiz | I’m trying to implement the Recurrent Attention U-net model fromhere. I’ve modified the code a little bit for my purpose. Here is my implementation:class R2AttU_Net(nn.Module):
def __init__(self,img_ch=3,output_ch=2,t=2):
super(R2AttU_Net,self).__init__()
## Just basic stuff from the original code
... | ptrblck | Yes, this operation pred>threshold won’t get any gradients as you can see in the missing .grad_fn in the output, as this operation is not differentiable. |
Mona_Jalal | I am trying to run this code:https://github.com/benjiebob/SMALViewerHowever I get the following error:(base) mona@mona:~/research/3danimals/SMALViewer$ python smal_viewer.py
dict_keys(['f', 'J_regressor', 'kintree_table', 'weights', 'posedirs', 'v_template', 'shapedirs'])
torch.Size([4, 3889])
Tensor J_regressor shap... | ptrblck | The latest stable PyTorch version is 1.6.0 and you can find the install commands for the conda binaries or pip wheelshere. I would recommend to use the latest CUDA version (10.2), but make sure your driver supports it (you are currently using 10.1 so you might use an older driver).
You can see the… |
picklerick | I’m having a hard time visualizing how nn.functional.pad works. The docs about pad say the following:For example, to pad only the last dimension of the input tensor, thenpadhas the form (padding_left, padding_right); to pad the last 2 dimensions of the input tensor, then use (padding_left, padding_right, padding_top, p... | ptrblck | The “left”, “right”, “top”, and “bottom” description might be understood if you think about an image tensor.
For multi-dimensional tensors you can think about the “front” or “end” of the dimension.
Each dimension will use two values, one for the “front” the other one for the “end” of this dimensio… |
SAI_VARSHITTHA | x = torch.randn(1)
print(x)
print(x.item())The output of the above code istensor([0.3369])
0.3368943929672241 # this is python numberWhen doing operations on x , what values will be used for the values iniside x? the rounted value( 0.3369) will be used or the number (0.3368943929672241 ) is used? | ptrblck | The complete float32 number will be used. The print(x) uses the default print options, which truncate the output.
You can increase the print precision via: torch.set_printoptions(precision=10) (or to any other value). |
Giuseppe | Hy guys i have an error in runtime.The code is in below:import torch
import torch.nn as nn
from torchvision.models import resnet50
from torchvision.models import resnet18
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.model = resnet50(pretrained = True)
... | ptrblck | Changing the in_channels attribute after creating the module won’t reinitialize the weights and would need to assign a new nn.Conv2d object to self.model.conv1, which accepts 9 input channels. |
bing | Hi,I am trying to use transfer learning for image classification.Can anyone suggest best practices,I have seen multiple tutorial where few people adds single fc layers after removing the initial fc layerAlso, it seems like a rabbit hole where we can freeze-unfreeze the different number of sub-modules. It seems not very... | ptrblck | I don’t think there is a simple answer to this question.
I think that’s unfortunately still often the case and you will read in a lot of papers that the training hyperparameters were “tuned” or “heuristically determined”.
You could have a look at e.g.FastAIwhich explains the best practices for … |
dougsouza | I started playing around with new Amp interface. The thing is: I am training GANs and my models use spectral norm.I would like to know how things work with mixed precision when using spectral norm. Are my spectraly normalized weights eligible for fp16 precision? Do I need to do something extra to get things working (su... | ptrblck | No, that shouldn’t be the case as the compute and accumulate dtype would still be performed in FP32 even if FP16 inputs are passed.
If depends on the range of your values and if they are representable. Theoretically it would be possible, e.g. via:
x = torch.tensor(2**(-149)).cuda()
print(x)
> tens… |
ptrblck | You cannot callnn.ModuleListdirectly, as it’s used as a container to store other modules.If you want to callencoderwith an input, you could either try to wrap all modules intonn.Sequentialor apply the loop over all modules manually. | ptrblck | Thanks for the notebook.
The DownConv layer returns a tuple inthis line of code, which doesn’t work in an nn.Sequential container and standard layers.
If you want to accept the tuple in the next layer, you could e.g. write a custom layer, which unwraps the tuple internally. |
chandra_sutrisno | Hi all,I am new on this thing but would like to get an understanding of the problem I have.I convert RNN model, like below:class RNN(nn.Module):definit(self, input_dim, embedding_dim, hidden_dim, output_dim):super().init()self.embedding = nn.Embedding(input_dim, embedding_dim)
self.rnn = nn.RNN(embedding_dim, hidde... | ptrblck | I don’t know what kind of input shape you are using, but assume you are passing in a 3-dimensional tensor?
If that’s the case, I would recommend to check all shapes in both models and make sure the layers work as intended.
E.g.nn.RNNexpects an input in the shape [seq_len, batch_size, features] b… |
MichaelMMeskhi | Hello,I am looking into how to properly setup a regression problem. My concern is with the targets. For example, for each example in my input, I have 3x5 numerical outputs.Example 1: output_1 - 5, 6, 7, 53, 0.5output_2 - 5, 0.3, 7, 53, 0.5output_3 - 5, 6.2, 7, 53, 0.5And so on. Basically it is a multi-target regression... | ptrblck | Thanks for the explanation. In that case I think you could treat this output as 15 independent predictions.
I assume you would like to predict the 5 attributes from all 3 websites, not the mean/median etc. |
Ethan_P | Hey I’m kinda a newbie…How can I calculate closest tensor in list to another tensor?Example:Say I have:[tensor([1,1,1]),tensor([5,5,5]),tensor([10,10,10])]and:tensor([2,2,2])If would want:tensor([1,1,1])How can I achieve this? Thank you | ptrblck | You could calculate the distance between the tensors using torch.norm and use argmin to get the index corresponding to the smallest distance:
a = torch.stack([torch.tensor([1,1,1]), torch.tensor([5,5,5]), torch.tensor([10,10,10])]).float()
b = torch.tensor([2,2,2]).float()
min_idx = torch.norm(a - … |
Anubhav1107 | I want to know is there any function forK.ctc_batch_cost()for Pytorch.and also forctc_loss = Lambda(ctc_lambda_func, output_shape=(1,), name=‘ctc’)([y_pred, labels, input_length, label_length])In this code, ctc_lambda_func is a function I earlier defined. And y_pred,… are parameteres I have defined. I want the equival... | ptrblck | I guess nn.CTCLoss might be the equivalent to ctc_batch_loss.
What does the Lambda function do? It seems you are passing a ctc_lambda_func to it and execute it with input data?
Note that you don’t have to define the computation graph beforehand in PyTorch and can just execute the code similar to n… |
freezek | So, what’s the corresponding code in C++? | ptrblck | at::globalContext().setBenchmarkCuDNN(flag) should work in C++.
However, benchmark is off by default so I guess that’s not the root cause of the non-deterministic results.
You could try to use at::globalContext().deterministicCuDNN() or at::globalContext().setDeterministic() in the nightly binarie… |
Ali_Shahbaaz_Khan | total_preds = []
for model in models :
dataloader = DataLoader(test_data,batch_size=1,shuffle=False,num_workers=2)
preds = []
temp = []
i = 0
for batch in dataloader :
inputs = batch['input_features'].float()
with torch.no_grad() :
p = model(inputs)
preds.appe... | ptrblck | You could calculate the mean in the “kfold” dimension as given in this code snippet:
total_preds = []
for _ in range(4): # kfold loop
preds = []
for _ in range(730): # data loop
p = torch.randn(3)
preds.append(p)
preds = torch.stack(preds)
total_preds.append(preds)
… |
skerlet_flandorle | I would like to change an array of size (1,4,4,4,4) to (1,16,16).error contentsview size is not compatible with input tensor’s size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape (…) instead.Until now, this error only appeared when the size was specified incorrectly in the viewI... | ptrblck | The view operation just changes the tensor metadata without triggering a copy.
After the permute call this won’t be possible anymore as explained in the error message and you would either have to use reshape (which copies the data and performs the view op) or call .contiguous() before the view oper… |
Ykk_L | The target tensor is X (B, H, W, C). The index tensor is I (B, N, 2). And the source tensor is S (B, N, C).So how can I implement X[i, I[i,j,0], I[i,j,1]] = S[i, j] efficiently and parallelly?I tried to useforloop to assign X. But it took too much time inloss.backward(). | ptrblck | This code might work:
B, H, W, C = 2, 3, 3, 4
N = 5
x = torch.randn(B, H, W, C)
I = torch.randint(0, H, (B, N, 2))
S = torch.ones(B, N, C)
x[torch.arange(B).unsqueeze(1),
I[torch.arange(B), :, 0],
I[torch.arange(B), :, 1]] = S
Could you please double check it using your manual approach with t… |
antran96 | My model size is not so big (2M parameters). However, it throws the following error after several epochs (sometimes it could train for >20 epochs and throw this error).RuntimeError: CUDA out of memory. Tried to allocate 2.00 MiB (GPU 0; 31.75 GiB total capacity; 16.29 GiB already allocated; 1.69 MiB free; 14.46 GiB cac... | ptrblck | Your script might be already hitting OOM issues and would call empty_cache internally.
You can check it viatorch.cuda.memory_stats().
If you see that OOMs were detected, lower the batch size as suggested. |
soulslicer | Have the following model as follows:import torch.nn as nn
class DefaultModel(nn.Module):
def __init__(self, guess, K):
super(DefaultModel, self).__init__()
#guess = [-0.7541, -0.044, 0.0916, 1.5914, -0.0017, 1.4991]
self.T = torch.tensor(guess).unsqueeze(0)
self.T.requires_grad =... | ptrblck | You would have to register self.T as an nn.Parameter:
self.T = nn.Parameter(torch.tensor(guess).unsqueeze(0))
which makes sure it’s returned in model.parameters(). |
nsacco | We are facing a very strange issue. We tested the exact same model into two different “execution” settings. In the first case, given a certain amount of epochs, we train using mini-batches for one epoch, and thereafter we test on the validation set following the same criteria. Then, we go for the next epoch. Clearly, b... | ptrblck | Did you try to use different seeds without the validation loop and check how the training behaves?
I guess your training might not be very stable so that calling into the pseudo-random number generator during validation would change the next random values and your model would diverge during the tra… |
Enes_Uguroglu | You can find training section of my code below:device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)Note: I am receiving True when i check torch.cuda.is_availableAfter creating CNN model i wrote:model = model.to(device)Training Section:import timestart_time = time.time()epochs = 3#Limitson numbers of ba... | ptrblck | You should get an error, if you try to push tensors or the model to the GPU and no GPU is available.
Also, once the data is transferred, you can check the device via print(X_test.device) and make sure it’s cuda:id.
Your GPU utilization might be that low as your model is really small, such that you… |
over9k | Hi,I see here (https://pytorch.org/docs/stable/torchvision/models.html#classification) that the imagenet pretrained models expect image height and width dimensions to be “at least 224”. What does that mean? Can we pass in images smaller or larger?Were the models trained on Imagenet images that were resized to 224x224 f... | ptrblck | The pretrained models are most likely sticking to the literature for the corresponding model, which often used input images of the shape 224 x 224 (often randomly cropped to this shape).
Since these torchvision models use adaptive pooling layers the strict size restriction was relaxed and you would… |
shamoons | I have a pretrained model:ModuleList(
(0): Sequential(
(0): Conv1d(1, 512, kernel_size=(10,), stride=(5,), bias=False)
(1): Dropout(p=0.0, inplace=False)
(2): Fp32GroupNorm(1, 512, eps=1e-05, affine=True)
(3): ReLU()
)
(1): Sequential(
(0): Conv1d(512, 512, kern... | ptrblck | If the input and output channels of the nn.Conv1d layers are reversed to the input and output channels of the transposed equivalent, you could try to reuse the weights.
Usually you would create new layers and I don’t know how well this weight sharing approach would work, so let us know what you fin… |
biggusbackpropagatus | I am trying to rebuild a Keras architecture in pytorch, which looks like thisrnn_layer1 = GRU(25) (emb_seq_title_description)
# [...]
main_l = Dropout(0.1)(Dense(512,activation='relu') (main_l))
main_l = Dropout(0.1)(Dense(64,activation='relu') (main_l))
#output
output = Dense(1,activation="sig... | ptrblck | Since nn.ReLU is a class, you have to instantiate it first. This can be done in the __init__ method or if you would like in the forward as:
hidden = nn.ReLU()(self.i2h(combined))
However, I would create an instance in __init__ and just call it in the forward method.
Alternatively, you don’t have … |
omar_bouhamed | Hi, am new to pytorch and am trying to run my model on GPU, the Jupyter notebook successfully detect my GPUif torch.cuda.is_available():
self.device = torch.device("cuda:0") # you can continue going on here, like cuda:1 cuda:2....etc.
print("Running on the GPU")
torch.cuda.set_devi... | ptrblck | The Windows task manager is often nor properly reporting the GPU utilization so you could either select the “compute” output in a drop down menu (I’m no Windows expert as you might notice) or use nvidia-smi. |
ImportYang_Howard | I installed CUDA 10.1.105 and reinstall NVIDIA driver 430.64 , cuDnn 7.6.5 even Anaconda because of no availablepython -m torch.utils.collect_env
Collecting environment information...
PyTorch version: 1.3.1
Is debug build: No
CUDA used to build PyTorch: Could not collect
OS: Ubuntu 18.04.4 LTS
GCC version: (Ubuntu 7.5... | ptrblck | You don’t need local CUDA and cudnn installations, if you are using the conda binary.
Only the NVIDIA driver will be used.
Based on the output you are seeing, I assume you’ve installed the CPU binary.
Could you reinstall PyTorch with the desired CUDA version using the install command fromherean… |
gakadam | I am using pre-trained AlexNet network to validate some prior work.The code is as follows:import os
import torch
import torchvision
import torchvision.datasets as datasets
import torchvision.models as models
import torchvision.transforms as transforms
model = torch.hub.load('pytorch/vision:v0.6.0', 'alexnet', pretra... | ptrblck | Instead of the fop loop you could directly use torch.argmax(output, dim=1), but your code should also work.
I guess the correspondence between the data and labels might be broken. Could you check some random examples from your ground truth file and the input image manually? |
Yupjun | Let’s say I have two GPUs with 4GB VRAM and I have a 6GB model.Can I run this model by utilizing the two GPUs? | ptrblck | You could use model sharding, i.e. executing different parts of the model of different devices, as given inthis example. |
qiminchen | I have two tensorsa = torch.randn(2, 3, 10, 25, 25) # B x C x *andb = a.permute(0, 2, 1, 3, 4) # 2 x 10 x 3 x 25 x 25, I want to do matrix multiplication onaandbto get the output with size of2 x 3 x 3 x 25 x 25,a = torch.randn(2, 3, 10, 25, 25)
b = a.permute(0, 2, 1, 3, 4)
c = torch.matmul(a, b)but I ran into this er... | ptrblck | The matrix multiplication doesn’t “check” for the memory format, i.e. if the tensors are in channels-first or channels-last, but just uses both tensors in the provided shapes.
It’s on the user to make sure the result is expected, so I would recommend to create tensors with known values and compare… |
Pranavan_Theivendira | Hi,I want to convert a tensor of images to PIL images.import torch
import torchvision.transforms as transforms
tran1 = transforms.ToPILImage()
x = torch.randn(64, 3, 32, 32) # 64 images here
pil_image_single = tran1(x[0]) # this works fine
pil_image_batch = tran1(x) # this does not workCan somebody tell me if there is... | ptrblck | I don’t think there is a way to achieve this without a loop, since the underlying PIL.Image.fromarray operation expects a single numpy array, if I’m not mistaken. |
Ahmed_Abdelaziz | Hi, what would you do if you have PyTorch and TensorFlow models that are supposed to be replicas of each other and you wanted to test that they are exact replicas in terms of layer, weight initialization, loss functions, etc? I converted a TF model into PyTorch but PyTorch accuracy is far off from that of TensorFlow. I... | ptrblck | I wouldn’t try to use seeds in order to initialize both models etc., as the implementation of the random number generator might be different in the worst case and you would waste a lot of time.
If you want to compare both models, I would start with the good performing model (i.e. the TF model in yo… |
Rafi | I am training distilBert model for text classification. I am using the amp package to train the mixed precision version. here is the code to train the model# define the model
model = BertMulticlassifier(....)
# Define optimizer and scheduler
optimizer = Config.OPTIMIZER(model.parameters(), lr=Config.LR, ... | ptrblck | The native amp implementation is corresponding to opt_level="O1" in apex.amp, as the usability is the most user-friendly and it should support all use cases. We are experimenting with other utilities to lower the memory usage, but for now we strongly recommend to stick to the native implementation f… |
pyscorcher | I tried implementing a custom dataset, which works fine, but as soon as I specify to use multiple workers for accelerating the loading, I get a huge chained error message. The example here doesn’t make any practical sense, it is just the minimal example to reproduce the error. Curiously, the error happens on windows, b... | ptrblck | Could you add the if-clause protection as described in theWindows FAQ? |
bing | Hi Guys,I am trying to generate data in parallel usingthistutorial. I am using it for image classification problem so I have image data in jpeg format.I have a very basic doubt, in the below code , the data is being accessed usingX = torch.load('data/' + ID + '.pt'), is this some sort of pickling the data or is the gen... | ptrblck | It depends a bit on your use case.
You could save some data loading time, if you preload the data (e.g. images), process it all, and store it as binary data. However, since e.g. JPEG images are compressed, while binary data is usually not, you could potentially use more space on your device.
Also… |
jmaronas | Hello.I am facing an unexpected behaviour in my dataloading scheme. I have two dataloaders, atrain_dland atest_dl. Thetrain_dlprovides batches of data with the argumentshuffle=Trueand thetest_dlprovide batches with the argumentshuffle=False.I evaluate my test metrics each N epochs, i.e each N epochs I loop overtest_dld... | ptrblck | Thanks for the code.
I can reproduce this behavior using two simple DataLoaders:
X_train = torch.arange(10).float().view(-1, 1)
y_train = torch.arange(10).float().view(-1, 1) + 0.1
train_dataset = dataset_class(X_train, y_train)
train_loader = DataLoader(train_dataset, batch_size=2, shuffle=True)
… |
Jona | Hi,Do you know how to extract the raw data or Dataset (in the original order when the Dataloader was created) from a shuffled Dataloader?Best regards | ptrblck | Your proposed approach using dl.dataset should work:
class MyDataset(Dataset):
def __init__(self):
self.data = torch.arange(10)
def __getitem__(self, index):
x = self.data[index]
return x
def __len__(self):
return len(self.data)
dataset = M… |
ptrch_c_m | I am working on small texts doing Sequence Labelling. Specifically, I use a BERT model from the huggingface library (BertModel in particular), and I tokenize every text with the library’s tokenizer to feed the model. Since the texts are small, I have specified that the sequence length that the tokenizer produces is 256... | ptrblck | I think you could try to use the raw loss output (via reduction='none'), set the unwanted loss entries to zero, reduce the loss, and calculate the gradients via loss.backward(). Unsure, if there is a better way to mask the loss. |
Jona | HiSuppose you have a NN model which predicts a probability (Sigmoidin the last layer andBCELossas a loss function), and the target column has the valuesTrueorFalse, a you use roc_auc as a accuracy metric.How can you perform an Error Analysis? I mean … take a look at the missclassified samplesHow can I know if a sample ... | ptrblck | You could use the ROC to pick a threshold value and create the predictions using this threshold.
Once you have the predictions you could check all misclassified samples, compute a confusion matrix etc. for further investigation. |
maamli | I have converted a tensorflow code for timeseries analysis to pytorch and performance difference is very high, in fact pytorch layers cannot account for seasonality at all. It feels like I must be missing something important.Please help find where the pytorch code is lacking that the learning is not up to the par. I no... | ptrblck | You should get a warning, which points to a shape mismatch:
UserWarning: Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
return F.mse_loss(input… |
Rose12321 | HiI have made a simple feed-forward network, and I’m having problems with overfitting.I am trying to implement dropout, however, it doesn’t do quite what I would expect, so I find it likely that maybe I’m using it wrongI have tried 3, 4 and 5 layers, learningsrates from 0.00001 to 0.001. I have tried to place dropout a... | ptrblck | Yes, the code looks generally alright.
If your model isn’t training properly, I would recommend to try to overfit a small data snippet (e.g. just 10 samples) and make sure your model is able to perfectly fit this set.
PS: you can post code snippets by wrapping them into three backticks ```, which … |
luan1412167 | Hi you guys, pardon me I’m not good at training model. I’m training the model with architecture as followingout = self.conv2_dw(out)
out = self.conv_23(out)
out = self.conv_3(out)
out = self.conv_34(out)
out = self.conv_4(out)
out = self.conv_45(out)
out = self.conv_5(out... | ptrblck | Thanks for the clarification.
If I understand the question correctly, you are wondering why the output values of the last linear take values such as [4.2354, -4.1672]?
The last linear layer outputs logits, which are raw prediction values and are not bounded to a specific range.
The lower the valu… |
Henry_Chibueze | I’m currently working on a regression model with input data of range(1, 26) and target data of range(1, 42) and I discovered that when I normalize the data to be within range(0, 1) and set learning rate to 0.001 the loss reduces by a huge factor after one epoch it’s so unbelievable than when I don’t normalize the trai... | ptrblck | I’m not sure, if I understand this sentence correctly.
Are you comparing these use cases:
# case0
output = model(unnormalized_input)
loss0 = criterion(output, unnormalized_target)
# case1
output = model(normalized_input)
loss1 = criterion(output, normalized_target)
If so, then I would expect th… |
ghfkddorl | I created a PointNet module with libtorch. It has a point cloud input as {min batch size, 3, pointCount(about 500000)} shape. But, when I training the model, It consumes so many memory.As I know, on training, ‘conv, linear, batchNormalize…’ hold it’s input tensor for backward. If input tensor shape is {4, 3, 500000} an... | ptrblck | It is true that some layers need to store intermediate tensors to be able to calculate the gradients during the backward pass.
If you are running out of memory you could either decrease the batch size (or number of points, if possible). I don’t know, if e.g. torch.utils.checkpoint can be used in li… |
granth_jain | I am using pytorch to make an A3C with 4 processes as in below code.But to my surprise while training the A3C action values goes to nan for all actions. Initially it was not the case that action values were gone to nan.But after an overnight training it goes to nan. Can someone please help to let me know what issue is ... | ptrblck | Your sample function might return invalid outputs.
torch.rand samples from [0, 1) and if you sample a zero in it, torch.log would return -Inf.
Try to add a small eps value to this operation or check other operations, which could potentially output an invalid value. |
linlin | I want to build a multi task learning model on two related datasets with different inputs and targets. The two tasks are sharing lower-level layers but with different header layers, a minimal example:class MultiMLP(nn.Module):
"""
A simple dense network for MTL on hard parameter sharing.
"""
def __init_... | ptrblck | The parameters might still get updated even with a zero gradient, if you are using an optimizer with momentum or other running estimates.
Here is a small code example:
model = nn.Linear(1, 1, bias=False)
optimizer = torch.optim.SGD(model.parameters(), lr=1., momentum=0.) # same results for w1 and… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.