user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
ian_malcolm | Hi, I try to learn the actual function by reading the code. For example, I want to understand what is happening in a linear layer (in forward and backward pass). I track fromheretohereand get lost.My question is: Is it possible for me to find a pythonic (or jit or C) implementation, of the actual operation, e.g., x*w+b... | ptrblck | This postshows where the underling methods for a linear layer are defined. Convolutions dispatch to different implementations fromhere(i.e. the CPU kernel, native CUDA kernel, cuDNN, etc.). |
Tom_F | Is there an easy way to access the last layer in a torchvision model, without coding a special version for each type of model as described in this tutorial:Finetuning Torchvision Models — PyTorch Tutorials 1.2.0 documentationIe. the problem is that the last layer has different names for different pretrained models, lik... | ptrblck | I don’t believe there is a safe way to get the last layer, since even indexing the last module from model.children() would return the module initialized last and not necessarily the layer used last in the forward. Since your model could use different execution path in the forward (e.g. Inception mod… |
Papaa_Emeritus | Hello everyone, I am trying to implement Pytorch LSTM to stock market closing prices using historical values.My input features are Open, High, Low, Close and Volume values for 12 days and my target variable is the closing price for the 13th day. So from my understanding, my input size is 5, output size is 1 and number ... | ptrblck | Based on your description of the use case I would assume your output would have the shape [batch_size, 1] and you are working on a regression task.
To do so you could pass the output activation from the last time step of the lstm to the linear layer, which should have the expected shape afterwards. … |
sevagh | Hello,I’m trying to speed up my model inference. It’s a PyTorch module, pretty standard - no special ops, just PyTorch convolution layers.The export code is copied from this tutorial(optional) Exporting a Model from PyTorch to ONNX and Running it using ONNX Runtime — PyTorch Tutorials 1.9.0+cu102 documentation:if __nam... | ptrblck | Creating a 39MB file in 8h seems terrible and I still think that this cannot be expected.
Good to hear the script finally finished, but I guess the export might have been slower than the model training?In case you can reproduce it, could you create an issue onGitHub, please? |
seer_mer | Usually, when we want to train on a certain device, we do xxx.to(device), a typical procedure isx = x.to(device)
y = y.to(device)
model = model.to(device)where you add data and model to the desired device.However, I noticed that some people also add criterion (loss function) to device:criterion = criterion.to(device)Is... | ptrblck | The necessity of calling criterion.to(device) would depend on the used criterion and in particular if it’s stateful, i.e. if it contains internal tensors etc.
In the latter case, you should get a device mismatch error in case this line is missing and needed, so in case you are not getting any error… |
AlphaBetaGamma96 | Hi All,I just have a quick question regardingRecursiveScriptModule, I’ve built a custom optimizer and within it I cycle through all layers viafor module in net.modules()and call the name of themoduleviamodule.__class__.__name___. I need this as my optimizer handles different layers differently, and I determine what typ... | ptrblck | module.original_name would return a string containing the original module name, e.g.:
lin = nn.Linear(1, 1)
s = torch.jit.script(lin)
print(s.original_name)
> 'Linear'
so you could try to use this attribute instead. |
JamesDickens | The graph used in the docs available herehttps://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.htmlis the graph of the regular ReLU function. The slope of the graph for x<0 should be non-zero. Is there somewhere to report this so it can be fixed? | ptrblck | I don’t think the plot shows the plain ReLU, but a LeakyReLU using the default negative_slope value of 1e-2.
You can zoom in a bit and would see the tiny slope:[image]To reproduce the figure, run:
act = torch.nn.LeakyReLU()
x = torch.arange(-7, 7, 0.01)
out = act(x)
f = plt.figure()
plt.xlim… |
Atila1 | Dear all,I have a 4D tensor [batch_size, temporal_dimension, data[0], data[1]], the 3d tensor of [temporal_dimension, data[0], data[1]] is actually my input data to the network. I would shuffle the tensor along the second dimension, which is my temporal dimension to check if the network is learning something from the t... | ptrblck | In that case the indexing with idx created by randperm should work and you could skip the last part. This would shuffle the x tensor in dim1. |
bhaktatejas922 | Getting this strange error during validation. Can’t find the same issue online. Are some of my batches being empty somehow?Traceback (most recent call last):
File "/home/tbhakta/anaconda3/envs/test/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/home/tbhakta/anaconda3/envs... | ptrblck | For now you could use it as a workaround, as it’s unclear what’s causing the workers to crash.
In case you are using an older PyTorch version, I would recommend to update to the latest release. Also, to further isolate the issue, could you try to post an executable code snippet, which would reprodu… |
Z_Huang | This question may sound silly. Is it possible to take a few layers from a built-in model for example resnet50?For example, I only want to pull out the first 2 layers from resnet50. Is it a possible way to make that happen? | ptrblck | Yes, this will also work:
class NewNet(nn.Module):
def __init__(self):
super().__init__()
resnet = models.resnet50()
self.conv1 = resnet.conv1
self.bn1 = resnet.bn1
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
retur… |
Wei_Lighter | I am training my models(pretrained resnet and densenet) in rtx 2080ti, it works well. When I move the models to rtx a6000(i need lager batch size)the bug occurs, about 4.5GB is allocated and nearly 40GB is free! I have no idea about this bug, anything could help thank you very much. | ptrblck | Thanks for the update to the code.
I cannot reproduce the issue on an A6000 and the script runs fine for a few epochs:
root@dc9def623dde:/workspace/src/OOM-occurs-while-I-have-enough-cuda-memory# python run2.py
Namespace(base_path='/data/guest1/clothing1m/', batch_size=64, cuda_device=0, img_size… |
Ameen_Ali | Hello,Let’s assume I have a Tensor of shape [M , D] where M is the number of samples and D is the feature dimension. additionally a mask tensor of shape [M , K] which contains K different indices for each of the M samples.my question is how can I for each of the M samples calculate the mean of its K indices (for each s... | ptrblck | Ah OK, so idx would be used in dim0:
M, D, K = 5, 4, 2
x = torch.randn(M, D)
print(x)
> tensor([[ 0.3545, -1.2674, -0.1321, -0.4732],
[-0.9573, 0.8507, -0.1691, 0.6376],
[ 0.1386, -1.4488, 0.5860, -0.0135],
[-0.9486, -0.2253, -1.0952, -0.0432],
[-0.0213, … |
leckofunny | Hello everybody,the authors (Bjorck et al. 2021) of the paper “Towards Deeper Deep Reinforcement Learning” share a plot (Figure 3) showing the gradient of the actor and the critic loss (SAC).plot1404×465 83.2 KBI’ve got no idea how this plots was achieved, because the gradient of the loss is 1.0 after calling backward(... | ptrblck | I don’t think these plots show the loss gradient, but might show the (accumulated) gradients of all parameters.
From the paper:
Results averaged over five runs are shownin Figure 3. The losses initially start on the same scale, but the modern network later has losses thatincrease dramatically — s… |
damca | I have trained a Unet-esque model on 512x512 images. Training and evaluation perform without error.However, I would like to evaluate the model on a much larger image, ~15,000x40,000.I have 24 GB of total GPU memory. After loading the model’s state dictionary and sending to the gpu, the gpu memory usage istorch.cuda.me... | ptrblck | The forward pass would calculate the forward activations, which would also need to be stored temporarily, so the OOM issue could be expected. What was the peak memory usage using the 512x512 images? |
Tryfonm | I m probably missing something obvious, but i cant figure it out. I tried to reproduce partly the running statistics of a BatchNorm2d layer (while on train mode) but i dont seem to be able to get them right. It’s not like it matters, but i m just curious at this point what i m doing wrong. Here is my attempt:class Batc... | ptrblck | The running_var update is performed using the unbiased variance as seen inmy manual exampleand thePyTorch backend implementation. |
pierremrg | Hi all,I’m performing cross-correlations between images and kernels. But it’s common that I need to perform a cross-correlation on anunique imagewith manydifferent kernels.All kernels have the same shape, so a simple solution is to batch them, and duplicate the image along the batch dimension. Doing so, I have the foll... | ptrblck | Thanks for the code snippet.
Your approach looks valid assuming you are using different images in f_img.
However, based on your previous description:
it seems that f_img would contain only a single unique image and you are repeating it in the batch dimension to use the view operation with the gr… |
Jendker | Hello! This is my first post on this forum.I wanted to ask you if you see any use of utilizing DataLoader for parallel data loading into batches if all the data is already stored in the memory? Is the data actually prepared in advance or is it split into batches still done in sequence with the main loop with only data ... | ptrblck | Each worker in the DataLoader will create a batch by calling into Dataset.__getitem__ with the corresponding index and will add the batch to the queue.
It depends on your use case, if using a DataLoader (with multiple workers) would yield a speedup.
E.g. if you are preloading the entire dataset, a… |
Mari | Hi,Is there any suggestion about how I can implement below conditions for kc which is a tensor in pytorch?following conditions give this error:“Boolean value of Tensor with more than one value is ambiguous.”net_in = torch.cat((x,y),1)kc = net2_kc(net_in)kc = kc.view(len(kc),-1)if kc>0.5:f = (kc-0.5)^2elif 0 <= kc <= 0.... | ptrblck | The if condition checks for a single return value, so applying it to a tensor won’t work out of the box and you could index the tensor instead.
I.e. using the posted conditions, you could apply the changes to parts of the tensor.
Something like this might work:
kc = torch.randn(10, 2)
f = torch.z… |
Soumyajain29 | I have a 3D tensor A of shape (M, N, K) where M is the batch size, N is sequence length, and K is embedding dimension. I also have a list of indices along dimension 1 (i.e., indices for sequence length dimension). I am unable to figure out how to get elements of A based on this indexing.For ex- M = 2 , N = 4 , K = 2A =... | ptrblck | This should work:
A = torch.tensor([[[1,2],[3,4],[5,6],[7,8]] , [[9,10],[11,12],[13,14],[15,16]]])
index = torch.tensor([0,2])
out = A[torch.arange(A.size(0)), index]
print(out)
> tensor([[ 1, 2],
[13, 14]]) |
Huaiyang_Gongzi | Hello, I was following the Pytorch tutorial of [customizing dataloader class], everything works just fine except when running the last segment of code. It just stay there without finishing, and does not print any output either.tutorialoutput1137×1000 95.1 KB(Developing Custom PyTorch Dataloaders — PyTorch Tutorials 1.7... | ptrblck | Could you set the num_workers to 0 and try to rerun the cell?
Depending on your setup etc. multiprocessing might run into issues (e.g. theWindows FAQexplains the if-clause guard, which is needed for Windows setups). |
Jamboulie | Hello everyone,I am new to PyTorch, so please excuse me if my problem is trivial :). At the moment I am trying to rewrite a code implementing the reinforcement learning algorithm Soft Actor Critic (SAC) together with an LSTM-layer shared by all the neural nets involved. My version of the code is exactly the same as the... | ptrblck | As a first debugging step you could make sure that the same parameters are properly registered and returned in model.parameters() in both approaches. Once this is done, make sure you are not freezing some parameters differently (if that’s even used). If this is also verified, I’m unsure why the opti… |
luvwinnie | I have a neural network implemented in pytorch which i wished to used for augment the dataset within Dataloader. I loaded the neural network in a python generator and pass it to Dataloader. However it seems like it initialized multiple neural network on CPU, it there anyway or anybody know a way to use a neural network... | ptrblck | If you want to use the model on the GPU, I would probably just use it inside the DataLoader loop, as it would process an entire batch (while in the __getitem__ of the Dataset it would process a single sample by default). Re-initializing it in the collate_fn wouldn’t yield any gain (besides the initi… |
ajoshi944 | I have to compare two different implementations of a network architecture with corresponding parameters. I know the number of parameters of the models is one way to make sure the implementations are similar. But, is there any other/ correct way to do this?Thank you. | ptrblck | You could additionally try to print the graphs of both models (assuming you want to compare the forward/backward pass) and check if the computation graphs are also equal. |
ashcher51 | I am trying to train a custom convnet, and I am getting this error:RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x25088 and 784x16)From what I have seen, I understand that there is an issue with inputs/outputs with each layer, but I am not sure where exactly is my mistake. Can anyone help me out with figuri... | ptrblck | The in_features of self.fc1 = nn.Linear(784, 16) do not match the number of features in the flattened activation in:
x = torch.flatten(x)
x = self.fc1(x)
so you would need to set in_features of fc1 to 20588 or adapt the input shape to the model. |
Astariul | I thought that for same input, we should receive same output, no matter the batch size.But I tried a small experiment, and it’s not confirming my intuition…I define a simple network :import torch
import torch.nn as nn
smol = nn.Sequential(
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU()
... | ptrblck | Different algorithms could be used for different input shapes, which would thus create the small errors due to the limited numerical precision.
E.g. a different order of operations would also create these numerical differences as seen here:
x = torch.randn(10, 10, 10)
s1 = x.sum()
s2 = x.sum(0).su… |
samarendra109 | I have a basic scenario like this,import torch
def someFn(w):
return w.sum(dim=1)
w = torch.rand(10,3,2)
fW = someFn(w)
fMinW, fIndex = fW.min(dim=1)
# Select wmin of size 10,3Now I want to select the 10 (1x3) vectors that correspond to the fMinW output. How can I achieve this ? | ptrblck | Assuming the desired output can be created via:
res2 = []
for idx in range(w.size(0)):
res2.append(w[idx, :, fIndex[idx]])
res2 = torch.stack(res2)
then this should work:
res1 = w[torch.arange(w.size(0)), :, fIndex]
# compare
print((res2 == res1).all())
> tensor(True) |
Mwni | The goal: transform a 1d vector of length 512 into an 3x299x299 image.The attempt is to transform each value of the vector into a 1x1 channel, then deconvolve/upsample from there. Sadly, trying to run ConvTranspose2d over a tensor of size (512, 1, 1) throwsKernel size can not be greater than actual input sizeBelow is a... | ptrblck | It works for me trying to create an output of 2x2 from a single pixel:
x = torch.randn(1, 1, 1, 1)
conv_trans = nn.ConvTranspose2d(1, 1, kernel_size=2)
out = conv_trans(x)
print(out.shape)
> torch.Size([1, 1, 2, 2])
so I guess your setup might be different? |
johannesgensheimer | Hello everyone,I’m building a CNN model in PyTorch for Image Super Resolution. After applying the model to the low resolution image I want to validate only a small part of the image against a high resolution image, meaning that I have to post process the model output (shape 100x100) so that it is only an array (shape 5... | ptrblck | Your code should work as seen here:
model = nn.Conv2d(3, 1, 3, 1, 1)
input = torch.randn(1, 3, 100, 100)
pred = model(input)
pred_array = pred[:, :, :50, 0]
print(pred_array.shape)
> torch.Size([1, 1, 50])
loss = F.mse_loss(pred_array, torch.rand_like(pred_array))
loss.backward()
and the error me… |
CasellaJr | I have two datasets, MNIST and SVHN.It is known that the num. test samples of MNIST is 1000 and the num. test samples of SVHN is 26032.Now, i want to append the test set of SVHN to MNIST, in the sense that test_set_append[9999] is the last element of MNIST, and test_set_append[10000] is the first element of SVHN.I have... | ptrblck | In your custom ConcatDataset you are returning a tuple containing samples of both datasets, but I think torch.utils.data.ConcatDataset would directly work. |
sheraz | sample 1973×411 24.5 KB | ptrblck | The error is raised in an nn.Conv2d layer, which uses in_channels=300, while the incoming activation has only 128 channels, so you would have to change the in_channels argument of this layer. |
AP_M | While trying to execute the below code, getting the error which I am not able to understand. Plz suggestclass Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(6, 16, kernel_size=3, stride=1... | ptrblck | This shape mismatch error might be raised by a linear layer, which expects another in_features shape.
I’m currently unsure which layer it would be so you would need to check for in_features=7680 in your model definition and change it to 3072, as this seems to be the number of features used in the a… |
MRRP | Hi Pytorch CommunityI want to decompose a tensor into some non_overlapping tensors. Let me show you an example of what i want to do. Assume that i have a tensor which it’s elements are only 1 like:a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]Now i want to decompose it into a few non_overlapping tensors. here for simplicity we ... | ptrblck | Given your example, you might be looking for scatter_:
a = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=torch.float32).unsqueeze(0)
b = torch.zeros(2, a.size(1))
idx = torch.randint(0, 2, (1, a.size(1)))
b.scatter_(0, idx, a)
print(b)
> tensor([[0., 0., 1., 1., 0., 0., 1., 1., 0., 0., 1.],… |
ericlormul | When debugging a neural network model, do we expect to get 0 loss on a single batch? For example, running 1000 times optimization on the same single batch input.If the loss is close to 0, we can conclude the model is able to overfit on that batch.if the loss is far from 0, e.g. say start at 5.5 and end at 4.7, what do... | ptrblck | I would not expect a perfect 0 as the final loss in any case alone due to the limited floating point precision (but a small value instead).
By “standard” criterion I meant the loss functions included in torch.nn assuming you are not inverting them or add any constant etc.
E.g. depending on your us… |
milan_kalkenings | Hi all,I am new to pytorch and I wonder why my neural network doesn’t train. The loss is always the same in every epoch and the execution time per epoch implicates that no training really happens.Sry for the long post…class NeuralNetwork(nn.Module):definit(self):super(NeuralNetwork, self).init()self.flatten = nn.Flatte... | ptrblck | I assume you are working on a binary classification.
If that’s the case, note that nn.Softmax would output a tensor of ones for an input tensor (activation coming from the previous linear layer) in the shape [batch_size, 1], so you might want the use nn.Sigmoid instead.
For better numerical stabil… |
111119 | Hi, I’m struggling to make my deep learning network for A2C model.My networks can’t be updated bcz of error displayed bottom image.I can’t understand what is the cause of this problem.Does anyone know about this problem in detail?(I already check my Critic-network gradient check by torch.autograd.gradcheck. it returns ... | ptrblck | This error is raised, if you are trying to call backward() on a tensor, which isn’t attached to the computation graph and you can verify it by checking its .grad_fn attribute which would return None.
This might happen, if you’ve detached the tensors manually (e.g. via calling detach() directly, usi… |
nikhil6041 | I am trying to add fivecrop to my torchvision.transforms pipeline but as per the doc it returns me a tuple of 5 instead of all the 5 images i want to randomly select one of them and then feed it to the network . If there is any way to do this?@ptrblckWould you have a look at it? | ptrblck | I’m unsure if I understand the issue correctly, as a tuple of 5 images would return all images.
To randomly select one of them, you could use torch.randperm and use it to index the returned images:
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.FiveCrop(size=(10, 10))… |
alee023 | I’m trying to input a 5D tensor with shape ( 1, 8, 32, 32, 32 ) to a VAE I wrote:self.encoder = nn.Sequential(
nn.Conv3d( 8, 16, 4, 2, 1 ), # 32 -> 16
nn.BatchNorm3d( 16 ),
nn.LeakyReLU( 0.2 ),
nn.Conv3d( 16, 32, 4, 2, 1 ), # 16 -> 8
nn.BatchNorm3d( 32 ),
nn.Lea... | ptrblck | Based on the error message I would assume that the error is either raised in self.fc_mu or self.fc_logvar, since both are using the mentioned 3072 in_features.
You could add debug print statements to the forward method of your model and check the shape of the input activations to these layers, whic… |
Hristo_Petkov | Hello! Just upgraded from my old version of pytorch to 1.9. I ran some code I am using which involves DataLoaders. In the old version of Pytorch it works as expected. In this one I get this error:AttributeError: ‘DataLoader’ object has no attribute ‘persistent_workers’I’ve been searching in the source code for the clas... | ptrblck | I’m still unsure, what might be causing the issue, as this code snippet works fine for me:
import torch
from torch.utils.data import Dataset, DataLoader, TensorDataset
print(torch.__version__)
dataset = TensorDataset(torch.randn(100, 1), torch.randn(100, 1))
loader = DataLoader(dataset, batch_size… |
zyh3826 | Hi, everyone, I got this error when the program running on GPU, but everything is ok when running on the CPU微信图片_202107282004211649×245 17.1 KBmy model is a simple seq2seq model.Hope someone can help me, thanks a lothere are my system infomations:PyTorch Version (e.g., 1.0): 1.7.1
OS (e.g., Linux): Ubuntu 18.04.5 LTS (... | ptrblck | Could you remove the inplace operations (such as seq -= (1 - mask) * 1e10) and rerun the code?
The different CPU/GPU (via cuDNN) implementations might have different requirements to store the unmodified forward activation. |
t0mo | Hi, I’m new in pytorch as well as in deep learning.I have used this repository:GitHub - LixiangHan/GANs-for-1D-Signal: implementation of several GANs with pytorch(dcgan is part im interested in) I changed training set for my needs and it performed pretty well. Now I would like to use trained generator to generate data ... | ptrblck | After training the models, you could create a new Generator and load the trained state_dict via:
netG = Generator()
netG.load_state_dict(torch.load(path_to_generator_state_dict))
Afterwards, you could execute the forward pass using the same inputs as were used to train this model:
with torch.no_g… |
aswamy | Hello,I have a model ‘m’ which is a torch.nn.ModuleList of 30 fully connected layers. Now I have to send this model ‘m’ in the forward() method of another model ‘K’ in every training iteration.Pseudo code of above description:class M(nn.Module):
def __init__(self,):
super().__init__()
nw_1 = nn.Line... | ptrblck | By default the models would by on the CPU, so you would still make sure to push them independently.
I think your approach of using the functional API for these fixed parameters looks good and I probably wouldn’t try to use modules and reload the parameter. In case you still want to do so, you could… |
Siarhei_D | After usage spectral_norm after backward no grad:import torch
import torch.nn as nn
import torch.nn.utils.spectral_norm as spectral_norm
m = nn.Conv2d(1,1,3,1,1)
m(torch.randn((1,1,3,3))).mean().backward()
print(m.weight,m.weight.grad)(Parameter containing:tensor([[[[ 0.1578, 0.1756, 0.3056],[ 0.1704, -0.0901, -0.172... | ptrblck | SpectralNorm manipulated the weight parameter as seenhereso you could access the gradient via m.weight_orig.grad. |
PatricYan | two tensors in different dimensions, for example, A1=[B, H, V] A2=[H], how to contenate the two tensors to [B, H, V+1]? | ptrblck | This should work:
B, H, V = 2, 3, 4
A1 = torch.randn([B, H, V])
A2 = torch.randn([H])
A2 = A2[None, :, None].expand(B, -1, -1)
print(A2.shape)
out = torch.cat((A1, A2), dim=2)
print(out.shape)
torch.Size([2, 3, 5]) |
Ammara | Hi, I create a model and then wrap it in Data Parallel.model = DataParallel(model)Now, can I resume the model from a checkpoint using load_state_dict()?model.load_state_dict(checkpoint[‘model_state_dict’])will the new model weights be broadcasted across all gpus? | ptrblck | Yes, nn.DataParallel will scatter the parameters in each forward pass, so it should work.
This is also the reason for the lower performance compared to DDP, which has a reduced communication overhead. |
OBouldjedri | Hi I am training a neural network on pythorch using the training / validation/ test configuration.for the optimizer I am doing this:optimizer = optim.Adam(model.parameters(), lr=args.lr)scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, verbose=True, patience=15, min_lr=1e-6)but I was wondering if the scheduler st... | ptrblck | I would use the validation loss and would not use the test loss at all (neither for the scheduler, nor early stopping etc., as I would consider it a data leak).
Once your training is finished using the training and validation datasets, you would use the test dataset once and deploy the model. |
AlphaBetaGamma96 | Hi All,I have a quick question about merging 2 tensors together. Let’s say I have 1 tensor of shape [N,] which represents the diagonal of an N by N matrix. And another matrix which is of shape [N, N-1] and represents the off-diagonal elements, is it at all possible to merge the two different tensors together in an effi... | ptrblck | I’m sure there are better ways, but this should work:
tmp = torch.cat((diag[:-1].unsqueeze(1), off_diag.view(3, 4)), dim=1)
res = torch.cat((tmp.view(-1), diag[-1].unsqueeze(0))).view(4, 4)
print(res)
> tensor([[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34],
[41,… |
Simon_Kassab | Hi, I’m trying to adapt some code to run on multiple GPUs. To do so, I’ve followedthis example. It seemed quite simple and seamless. I was able to make it work on a simple dummy example.However, I’m unable to make it work on my actual code. I keep getting the following error:RuntimeError: Expected all tensors to be on ... | ptrblck | You are creating self.hidden and self.BN as plain Python lists, which won’t work.
To properly register modules you would need to use nn.ModuleList instead and it’ll work. |
Samue1 | I want to use the indices returned bymax_pool2d_with_indices(x)to extract elements from a tensormwith the same dimensions asx. However, the returned values are wrong. Here is a minimal working example:import torch
def main():
x = [[[[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0,... | ptrblck | You could flatten the tensors and use gather to get the desired output:
out = torch.gather(torch.flatten(m, 2), 2, torch.flatten(idx, 2)).view(idx.size())
print(out)
> tensor([[[[15., 16.],
[19., 20.]],
[[26., 29.],
[38., 41.]]]]) |
Ajinkya.Bankar | I am studying the tutorial givenhereto profile the CPU time of the model. I get an error messageModuleNotFoundError: No module named 'torch.profiler'. I have torch version 1.7.1 installed. May I know what’s the problem? | ptrblck | The new profiler was released in 1.8.1 as described inthis blog postso you would have to update PyTorch. |
Omroth | mask has shape [125]dots has shape [100, 125]First I want to multiply each element in column c in dots by mask[c]Second I want to sum each column c of dots to end up with a tensor of shape [100]for (int i = 0; i < 125; i += 1)
{
for (int j = 0; j < 100; j+= 1)
{
dots.inde... | ptrblck | You could use broadcasting for the first operation and sum(1) for the second one as seen here:
# setup
mask_ref = torch.randn(125)
dots_ref = torch.randn(100, 125)
# loop approach
mask = mask_ref.clone()
dots = dots_ref.clone()
for i in range(125):
for j in range(100):
dots[j, i] = do… |
jungminc88 | The dataloader I have is derived like this:from torch.utils.data import DataLoader,TensorDataset
dataset = TensorDataset(tensor0, tensor1)
dataloader = DataLoader(
dataset,
sampler = RandomSampler(dataset)
batch_size = batch_size
)Then I realized I had to addtensor2when... | ptrblck | The DataLoader uses the provided Dataset to create the batches. Based on your description it seems that you would like to add the new tensor to the Dataset. Outside of the DataLoader loop, you could access it via dataloader.dataset and could also try to reassign a new Dataset. However, theTensorDat… |
Jamesong7822 | Hi Pytorch Gurus,I found a similar question, but it was left unanswered:Training an ensemble model with and without saperatelyI believe I have a similar question.I would like to ensemble 2 models together which I have trained. The classifier will be in charged of predicting whether there will be retweets or not (basica... | ptrblck | As the error message claims, you cannot use an if condition on multiple values and would need to split the tensor.
Assuming you want to pass the values matching the condition to self.modelPredictor and return the others, you could apply this workflow:
# output from previous layer
x = torch.randn(1… |
mishi | Hii, I’ have made a Graph convolution network which takes 2 graphs as inputs and gives output between 0 to 1 , After running on one sample , it shows this error . Please helpimage1089×518 61.6 KB | ptrblck | The error points to an invalid index.
You could rerun the code either on the CPU to get the line of code causing the issue or on the GPU via CUDA_LAUNCH_BLOCKING=1 as suggested in the error message. |
Xsurgeon | I want to know how to change the model modules from storing them in Orderdict to Moduledict.I want to know how to convert the model if it is already in Orderdict.Thanks | ptrblck | The state_dict will return the parameters and buffers, so you could try to use an nn.ParameterDict.
nn.ModuleDict is for nn.Modules and works fine:
# plain dict
d = {'a': nn.Linear(1, 1),
'b': nn.Linear(2, 2)}
m = nn.ModuleDict(d)
print(m)
# OrderedDict
d = {'a': nn.Linear(3, 3),
'b': n… |
yuejiang_li | Hi, I have a question of getting certain indexed element from a tensor.For example, I have a tensora = torch.arange(24).to(torch.float).reshape(2, 3, 4)
a.requires_grad = True
print(a)
# output
tensor([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]],
[[12., 13., 14., 15.],
... | ptrblck | Rewrapping a tensor in torch.Tensor will detach it from the computation graph, so you might want to use torch.cat or torch.stack instead. |
Arturas_Druteika | I don’t know if it is even worth to ask this question in this forum, but I was wondering if it is a good, neutral or bad practice to specify loss as well as optimizer inside the model class, for example:class Net(nn.Module):
def __init__(self, in_features, n_classes, lr):
self.fc_1 = nn.Linear(in_features, ... | ptrblck | I agree with@KFrankalso also think that the model, criterion, and optimizer are separate units, which can be independently used and changed.
E.g. reusing your “model” to finetune it in another scenario would also recreate your optimizer, which would not be needed. Restoring a checkpoint also woul… |
Alessio_Rosatelli | I can’t provide all my code since it is quite extensive. Anyway below you can find my line of code regardig the DataLoader, the Sampler and respective output. My train dimensions and test dimensionsare [1530,600,8] and [428,600,8] and my batch_size in 170self.test_samples_weight = [weight[class_id] for class_id in Labe... | ptrblck | Based on your weights, I assume you might have multiples of this distribution:
class_counts = torch.tensor([104, 642, 784])
If so, I’ve manipulated my example code to use your weights and data distribution to get approx. equally distributed batches:
# Create dummy data with class imbalance 99 to … |
JosueCom | If I implement a dynamic layer as present below, it’s output shape doesn’t get affected. See code below for greater details.>>> import torch as th
>>> import torch.nn as nn
>>> import torch.nn.functional as F
>>> class DyLinear(nn.Module):
... def __init__(self, in_fea, out_fea, device = 'cuda'):
... super(... | ptrblck | In your code you are setting self.out_fea to size before the actual creation of the new nn.Parameter so that torch.randn will yield an empty tensor (size - self.out_fea will be 0).
Move the update of self.out_fea after the new parameter assignment and it should work. |
artichoke | I have a model that trains fine without weight initialization but when I try to initialize the weights of my model to custom values (generated by custom_weight_fn), it stops training. Here is the code:def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
m.weight.data=custom_weight_fn(m.weight.sha... | ptrblck | Don’t use the .data attribute as it’s deprecated and could yield any side effects.
Instead, wrap the code in a with torch.no_grad() block and assign new nn.Parameters to the module parameters or use m.param.copy_ instead. |
marcus_pazini | I’m fairly new to pytorch and currently i would like to train a model wich consists in the following:I have one already trained model (net1) wich receives as an input the output of a untrained model (net2), and generates on output. (net2 → net1 → output)Then my question the is, is it possible compute the gradient throu... | ptrblck | Yes, that’s possible and you could directly pass the output of net2 to net1, compute the loss, and call loss.backward() to compute the gradients.
If you don’t want to train net1, you could freeze all parameters of it via:
for param in net1.parameters():
param.requires_grad = False
To update t… |
Henseljahja | Dear experts, so i just moved from tensorflow to Pytorch and i have a list of images in directories as suchroot/
ImageA/
ImageA001.jpg
ImageA002.jpg
,,,,,,,,
ImageB/
ImageB001.jpg
ImageB002.jpg
,,,,,,,,and labels of regression value like ... | ptrblck | Based on the error message it seems you are not transforming the PIL.Image to a tensor, so I guess in your code the transform argument might not be set properly. Note that your posted code snippet uses root_dir instead of img_dir, soI assume your real code is not using the same posted code.
To furt… |
ChiTseHuang | I modify a custom autograd function like thisI thought this error is caused by multiple return values from function Abut I need min scale to make other codes run properly.class A(torch.autograd.Function):@staticmethoddef forward(ctx, input, qparams=None):…return output, min, scale@staticmethoddef backward(ctx, grad_out... | ptrblck | The backward would expect the same number of input arguments as were returned in the forward method, so you would have to add these arguments as described in thebackward section of this doc. |
jhp | Hello, I’d like to ask about data loader.The data I’m using is very big, so I’d like to experiment with subsets and compare with multiple baselines for comparing with my model quickly. Would it be possible to experiment with subsets simply by reducing the length in the loader (i.e__len__: return {original_data_length... | ptrblck | Yes, you can reduce the len of the Dataset, which would then create samples using index values in the __getitem__ method in [0, len(dataset)-1]. |
yuanx749 | When using dropout in a multilayer LSTM trained on GPU, the weights are different across training. I have reset the same seed before training, so the dataloader has the same behaviour and the model has the same initialization. Note that the results are the same across different runs of the whole script, but different a... | ptrblck | I think the deterministic behavior for each script run is expected, but there is no guarantee to get deterministic output inside the script by rerunning the code.
For the cudnn RNN implementations you can see that the dropout state is initialized oncein these lines of code, which explains why you … |
Rituraj_19_Dutta_100 | I’m writing a module that includes some Conv2D layers and I want to manually set their weights and make them non-trainable. My module is something like this:import torch
import torch.nn as nn
def SetWeights():
## manual function to set weights
return
## Returns a 4D tensor
class Module(nn.Module):
def __... | ptrblck | You can either assign the new weights via:
with torch.no_grad():
self.Conv1.weight = nn.Parameter(...)
# or
self.Conv1.weight.copy_(tensor)
and set their .requires_grad attribute to False to freeze them or alternatively you could also directly use the functional API:
x = F.conv2d(inpu… |
Mai_Magdy | Epoch: [1][0/25] Loss 0.5619 (0.5619)Prec@1 73.438 (73.438) Prec@5 100.000 (100.000)Epoch: [1][20/25] Loss 0.5804 (0.7834)Prec@1 73.438 (67.113) Prec@5 100.000 (100.000)I have two classes and prec 5 always 100 is it okay or I have a problem ? | ptrblck | I think the plain accuracy calculation would be sufficient for a binary classification use case and you could remove the Prec@5 one. |
pramesh | Hello,The requirement is :create initialization(w0,b0)<–init()i need to use the same weight for online model and global model at first epoch and need to do self update of weight and bias…I have done following but its not working…please support me …I have done the initilization by following code,def init_normal(m):
... | ptrblck | To use the init_normal function, you would have to use it via model.apply(init_normal).
I’m unsure what the real use case is and what exactly is not working, so could you explain the use case and problems a bit more? |
char-t | Quick one - is it necessary to use a manual seed when using DDP to ensure all local models initialise with the same parameters? I have been looking and seen examples that do and examples that don’t but nothing definitive.Many thanks! | ptrblck | No, DDP shares the state_dict in the first iteration, so you won’t need to seed the code for the parameter initialization, but might need it for other use cases.
From theDDP Internal Design:
The DDP constructor takes a reference to the local module, and broadcasts state_dict() from the process w… |
kyy | Hi, I notice my jupyter notebook is using super large memory (~40GB) when it is running, and after using the tool here:How to debug causes of GPU memory leaks? - #2 by SpandanMadan, I found most memory is used by some intermediate tensor variables. For instance, if I have a large numpy arrayX, and pass it to a network... | ptrblck | Intermediate tensors will be freed, once backward() (without retain_graph=True) is used and these intermediates are not needed for the gradient calculation anymore.
If you don’t need to compute the gradients and call backward(), you can wrap the forward pass into a with torch.no_grad() block, which… |
Myailab | Hi, Can I please get some help here.I have been using the following code to obtain:output = model(images)where model = get_resnet34()def get_resnet34(num_classes=6, **_):
model_name = 'resnet34'
model = pretrainedmodels.__dict__[model_name](num_classes=1000, pretrained='imagenet')
arc_margin_product=ArcMarg... | ptrblck | The error doesn’t match the posted code, as you are not using model.norm() anywhere.
After creating the model, you could replace the last linear layer with an nn.Identity module to get the features instead of the logits from the last layer. |
ArshadIram | I am following this document to implement DC GANDCGAN Tutorial — PyTorch Tutorials 2.2.0+cu121 documentationHowever, I am not using num_workers = 2. I am only using Default workers and device is cuda:0.on training the generator and discriminators I am getting this error:image1183×268 41.2 KBHere is the code line:image7... | ptrblck | The forward method seems to be outside of the model definition, so you would have to add an indentation.
PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier. |
SarthakJain | Hi,For the last couple of weeks, I have been really struggling to debug this new problem when training my detection model. Couple of weeks before the training worked great, but now all of a sudden I get this new unheard error.I make my model and train overall like this but still get an error.#Model
torch.set_default_d... | ptrblck | Could you remove the torch.set_default_dtype line of code and explicitly cast the tensors to the desired dtype? |
seyeeet | So I have this confusion for months now, should I use clone in the folliwng code forx?I am not sure if it is important or not, but I appreciate if someone can help me understand it.Is it gonna effect the learning if I go with any of the following samplesLets say I have a model that somewhere in it I have to use branche... | ptrblck | You would have to clone() the input to the separate branches, in case they are using inplace operations in the first branch, as it would yield unexpected results in the second (and further) branch as seen here:
lin = nn.Linear(10, 10)
branch1 = nn.ReLU(inplace=True)
branch2 = nn.Sigmoid()
# withou… |
malioboro | Do we still need to usemanual_seedif we have setuse_deterministic_algorithms(True)to create a reproducible code?Because as far as I understand, the two functions are interchangeable. Is this true? | ptrblck | You would need to use both, as setting the seed would make sure the pseudorandom number generator would return a deterministic output, while using deterministic algorithms would force e.g. cudnn to select deterministic kernels and could also use a different code path for native functions. |
Programmer-RD-AI | how to get val loss CNN Pytorch Output 1 (Sigmoid) Output Layer Criterion = BCELoss() | ptrblck | loss.item() will return a Python scalar value, which is detached from the computation graph.
If you want to use this loss for training, you should remove this line of code.
Also, I’m unsure why you need to push the preds and y_batch, to the CPU, but I’m also not familiar with your use case, so you… |
danielmanu93 | Hi everyone, I have a class “MolecularDataset” which has a self.data argument at line 35 to line 39 as shown in the first pic. I want to access this “self.data” argument in a function “data_noniid” defined outside the class as in the second pic but I have tried both “MolecularDataset.generate.data” and “MolecularDatas... | ptrblck | Yes, exactly. I’ve used args as a placeholder for the actual input arguments for generate. |
Rituraj_19_Dutta_100 | I wanted to create aNonedimension in a Pytorch tensor just like we do in Keras something like(None,224,224,3). Is it possible in Pytorch? | ptrblck | I don’t think it’s possible to add this “symbolic” None dimension to a PyTorch tensor (at least not in the standard eager tensors), as it wouldn’t be needed. If I’m not mistaken, Keras (and/or TF) uses it to specify a dimension with a variable size. If so, you can just use a different (batch) size i… |
Lukens | I am using this model:GitHubGitHub - kylemin/S3D: Release of the pretrained S3D Network in PyTorch (ECCV...Release of the pretrained S3D Network in PyTorch (ECCV 2018) - GitHub - kylemin/S3D: Release of the pretrained S3D Network in PyTorch (ECCV 2018)I should train the model to recognize a series of (volcanic) videos ... | ptrblck | Yes, you can pass a tensor in the shape [nb_classes] as the argument to pos_weight.
In case you want to split the output in dim1, you could use output.split(1, dim=1). |
Mayur28 | Hi!I have been trying to optimize the way that I am looking my image data, and I have considered using pin_memory =True, however, when I profiled my code (using torch.utils.bottleneck), I noticed something unusual.(All experiments I conducted were for 1 epoch using an 8GB image dataset (LRS2))When pin_memory =True, mos... | ptrblck | Your system might suffer, if you lock too much memory for the data (and thus other processes won’t be able to use this memory and their performance might decrease). For this reason it’s also not used by default. |
Rajat_Sharma1 | I have a situation where for each mini-batch, I have multiple nested data, for which model need to be trained.for idx, batch in enumerate(train_dataloader):
data = batch.get("data").squeeze(0)
op = torch.zeros(size) #zero_initializations
for i in range(data.shape[0]):
optimizer.zero_grad()
c... | ptrblck | This might be the culprit, as the computation graph might be kept alive using this approach.
Assuming you don’t want to backpropagate through the previous iterations, you could detach the tensor via op.detach_() in each iteration. |
Abdul-Abdul | I’m trying to train the MLP mixer on a custom dataset based onthis repository.The code I have so far is shown below. How can I save the training model to further use it on test images?import torch
import numpy as np
from torch import nn
from einops.layers.torch import Rearrange
import glob
import cv2
from torch.utils.d... | ptrblck | Yes, you should store it after the training is done.
Currently you are using a single epoch, so depending on your use case, you might want to train longer. |
Apogentus | Pytorch documentation provides aconcise wayto apply MiDaS monocular depth estimation network for depth extraction. But how should I modify their code to extract network representation at some intermediate layer? I know that I could download the model from github and modifyforwardfunction to return what I want, but I am... | ptrblck | You could indeed use forward hooks as describedhere. |
seer_mer | Can someone point out whichreliable sourcedoes the “mean = [0.485, 0.456, 0.406]” and “std = [0.229, 0.224, 0.225]” normalization for imagenet come from?After researching and reading some articles, whenever someone asks this, it seems like all articles I read are just referring to non-academic or unreliable sources lik... | ptrblck | You could check the stddev and variance of the resulting tensor and make sure it has a unit variance (=1), which is the purpose of this normalization/standardization step.
I’m not familiar with the TF implementation and don’t know what internally is used. |
thesekyi | class Baseline(nn.Module):
def __init__(self):
super().__init__()
# 5 Hidden Layer Network
self.fc1 = nn.Linear(28 * 28, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 128)
self.fc4 = nn.Linear(128, 64)
self.fc5 = nn.Linear(64, 3)
# Dro... | ptrblck | Based on the input shapes the in_features of the first linear layer should be set to 3*28*28=2352 and you would most likely want to flatten the input via:
def forward(self, x):
x = x.view(x.size(0), -1)
x = self.dropout(F.relu(self.fc1(x))) |
blueeagle | Hi everyone,I have a Model consisting of 3 parts. Part 1 is an encoder, part 2 and 3 are classifiers, that both get the output of the encoder (part 1) as input. I have two optimizers, the first has the parameters of part 1 and 2 (named optimizer12), the second only has the parameters of part 3 (optimizer3). I am calcul... | ptrblck | Yes, executing another forward pass should work. Another approach would be to compute the gradients for both losses and use optimizerX.step() afterwards, but it depends on your actual use case, if that’s possible.
Zeroing out the gradients of optimizer12 looks valid, but note that the forward pass … |
seyeeet | is there a pytorchic way (command/code) to know the memory that the model is taking on gpu instead of doing nvidia-smi? | ptrblck | Yes, you could use print(torch.cuda.memory_summary()). |
Z_Huang | Hi guys,I have created a neural network model with all the associated functions from scratch (basic Python code) into a class without using nn.Module. If I can still port this manually created model into GPU?I ported the train/test data into GPU, but don’t know how to port the model to GPU. It seems that I have to use ... | ptrblck | It depends what you define as a “model” now.
If you want to create nn.Modules, then yes you would have to use the nn namespace, as they are defined there. The same applies for nn.Parameters, but you could also create a tensor and set requires_grad=True. In this case, you wouldn’t use the nn namespa… |
AlphaBetaGamma96 | Hi everyone,I just have a general question. Let’s say I have a batch of matrices of shapematrices = [1000, 4, 8]and I have a batch of scalarsscalars = [1000], how can I divide the i-th matrix inmatriceswith the i-th scalar inscalars?I could see a potential way to usetorch.stackbut it’d be way too slow as I need the ope... | ptrblck | Yes, your approach should work fine and you could double check it with a defined examples, such as:
x = torch.arange(1, 5)[:, None, None].expand(-1, 4, 8).float()
y = torch.arange(1, 5).float()
xnew = x/y[:, None, None]
print(xnew) |
dhy | Hello,I am trying to implement my own model based on RoBERTa. My Python code looks like below.class My_RoBERTa(nn.Module):
def __init__(self, some_config, some_version):
super().__init__()
self.roberta = RobertaModel.from_pretrained(some_version)
def forward(self, input_ids, attn_masks, labels=N... | ptrblck | Are you using a data parallel approach (e.g. via nn.DataParallel or DistributedDataParallel)?
If so, then the output would be expected as the model is executed on each device. |
liuchangf | Hello There?I want to use 3rd party lib when define loss function , because pytorch can not fulfill all requirments for users ,pseudo code as following:from shapely.geometry import Polygon # 3rd party pacakage
p1=Polygon(polygon_from_model_inference)
p2=Polygon(polygon_ground_truth)
intersection_area=p1.intersection(... | ptrblck | Yes, it’s possible, but Autograd won’t be able to track these operations, so you would need to write the backward pass manually via a custom autograd.Function as describedhere. |
dgjung | Hi,I have a question about training in pytorch.There is a pseudo code that I wanna ask.model1 = Net()
model2 = copy.deepcopy(model1)
optimizer1 = torch.optim(model1.parameters(), lr)
optimizer2 = torch.optim(model2.parameters(), lr)
for i in range(dataset):
x = random(dataset[i])
y = dataset[i]
update_s... | ptrblck | Your code should work and both models as well as optimizers would be independent.
However, if you don’t have any randomness in the models and are also feeding the same data as well as target into them, the training might be equal (unless non-deterministic operations are used internally with an unde… |
yichong96 | I have noticed some discrepancy in object detection models when loaded in c++ vs python. I train the models in python before callingtorch.jit.script(model)and saving the scripted model.This is the script that I use to test the scripted model in pythonmodel = torch.jit.load("scripted_model_fasterrcnn.pt", map_location='... | ptrblck | I believe this line of code:
at::Tensor tensor_image = torch::from_blob(img.data, { 3, img.rows, img.cols}, at::kByte);
would interleave the tensor, since OpenCV would load the image in a channels-last memory layout, while you are loading it to a channels-first tensor_image, so you might need to l… |
DL_aspirant | I am running the official code for the pyramidal vision transformer on CIFAR-10.For a batchsize of 128, my test accuracy starts at 40%,but for a batch size of 4, my model starts at a test accuracy of 44-45%.Here’s a high level visualization of the PVT model for a quick understanding:image1759×406 70.6 KBI have attached... | ptrblck | Changing the validation batch size alone should not change the validation accuracy.
However, in your current code you are changing the training and validation batch sizes together, which is expected to potentially change the accuracy, since different training batch sizes would change the convergenc… |
WayneAng | for epoch in range(start_epoch, start_epoch + epochs):
print('\n\n\nEpoch: {}\n<Train>'.format(epoch))
net.train(True)
loss = 0
learning_rate = learning_rate * (0.5 ** (epoch // 4))
for param_group in optimizer.param_groups:
param_group["learning_rate"] = learning_rate
torch.set_grad_en... | ptrblck | As the error message suggests, you would have to push the tensor to the CPU first before converting it to a numpy array via tensor.cpu().
In particular np.array(targets.argmax(1)) seems to raise the error to use:
targets = targets.argmax(1).cpu().numpy()
instead.
PS: you can post code snippets b… |
blueeagle | Hi everyone,i implemented an architecture that handles multiple inputs, each being processed by its own encoder. In order to speed things up, I want to train my model on multiple gpus. This is my code:def forward(self, x):
''' x: list of input tensors '''
h = list()
for i, x_i in enumerate(x):
h_i =... | ptrblck | Yes, you can push each model to a specific GPU via self.encoders[i].to('cuda:{}'.format(i)) (where i would be the GPU id) as well as the input, transfer the outputs back, and concatenate the final output tensor. |
sakh251 | I have a loss function for a Model (model 1) which has a term calculating based on output of other model (model 2). So model 2 is not trained. I want to disable gard to get the output of model 2 faster. but I want to enable it for model 1.input = …output1 = model1(input)#disablegardoutput2 = model2(input)#enableagainl... | ptrblck | You could disable the gradient calculation via with torch.no_grad() as seen here:
model1 = nn.Linear(1, 1)
model2 = nn.Linear(1, 1)
input = torch.randn(1, 1)
target = torch.randn(1, 1)
criterion = nn.MSELoss()
function = criterion
output1 = model1(input)
with torch.no_grad():
output2 = model… |
students | Hello. I train one network and save it, then load this network and I partition network to three module and give one images to input of first module and take output from end module but the output of this three module has low resolution… I dont understand why this happened?!!model = ConvAutoencoder()
max_epochs =10
outp... | ptrblck | Based on the posted code I assume the left image represents the input while the right one the model output?
If that’s the case, I guess your model isn’t able to create sharp images and you could check the literature for new architectures, which could avoid the blurry output. |
FengZhiheng-coder | When I use torch_scatter, I get error as followed here.RuntimeError: Detected that PyTorch and torch_scatter were compiled with different CUDA versions. PyTocatter has CUDA version 10.1. Please reinstall the torch_scatter that matches your PyTorch install.My torch vision is torch==1.8.0+cu111 and torch-scatter’s is tor... | ptrblck | Since it’s the same error I assume pytorch-geometric still claims to be using CUDA10.1?
In that case, your install command wasn’t successful and you would have to uninstall the previous package and reinstall the new one. |
students | hello, I change output one layer and I want this change again feed to network (input this change to network). I write below code but no changes are applied to the network !!! please help me.model.conv3.register_forward_hook(get_activation('conv3'))
x, labels = next(iter(test_loader))
a = activation['conv3']
a[9,0,1,... | ptrblck | It seems you are still manipulating the activation after the forward pass finished, so you could take a look at this example to see how to manipulate them inside the hook:
model = nn.Sequential(
nn.Linear(1, 1),
nn.ReLU())
model[0].register_forward_hook(lambda m, input, output: output + 100… |
duddal | Hello,I am working with grayscale images. I want to use the Resnet 18 architecture. I don’t want to use the pre-trained model as I am planning to train it from scratch. However, my input_image size is (512, 1536) and I cannot resize or downsample it. I need to feed this as an input to the resnet18. Once the image (feat... | ptrblck | Yes, you can use any valid shape and it shouldn’t break anything. Powers of two are often friendly for memory access pattern etc. so you might see performance plateaus or cliffs.
Yes, same as 1.
I’m not deeply familiar with the package, but it seems thatmultiple inputs are supported. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.