user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
liuchangf
Hello There:Test code as following ,when the “loop” function return to “test” function , the GPU memory was still occupied by python , I found this issue by check “nvidia-smi -l 1” , what I expected is :Pytorch clear GPU memory when “loop” function return , so the GPU resource can be used by other programme.How to clea...
ptrblck
The remaining memory is used by the CUDA context (which you cannot delete unless you exit the script) as well as all other processes shown in nvidia-smi. You can add print(torch.cuda.memory_summary()) to the code before and after deleting the model and clearing the cache and would see no allocations…
Haewon_Lee
When I convert module output to tuple, I got an error like this.I can’t debug anything. How to debug libtorch? I’m using libtorch1.5.0(debug)image781×292 16.6 KB
ptrblck
Could you translate the error message, please?
Guest_Account
I’ve been trying to implement a version of an hourglass model but during training I keep running into this error:RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling backward the first time.I’ve read the othe...
ptrblck
I guess appending to self.skips and using it afterwards could create the issue. Could you re-initialize self.skips = [] inside the forward method for the sake of debugging and check, if this would be working?
danishnazir
Hi,I have two tensors of shape [12, 39,1024] and [12, 39,1024]. I want to concatenate them depth-wise but in a one-on-one fashion. For example, the first feature map of the first tensor is attached to the first feature map of the second tensor. So the sequence would be [(Feature map of 1st) Concatenated with (Feature m...
ptrblck
I’m not sure I understand the use case correctly and what “feature” maps refer to in this case, but this might work: a = torch.zeros(2, 3, 4) a[1] = 1. b = torch.ones(2, 3, 4) * 2 b[1] = 3 c = torch.cat((a, b), dim=1) print(c) > tensor([[[0., 0., 0., 0.], [0., 0., 0., 0.], […
han-yeol
I want to implement dataloader belowhow can I do this?research note-62244×2904 315 KB
ptrblck
Could you explain the use case a bit more, please? Would you like to randomly augment the sample/batch and concatenate these transformed versions to the current sample/batch? If so, I assume the batch size would be variable, since these transformations are applied randomly. In that case, I think …
Hyeonuk_Woo
Hi, I have a question about using multiple GPU devices.I set my model to use multiple device as below.os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2,3" model = model().to(device) model = nn.DataParallel(model.to(device)) (...) def train(): (....) for epoch in range(start_epoch, 10001): (....) ...
ptrblck
No, each device will get a batch containing 2 samples. DDP should be faster as it reduces the communication overhead in nn.DataParallel. The details of the latter (including the scatter/gather calls) are described inthis blog post.
Kaustubh_Kulkarni
No other transform is giving me an error but using the GaussianBlur transform gives me this error:File "/home/kaustubh/test/basic_augment.py", line 41, in <module> main() File "/home/kaustubh/test/basic_augment.py", line 34, in main transformed_image = data_transforms(image) File "/home/kaustubh/Envs/ml/lib...
ptrblck
This seems to be the PIL/Pillow issue as describedhere.
andrejankas
I am currently doing a module that initializes a Conv2d and BatchNorm2doutsidethe__init__. Code works fine in cpu, but when moving module to cuda theseconvandbnaren’t moved properly. Code:import torch import torch.nn as nn class ExpandChannels(nn.Module): def __init__(self, num_classes: int = None): super(...
ptrblck
You are creating the new self.conv and self.bn layers inside the forward pass without specifying the device, so they will be created on the CPU by default. To properly push them to the GPU, you could use: def reset_parameters(self, x): self.conv = nn.Conv2d(x.size(1), self.num_classes,…
sjasonw
I am encountering some particularly strange behavior with very simple usage ofnn.Linearwhen using CUDA. I wanted to post and see if others have encountered similar behavior. I’ve posted some information about my environment below the example.Example:I start with a trivialnn.Linearand aTensor, both on CUDA.import torch ...
ptrblck
Could you update to 1.9.0 and rerun the code, please? We’ve seen some issues in the pip wheels in 1.8.0 and 1.8.1 in particular for sm_61 by leaking cublas symbols, which might be also visible on the K80.
Hasan_Khan
I’m downloading my waveglow model using:torch.hub.load('nvidia/DeepLearningExamples:torchhub', 'nvidia_waveglow')but what if I want to directly download it locally on my pc or into the s3 bucket. What would be the procedure please help.
ptrblck
The code should be stored in the default cache directory, which can be changed via torch.hub.set_dir. Alternatively to changing the cache directory, you could also directly git clone the WaveGlow repository fromGitHub.
EasonC13
Hi, I’m working on an NER model with multi label on one word. So I chooseBCELossinstead ofCrossEntropyLoss.WhileCrossEntropyLosshaveignore_indexfeature, so it will ignore the part where attention_mask is 0.In BCELoss I only able to do it via manual filter unwanted part like the following code.loss_fct = torch.nn.BCELos...
ptrblck
Yes, indexing the model output and target should work and the gradient would be backpropagated to the selected values: output = torch.randn(10, 1, requires_grad=True) target = torch.randint(0, 2, (10, 1)).float() criterion = nn.BCEWithLogitsLoss() batch_idx = torch.tensor([1, 3, 5, 7]) loss = crit…
GMSL
I’ve tried thequickstart tutorialon two machines - one without a CUDA-compatible GPU running PyTorch 1.9.0-CPU, and the other with CUDA-compatible GPU running PyTorch 1.9.0+cu111. For the first one (with CPU), the tutorial works fine, however with the second one (with CUDA) it fails in the first section.I copied and pa...
ptrblck
The issue might be related to PIL==8.3.0 as describedhereand@tomalready provided a fixhere. If you are also using PIL==8.3.0, downgrade it to 8.2.0 for now. If that’s not the case, please let us know and we’ll take another look into your issue.
metro
Is it possible to forward a model on gpu but calculate the loss of the last layer on cpu?If so, how does pytorch know during backprop where the tensor is? Or is it expecting all tensors to lie consistently on one device?If it is possible, is there a documentation article or other resource which explains this process?Ba...
ptrblck
Yes, you can move around activations, as Autograd will track the to()/cpu()/cuda() operations. E.g.: # setup x_cuda = torch.randn(1, 1).to('cuda') lin_cuda = nn.Linear(1, 1).to('cuda') lin_cpu = nn.Linear(1, 1) # workload on the GPU out = lin_cuda(x_cuda) # transfer to CPU out_cpu = out.to('cpu')…
pain
def init_hidden(self, batch_size): ''' Initializes hidden state ''' # Create two new tensors with sizes n_layers x batch_size x n_hidden, # initialized to zero, for hidden state and cell state of LSTM weight = next(self.parameters()).data if (train_on_gpu): hidden = (weight.new(...
ptrblck
You are creating one tuple containing two tensors and are most likely passing them to the nn.LSTM module as h0 and c0 (hidden and cell state) as described in thedocs
pravin382
System information:PyTorch version: 1.5.1CUDA used to build PyTorch: 9.2OS: Ubuntu 18.04.5 LTS (x86_64)GCC version: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0Clang version: Could not collectCMake version: version 3.10.2Libc version: glibc-2.27Python version: 3.8.10 (default, Jun 4 2021, 15:09:15) [GCC 7.5.0] (64-bit runtime...
ptrblck
Since you are using an Ampere GPU (3070), you would need to use CUDA>=11.0, so the old PyTorch 1.5.1 release with CUDA9.2 won’t work. Update to the latest release with CUDA11.1 and it should work.
BarCodeReader
for example, I have a tensor in shape [N,C,H,W] = [1,3,2,2]Then I apply softmax and argmax to obtain the index:# original tensor tensor([[[[ 0.4008, -0.6662], [-0.4133, 1.3639]], [[-0.8354, 0.6317], [ 0.3240, -1.1438]], [[-0.3452, 1.2110], [ 0.6575, 0.9924]]]]) # a...
ptrblck
This should work: x = torch.tensor([[[[ 0.4008, -0.6662], [-0.4133, 1.3639]], [[-0.8354, 0.6317], [ 0.3240, -1.1438]], [[-0.3452, 1.2110], [ 0.6575, 0.9924]]]]) pred = torch.argmax(x, dim=1) pri…
ZhouShaoyang
Hi,LSTM model output different between pytorch1.6 & 1.8.Could anyone help me? Thanks!Ver 1.6Python 3.8.5 (default, May 27 2021, 13:30:53) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import torch >>> torch.__version__ **'1.6.0'** >>> torch.manual_seed(0) <torch._C.Gen...
ptrblck
In your code snippets you are not showing the internal parameters, so could you add: for name, param in lstm.named_parameters(): print(name, param)
thoger
HiI love the amazing Pytorch docs, but one issue we ran into is that they seem a bit sparse on the topic of how loss functions, specifically Cross Entropy, isimplemented(i.e. mathematically and/or the raw code).Does someone have an insight into where I would go about finding that?Context: We are implementing a custom l...
ptrblck
A manual (and slow) implementation can be foundhereand the CPU implementation calls intocross_entropy_lossand then intonll_loss.
cinna
I have a model where each input from a list of inputs gets processed by its own Embedding and the results are concatenated. The underlying Embedding objects don’t have to be consistent with each other in any way.I subclass my model from Transformer and store Embeddings in a list. But this list does not show up in trans...
ptrblck
I guess you might have been using plain Python lists or dicts to store the embedding layers. If that case, use nn.ModuleList/Dict instead, which will make sure to properly register these modules and push them to the desired devices via the to() operation on the parent model.
vuhoangminh
Dear All,At the end of an intermediate layer in the forward pass, I want to store a modified version of the output of this layer instead of the original one. Then in the backward pass, I would like to use the modified version to compute the gradient for the next layer. Let’s assume that the operation of that intermedia...
ptrblck
No, you would have to implement the backward method manually as shown in the linked example. E.g. for ReLU: @staticmethod def backward(ctx, grad_output): """ In the backward pass we receive a Tensor containing the gradient of the loss with respect to the output, and…
Pedro_Coelho
I’m working on a neural network that can expand in size from one iteration to the next according to changes in the inputs. While developing the training loop, I encountered a problem during back-propagation. I coded a minimal example that reproduces the problem:import torch from torch import nn l1 = nn.Linear(2, 1) x...
ptrblck
You are currently manipulating the .data attribute, which is not supported and can yield unwanted side effects such as probably this one. If you want to replace the .weight parameter of the linear layer, wrap the assignment in a with torch.no_grad() block and assign a new nn.Parameter to it.
John_Doe
Hello,I am doing a segmentation project with a Unet. I have an unbalanced dataset with 2 class and I want to apply, as a first step, a weight for each class. I use the losstorch.nn.BCELoss(). After looking on internet, it seems that people that had a similar problem were advised to switch toBCEWithLogitsLoss()which has...
ptrblck
I believe you should be able to manually weight the unreduced loss, if you are using binary targets. If that’s not the case, you would need to use nn.BCEWithLogitsLoss with the pos_weight argument.This issueexplains the use case a bit more and this code snippet shows the results: for i in range(1…
BjornSing
How does the architecture of deeplabv3_resnet50 look like?I am using this command to get the model:model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=False,progress=True,num_classes=21,aux_loss=None, **kwargs)I can then get some impression of how the model looks like just by printing model, but this ...
ptrblck
Printing out the model wouldn’t show the computation graph and would only print the child modules, so I agree that this would not be sufficient to “see” the structure. You could check out e.g.PyTorchVizto visualize the computation graph in case that’s helpful. PS: Often I also take a look at the…
S_dB
I need some help. Basically I want to get the normal output of the ResNet18 that I modified, but also the one from the nn.Linear(512,32) I am able to get the one before nn.Linear(512,32), but not the one coming out, so the one just before the nn.Linear(32,5). I need this to then use an LSTM with these extracted feature...
ptrblck
If I execute your code I get a shape mismatch error: RuntimeError: mat1 and mat2 shapes cannot be multiplied (1024x1 and 512x32) since you are not flattening the activation. This should work: class Resnet18(torch.nn.Module): def __init__(self): super(Resnet18, self).__init__() …
drbeethoven
Hello, I created the following somewhat succinct neural net (code cited later on):colab.research.google.comGoogle ColaboratoryNow the original version uses a simple two layer network, but I was trying to make a larger version using an input layer, a module list, then an output layer. However, it seems the “loss” functi...
ptrblck
The error is raised by nn.ModuleList, which doesn’t implement a forward method, but acts as a list with the additional property to register all parameters and buffers into the parent nn.Module. You could use another nn.Sequential container and .add_module instead: net = nn.Sequential( nn.Linea…
Alexander_Soare
I just need to confirm I’m not confusing myself. I’m used to momentum (in an exponential moving average) referring to the weight that is placed on historical values in the time series. Higher momentum means more weight is placed on what has happened, rather than what is happening now. In math-speak if we have a time se...
ptrblck
Yes, I think you are right and I also think the note mentions exactly this, doesn’t it? This momentum argument is different from […] the conventional notion of momentum.
deeriny
First, I found out that the A100 supports:cuda 11.0nvidia driver 450So, when using the A100, I adjusted the environment as follows.cuda 11.0cudnn 8005 (I checked bytorch.backends.cudnn.version())nvidia driver 450 (more detailed, 450.119.04)pytorch 1.8.0I installed pytorch using,pip install torch==1.8.0+cu111 torchvisio...
ptrblck
Your command should install the latest 1.9.0 release, which would ship with the missing cutlass kernels in cudnn8.0.5. However, you might still get a better performance by building from source with cudnn8.2 as said before.
durv
Hi,I have defined the weight parameters as follows but still these trainable parameters are not listed in the model.parameters().class Module(nn.Module): def __init__(input_dim, output_dim) #some variables def build(self): self.wt_dict = nn.ParameterDict() # self.wt_dict = {} for i in ...
ptrblck
Yes, plain Python “containers” such as list, dict etc. won’t (recursively) register the parameters and buffers, so you should use the PyTorch equivalents instead such as nn.ParameterList, nn.ModuleList, nn.ModuleDict etc.
Cuiqing_Li
Hi friends:I have a question. Suppose I have a model which contains batch norm layers. Then, due to some tasks’ requirements, I need to get the batch norm layers’ running_var and running_mean at the end of training or evaluation process.for example, here is a simple code:class Net(nn.Module): def __init__(self)...
ptrblck
You can directly access them via: my_net.bn.running_mean my_net.bn.running_var
mark_eu
Hi,I noticed that multiclass classification on the same dataset gives different results for each training of bidirectional LSTM. I am mostly concerned for weighted avg f1 and weighted avg recall in the classification report. I justre-runthe same Jupyter notebook and get a different result. For example, the first time I...
ptrblck
Setting the seed alone might not be sufficient to get deterministic results and you would have to disable all non-deterministic algorithms as described in theReproducibility docs.
yacinem
Hi everyone,I have a tensor stored in a file (initially it was a dataset stored in a matlab .mat file that I read using scipy and then stored as a tensor using torch.save). the data represents RGB images stored in a tensor of shape (N * C * H * W) where N = number of training examples/images, C = number of channels, H ...
ptrblck
Based onthis older postit seems that you could use a Storage to load the data in chunks. However, I don’t see an offset argument, so I guess the proper way would be to usenp.memmapand load chunks of a numpy array (assuming you could store it via numpy).
LQT
Hi, correct me if I’m wrong but I found that Dropout behaves similarly (correlated) across different GPUs when using DDP. In other word, cells at same position in tensor in different GPUs get all dropped out or not dropped out.I believe this (might) makes the training loss reduce slower than when using single GPU train...
ptrblck
I think this would be expected, since you are manually seeding the script, wouldn’t it?
Rohit_R
In my training script, I have a function‘train’that carries out the model training for a certain number of epochs and the training proceeds successfully. The loss gradually decreases and I obtain a decent validation set accuracy.Now, I wanted to train the same model 3 times. So I essentially created a‘for loop’that exe...
ptrblck
Based on the description it seems that your overall training is unstable and the success rate of the training could be low. You could retrain N models using different seeds for each run and check how many times the model converges properly vs. a failure. To stabilize it, you could try to use other p…
hadaev8
/opt/conda/lib/python3.7/site-packages/torch/_tensor.py:575: UserWarning: floor_divide is deprecated, and will be removed in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values. To keep the current behavior, use torch....
ptrblck
The warning is triggered by a division with could have been executed via torch.div or the div operator (a/b), so you could check the code for the usage of those. You could also try to convert warnings to errors via: import warnings warnings.filterwarnings("error") to hopefully get a better stackt…
ljeonjko
Hello!I’m using NASA’s Ocean color data, chlorophyll to be precise, and a single day of data looks like this:Basically, each pair of (lat,lon) has a single float value of chlor_a. There’s a whole bunch of daily data to be used.How would I go about feeding this type of .nc data directly into a DCGAN, without reverting t...
ptrblck
In that case I think you can just unsqueeze dim0 and dim1 as x should already contain the values to create the batch and channel dimension. This would create a tensor in the shape [1, 1, lat, lon] which would be an “image-like” tensor.
tlim
Hi all,I was wondering whether has anyone done bilinear interpolation resizing with PyTorch Tensor under CUDA?I tried this usingtorch.nn.functional.F.interpolate(rgb_image,(size,size))and it works to resize the RGB image tensor shape (batch,channel,size,size). However, the default mode is ‘nearest’ and when I change to...
ptrblck
Your output might be clipped to [0, 1], if you are trying to visualize floating point numbers or [0, 255] if you are using uint8. I cannot reproduce the issue using the latest stable releases and by making sure I’m casting to the expected type: img = PIL.Image.open('drums.png') img_arr = np.array(…
schaefertim
There seems to be a bug inAdaptiveAvgPool3don cuda.Can someone confirm this with a different computer/PyTorch version?The bug occurs when trying to computeautograd.gradofAdaptiveAvgPool3d. 1d and 2d works fine. Mytorch.__version__: ‘1.8.1+cu102’To reproduce you can run the following code:import torch from torch import ...
ptrblck
Thank you very much for the code snippet as well as the additional test using 1.9.0. I can reproduce the issue on other devices as well and have created anissueto track and fix it.
Ahmed11
Hello,I am new to PyTorch, I just want to ensure that I correctly understand howmodel.to(device=device)works before I start creating more complex models.So far, almost all the tutorials that Ive followed create, train and evaluate their models in the same notebook/script.However, what if I am creating my model, trainin...
ptrblck
Yes, your assumption should be correct as also seen inthis post, since the model reference would be passed and its parameters (and buffers) updated inplace. You could use the code snippet in the linked post to verify it using your setup.
avalon1511
Hi, I have created a dataloader object from a subsetted dataset as:target_index = np.random.choice(len(target_dataset), k_samp, replace= True) target_dataset = torch.utils.data.Subset(target_dataset, target_index) target_loader = torch.utils.data.DataLoader(target_dataset, batch_size=batch_size, ...
ptrblck
ImageFolder will return a data and target tensor. You are currently assigning both return values to data in the DataLoader loop. If you want to use both objects as tensors, you could either use two return variables via: for i, (data, target) in enumerate(target_loader, 0): or unwrap them inside th…
guru
I encountered this error while i was trying train the model on my local gpuHere :Machine-Learning-Collection/ML/Pytorch/object_detection/YOLO/This is the test script that i have used to test the yolo-v1 modelimport torch import torch import torch.nn as nn from torch.utils.data import DataLoader import torchvision.tra...
ptrblck
Calling model.half() can easily create under/overflows, which could explain the NaN values in the forward/backward pass, which is why we recommend using torch.cuda.amp for mixed-precision training. Are you seeing the first cudnn error using amp? If so, could you post a minimal, executable code sni…
Florentino
I know how to print out the model bytorchsummary.summary(),So I want to know is there any way to save the text into a txt file that I don’t know how to save it? Thank you
ptrblck
Assuming you are usingthis method from torchsummaryyou could call: result, params_info = summary_string( model, input_size, batch_size, device, dtypes) and save the result into a file instead of printing it out.
nikhil6041
I am trying to use a dataset having nearly 5200 classes of images and total images to be somewhere around 14000, now some of these classes have only image per class i want to use only those images which have atleast say 3 or more images per class , one way could be by iterating over the entire directory and copying the...
ptrblck
You would have to map these indices to [0, nb_classes-1] as described in the previous post. EDIT: here is a code snippet in case you get stuck: target = torch.randint(3, 6, (10,)) print(target) > tensor([3, 4, 3, 3, 3, 5, 5, 4, 3, 4]) unique = torch.unique(target) for i, u in enumerate(unique): …
dfalbel
I wonder ifregister_parameteris expected to work withScriptdModules, for example:import torch module = torch.jit.trace(torch.nn.Linear(10, 10), torch.randn(100, 10)) module.register_parameter("new_parameter", torch.nn.Parameter(torch.randn(10, 10)))AttributeError: cannot assign parameter before Module.init() callI don’...
ptrblck
I don’t think this would be a supported use case, since the already traced model won’t have a chance to use the newly registered parameter afterwards. In the case that this parameter is indeed used in the forward (but not registered yet), tracing would raise an error due to the usage of undefined p…
hosseinshn
Hi,I am building an autoencoder like this:class autoencoder(torch.nn.Module): def __init__(self): super(autoencoder, self).__init__() self.encoder = torch.nn.Sequential( torch.nn.Linear(dim_input, h_dim1), torch.nn.ReLU(), torch.nn.Dropout(), torch.nn....
ptrblck
Sure, here is a simple example of using F.linear with a weight parameter: class MyModel(nn.Module): def __init__(self): super().__init__() self.weight = nn.Parameter(torch.randn(4, 10)) def forward(self, x): print(x.shape) x = F.linear(x, self.weight…
AlphaBetaGamma96
Hi All,I was wondering if it’s possible to jit a network whose output depends on a flag? For example, I have a neural network that has an internal flagself.use_det. The network is represented as ann.Modulewhoseforwardmethod comprises of a fewnn.Linearlayers that eventually produce a batch of matrices in the shape[B,N,N...
ptrblck
Yes, it should work as long as you don’t change the output type. In your case you could return an empty tensor in the if path as seen here: class MyModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(1, 10) self.fc2 = nn.Linear(1, 2) sel…
CHENSY
How can one optimize only part of a Dataparallel model, while perserving the data-parallel behaviour in an appropriate way.For example:parallel_model = DataParallel(model) optimizer = torch.optim.SGD(parallel_model.last_conv_layer.parameter(),lr=0.01)error: torch.nn.modules.module.ModuleAttributeError: 'DataParallel' ...
ptrblck
Yes, accessing the underlying layers via the .module attribute will work. You could alternatively create the optimizer before wrapping the model into nn.DataParalllel.
FreddyJ
I am working on multiple instance learning, and the first two steps before attempting to cluster images from a group are training a network (in this case a pre-trained DenseNet, of which I unfreeze the last few layers) on the images and then saving the encoded representation of these images. The issue is, despite catch...
ptrblck
No, the forward hook won’t terminate the execution and you could store the intermediate output in e.g. a list or dict as seenhere.
Surayuth_Pintawong
For example,x = torch.rand(1, 3, 7, 7) m = torch.nn.AdaptiveAvgPool2d(output_size=1) y = m(x) # y.shape = (1, 3, 1, 1)Is it possible to obtain x via y?
ptrblck
You won’t be able to calculate the input values of the mean calculation. However, if you are more concerned about the shapes (not the exact values) you could use e.g. nn.ConvTranspose2d.
MJChoi
I got this error while trying to test CNN model.I already checked type about this error point’variable.Here is error point10. imgs = imgs.to(device)#imgstype <class ‘torch.Tensor’>—> 11 labels = labels.to(device)#labelstype <class ‘torch.Tensor’>AttributeError: ‘tuple’ object has no attribute ‘to’Both are ...
ptrblck
Based on the output it seems that the working iterations are creating the label initially as a str and in the conditions are replacing it with an int: print("data_path label",type(label)) #label type : str if label.startswith("Black"): label=0 elif label.startswi…
majid
Hi everyone,I have data with size N that is separated into M chunks (N >> M). The data is too big to fit into RAM entirely. As we don’t have random access to data, I was looking for an implementation of a chunk Dataset that inherits IterableDataset which supports multiple workers. I didn’t find anything so I tried to i...
ptrblck
Thanks for sharing this implementation! I think you could start with a feature request onGitHuband explain your use case as well as your implementation. Currently you are using 3rd party modules such as pandas, which I assume could be removed to allow for a more general use case. Once the featur…
talhaanwarch
I want to create torch code for transform image using numpy. I am not sure whether I am doing it correctly?Here is pytorch codetransform=torchvision.transforms.Compose([ torchvision.transforms.Resize((224, 224)), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize([0.5820, 0.4512, 0.4023], [0.2217, 0.18...
ptrblck
Yes, I think you could use moveaxis as it’s giving the same results here: arr = np.random.randn(224, 224, 3) x = torch.from_numpy(arr).permute(2, 0, 1) arr_new = np.moveaxis(arr, 2, 0) print((x.numpy() == arr_new).all()) > True Your normalization is wrong, since you would need to subtract the mea…
Zhihan_Yang
I’m planning on using this repoGitHub - asappresearch/sru: Training RNNs as Fast as CNNs (https://arxiv.org/abs/1709.02755), which contains a RNN variant that’s fast to train. I followed the installation, which was very simple, but got the following error:/home/hnguyen/sru/sru/cuda_functional.py:23: UserWarning: Just-i...
ptrblck
The--generate-dependencies-with-compileargument was added in CUDA10.2, if I’m not mistaken, so you might need to update your local CUDA toolkit.
11179
image875×440 6.7 KBHello, I have some problems changing pretrained models (in my case Yolov5).Model is built by selections of modules and numbers of repetition.I want to change modules like above, trying to mask specific spatial regions of input features per image inference.However, I don’t know how to change all modul...
ptrblck
You could iterate the modules of the parent nn.Module, check for the mask attribute via hasattr and assign e.g. a new nn.Parameter to it as seen here: class MyModule(nn.Module): def __init__(self): super().__init__() self.mask = None class MyModel(nn.Module): def _…
tetelevm
I need to train YOLOv5 on my data and then use it in a program. I trained it from atutorialon their github:# download .zip from github cd /yolo/yolov5/ !python train.py --batch 10 --epochs 40 --data ./data.yaml --cfg ./models/yolov5m.yaml --weights '' --name yolo_m --nosave --cacheI replaced the parameters in training...
ptrblck
Usually this type of error is raised if you have some skip connections in the model (or anything similar where you are concatenating activations) and are using an “unsupported” spatial shape for the input. “Unsupported” means that the model wasn’t designed to work with any arbitrary shape, but ofte…
SimlaBurcu
Hello,I have been trying to implement a custom Conv2d module where grad_input (dx) and grad_weight (dw) are calculated by using different grad_output (dy) values. I implemented this by extending torch.autograd as in Pytorch tutorials.However I am confused by the informationin this link.Is extending the autograd.Functio...
ptrblck
You don’t need to write the C++ extensions and your current custom autograd.Function should work. Implementing the custom methods in C++ could yield a speedup as shown in the tutorial.
Bhavya_Soni
I got this error after updating torch and torchvision :- Torch not compiled with CUDA enabled.Before this I was able to train model on GPU.Current version of torch(after updating) is 1.9.0+cpu.After searching on internet I updated my Cuda 11.0 to 11.3 and GTX1050ti driver version 451.82 to 466.77.It’s not working still...
ptrblck
You can just install the NVIDIA driver, select a desired PyTorch binary using the posted link, and install it. E.g. conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch will install PyTorch with the CUDA 10.2 runtime (as well as cudnn7.6.5).
Flock1
I am working with VAE and I don’t know why but during the training process, I am getting the output of VAE as well as that of the encoder asnan. I am reading a CSV file with rows as my data. Here’s my code:My data loader:class data_gen(torch.utils.data.Dataset): def __init__(self, files): self.data...
ptrblck
I guess you might encounter specific data arrays with constant values, so that amin and amax would return the same value and divide by 0: data = np.array([0.1, 0.1]) print(np.amin(data) == np.amax(data)) > True 1 / (np.amin(data) - np.amax(data)) > inf
Haozhi
If I have several large intermediate variable in the optimization loop, can I allocate them outside the loop to avoid to generate them every iteration? I encountered RuntimeError when trying to do so and I found anexplanation. Is there a correct way to allocate intermediate variable?var1 = torch.rand(128, 128, requires...
ptrblck
Here is an example: var1 = torch.rand(128, 128, requires_grad=True) m1 = var1.new_empty((4, *var1.shape)) # intermediate variable a = torch.linspace(1, 10, 4).reshape(4, 1, 1) data = torch.randn(128, 128) for i in range(10): m1.detach_() m1[:] = torch.exp(var1[None, :] ** 2) l = (m1 - …
marcpaga
Hi all,I am trying to reshape and duplicate a tensor based on a window that is applied to one of theHere is a code example:x = torch.rand([1, 10, 60, 256]) # [batch, subsamples, timepoints, channels] window_size = 3 st = torch.arange(0, x.shape[1] - window_size + 1, 1) nd = st + window_size t_list = list() for s, n i...
ptrblck
You could use tensor.unfold for it: out = x.unfold(1, window_size, 1) out = out.squeeze(0).permute(0, 3, 1, 2) print(out.shape) # torch.Size([8, 3, 60, 256]) print((out == new_x).all()) # tensor(True)
oasjd7
How to empty_cache by passing gpu-tensor as a parameter to a function?In this case, It works! x = torch.tensor([1., 2.]).cuda() print(torch.cuda.memory_allocated()) # 512 del x print(torch.cuda.memory_allocated()) # 0x = torch.tensor([1., 2.]).cuda() print(torch.cuda.memory_allocated()) # 512 cleaner(x) print(torch....
ptrblck
The cleaner method will delete the x variable from the local scope, not the global one. To remove the global x, you could use the global keyword: x = torch.tensor([1., 2.]).cuda() print(torch.cuda.memory_allocated()) # 512 del x print(torch.cuda.memory_allocated()) # 0 def cleaner(): global…
Hyeonuk_Woo
Hi I’m new to pytorch.If I doloss.backwardfor every 0.1% of my training set and dooptimizer.stepfor every 1% of my training set, what could be the problem?Due to characteristic of my training data, I write my code as belowBATCH_SIZE = parameter from user for epoch in range(1,10001): i=0 (..........) fo...
ptrblck
Based on your description I understand that you are calling optimizer.step() more often (1 out of 100 steps) and calculate the gradients only 1 out of 1000 steps. In this case, the general problem could be that the optimizer updates the parameters with “old” gradients, which might not work. To cha…
JohnPolo
I am following theFinetuning Instance Segmentationtutorial with my own data.I am at the point in the tutorial where the model istrained for 10 epochs. All the code up to this point seems to work. When I run this section, the results are mixed. Once, it ran for one epoch and then gave an error. Then I tried it again and...
ptrblck
This error is raised, if the index tensor has a single dimension only while you are indexing it at dim1: boxes = torch.randn(4) out = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) > IndexError: too many indices for tensor of dimension 1 boxes = torch.randn(1, 4) out = (boxes[:, 3] - bo…
aleemsidra
I am trying to see the images being loaded in the data loader. I used PIL in a custom loader to load the images. However, when I am using the following code to display images, I face the error:images, labels = next(iter(test_loader)) plt.imshow( images )------------------------------------------------------------------...
ptrblck
matplotlib,pyplot.imshow expects a numpy array in a valid image shape (e.g. [height, width, channels] or [height, width]), while you are passing tensors in the shape [batch_size, channels, height, width] to it. You would thus have to index each image (via image = images[0]) and permute the axes to …
Dark
Hi there,I am planning on using the Batch Norm layer between the two other layers of my model. After training the model I am not sure how to 'un’normalize the output when I want to receive the predicted values?If it would be simply normalization on some values - I would just calculate and save the variance and mean, th...
ptrblck
The model.train() and model.eval() calls will switch between the training mode (normalizing the input batch with its own stats and updating the running stats) and evaluation mode (normalizing the input batch/sample with the running stats). You don’t need to apply the running stats manually.
thomas
Hello,I am in a situation were I initialize and train a model using some datasets. I then save the model state dict. I would like to be able to load the model without having to load the data again. However because of the dimensions mismatch when I callload_state_dictI don’t seem to be able to do that.example :class Mod...
ptrblck
In your code snippet you are loading the state_dict into model, while I assume you want to load it into model_loaded, which will raise a RuntimeError, since no x buffer was registered: import torch from typing import Optional class Model(torch.nn.Module): def __init__(self,x: Optional[list] =…
TheOraware
Hi ,I am training NN using pytorch 1.7.0 , when i use CrossEntopyLoss() loss function then i dont have any negative loss in any epochs, since this competition evaluation metrics is multi-class logarithmic loss which i believe BCEWithLogitsLoss() in pytorch serve this logarithmic loss for multi class (correct me if i am...
ptrblck
You shouldn’t use a softmax on the model outputs when you want to calculate the loss using nn.CrossEntropyLoss, since (as you’ve already said) nn.CrossEntropyLoss applies F.log_softmax and nn.NLLLoss internally, so pass the raw logits to this loss function instead. On the other hand, you can apply …
morphism
Hello, everyone.In every source file implementing attentions and transformers,I’ve found there is no backward function inside the class of TransformerI wonder why there is no backward method in the class of Transformer ?Also, how to backpropagate the Transformer?In pytorch, will pytorch engine backpropagate the encoder...
ptrblck
Autograd will use the backward methods of each submodule used in thenn.Transformer.forward methodto calculate the gradients so the nn.Transformer module doesn’t necessarily need to implement a custom backward method. You could check these submodules and see, how the backward methods are defined (…
astra1234567
Hello! I have problem with my code:import numpy as np import os import torch from torch.utils.data import Dataset, DataLoader import torchvision.models as models import torchvision as trv import torch.nn as nn from sklearn.model_selection import train_test_split import torch.optim as optim import argparse class Custo...
ptrblck
I’m unsure how the kernel size is related to the input shape of the batchnorm layer. However, if the input contains only a single value for each channel (as is the case here), you won’t be able to use batchnorm layers in training mode, since they need to calculate the stats from the input. Since i…
auzuha
Hello ,The parameter shuffle in DataLoader class seems to affect the model in some way.I have a saved model for a binary classification task (cats vs dogs) and changing the parameter shuffle in DataLoader affects my model heavily.I have used torch.save method to save my trained model , and I used torch.load method to l...
ptrblck
This would be expected, since calling model.eval() would disable dropout layers (shouldn’t make a difference regarding shuffling the dataset) and would use the running stats of all batchnorm layers. If you leave the model in training mode, the batchnorm layers would use the current batch stats to …
manix
Error :RuntimeError: Given groups=1, weight of size [16, 128, 1, 1], expected input[32, 64, 126, 126] to have 128 channels, but got 64 channels insteadThe above images are the errors that i got while trying to run a SqueezeNet model , i have tried various means to solve but no idea where it has gone wrong , i have take...
ptrblck
The error is raised by a conv layer, which is expecting 128 input channels and returns 16 output channels. Did you modify the model in any way and if so, could you post the applied changes? The torchvision implementation work fine for me: model = models.squeezenet1_0() x = torch.randn(1, 3, 224, …
phantom90
Hi There,Just curious is there there a way to manually allocate a gradient for an Adam step?
ptrblck
You could use hooks to manipulate the gradients for each parameter (its .grad attribute), backward hooks, or if needed you could also create a custom Adam implementation by reusing the PyTorchimplementation.
Caipi
Hello there,I have programmed a multiclass segmentation model, everything works fine. My output for the tests is a tensor shaped 668x388x388 thus the output contains 668 different classes. So my goal is to get a tensor (or numpy array) out of this shaped like 1x388x388 to give it to matplotlib.imshow and thus I provide...
ptrblck
To create the predictions containing the class index associated with the highest probability (or logit) you could use: preds = torch.argmax(output, dim=0) # assuming output has the mentioned shape [nb_classes, height, weight]
Abhishek_Minhas
the exact error isVariable._execution_engine.run_backward( RuntimeError: element 0 of tensors does not require grad and does not have a grad_fnits a simple fully connected nn with reinforce algorithm on a cpu. So the loss is simply the mean of q_value * log_probability of all the actions in one batch.I think the prob...
ptrblck
Your code isn’t executable and raises an error at: loss = -q_vals*batch_log_probs TypeError: only integer tensors of a single element can be converted to an index After adding: batch_log_probs = torch.stack(batch_log_probs) before the problematic operation and fixing loss/mean() to loss.mea…
hyuntae
I want to update the classifier’s weights twice with the two outputs of the classifier.To update, I wrote a code.But, the code gives me the error that’ enable anomaly detection to find the operation that failed to compute its gradient,’I saw the answer that this code works with the previous version of pytorch. But it s...
ptrblck
That wouldn’t be a fix, as it’s still using the wrong behavior. Previous PyTorch versions allowed this wrong gradient calculations, which is why no errors were raised.
abhibha1807
Hello,I am trying to implement a ‘one step gradient descent’ aproach wherein I accumulate the loss for the whole dataset, sum it, and then do a backpropagation. I have set my batch size to 8. The issue that I am facing is that after a few forward passes I obtain an OOM error. I think it is because pytorch is saving the...
ptrblck
Yes, Autograd will save the computation graphs, if you sum the losses (or store the references to those graphs in any other way) until a backward operation is performed. To accumulate gradients you could take a look atthis post, which explains different approaches and their computation as well as …
treadstone
To debug my code I need to get name of images in my batch with its labels and prediction. As images in batch are in form of tensor, So I can not acess image name.In my dataloader below part of code is used-defgetitem(self, i):data, label = self.data[i], self.label[i]#heredata is actual file name of imageimage = self.tr...
ptrblck
No, this should work: data, _, file_name = batch data = data.cuda() assuming batch contains 3 objects.
seyeeet
Can someone explain to me what do we mean by buffers in pytorch.what is its characteristics and when we will use that and when we should not use that?If a buffer is basically the same as tensor, Why would I even need a buffer when I can simply create my tensor inside the module?an example would be appreciated!!thanks
ptrblck
Buffers are tensors, which are registered in the module and will thus be inside the state_dict. These tensors do not require gradients and are thus not registered as parameters. This is useful e.g. to track the mean and std in batchnorm layers etc. which should be stored and loaded using the state…
hanoody
I have a UNET segmentation model with 5 classes and I am having trouble trying to save the image predictions.Here is the code:def save_predictions_as_imgs( loader, model, folder="saved_images/", device="cuda" ): model.eval() for idx, (x, y) in enumerate(loader): x = x.to(device=device) with ...
ptrblck
You won’t be able to save it directly as an image, if it’s not a valid format. In case you want to store the output directly, you could use torch.save. On the other hand, you might want to store the predictions for each class as a color-coded image. In that case, you could get the predicted class …
hydra
I implemented the resnet18 variant of the network by myself, and defined the’forward’ function in the network. My model can be trained on the computer normally, but when I save the model according to the method written in the pytorch Android tutorial, I got the error “Method’forward’ is not defined.”. I want to know wh...
ptrblck
Thanks for the code snippet. I cannot reproduce the issue using a source build with: torch.__version__ '1.9.0a0+git6d45d7a' torchvision.__version__ '0.11.0a0+882e11d' and the optimization step doesn’t raise an error, so you might want to update to the latest nightly binary (or build from source)…
Luesch
hello,In the past few days i tried to rebuild an autograd engine in the style of pytorch.All of the computed gradients do actually match pytorch’s gradients so it should all be fine.Now i decided to build a little nn library ontop of my autograd engine to train some small networks.So my problem is that due to operatio...
ptrblck
No, PyTorch doesn’t scale the gradients (unless you are using mixed-precision training with the GradScaler, but in any case the gradients would be unscaled before the update, so you can skip this side note) and you could take a look at the SGD implementationhereandhereto check this implementatio…
markcheung
Hi, I have encountered a problem that relates to the time consumption of the indexing operation.I have a tensor which is ‘output:[B,C,H,W]’ and I use unfold to transform it like ‘out_patch:[B,C,H//N,W//N,N,N]’. N is the patch size.And there is a binary mask tensor ‘mask:[B,C,H//N,W//N]’ so that I can select patches fro...
ptrblck
Yes, the nonzero would need some time to be executed, but you are right that your profiling is wrong as it accumulates the model forward time into the nonzero operation, so it looks as if the nonzero op is more expensive than it is. As mentioned before, this operation is synchronizing, so should be…
UCDuan
Hi all,I’m new tolr_schedulerand I get different results fromget_lrandget_last_lr. What’s the true learning rate? And why do they generate different results?Thanks.
ptrblck
I think you should rely on calling get_last_lr, since using get_lr outside of theinternal manipulation of the learning ratewould yield awarning.
Doha_Bouallal
Hi there, i want to train deeplabV3 on my own Dataset with 4 channels images. but i didn’t find any PyTorch implementation of deeplabV3 where i could change parameters and input channels number of the model to fit my (4channels) images .How can i modify deeplabV3 to adapt it to my dataset?
ptrblck
torchvision provides deeplabv3 implementationshereand you could manipulate the first conv layer as seen here: model = models.segmentation.deeplabv3_resnet50(pretrained=False, progress=True, num_classes=21, aux_loss=None) x = torch.randn(2, 3, 224, 224) out = model(x) model.backbone.conv1 = nn.C…
SungmanHong
I have batch x 4096 x 6(time samples) data in nn.I want to nn.Relu, so I want to reduce the data dimension tobatch x 512 x 6(time samples)but the nn.Relu layer take the last dimension, if I understand correct.How can I do a Relu, in the wanted dimension…?
ptrblck
The nn.ReLU layer won’t apply any reduction to the data, but would apply the relu activation on each element as seen here: batch_size = 2 x = torch.randn(batch_size, 4096, 6) relu = nn.ReLU() out = relu(x) print(out.shape) > torch.Size([2, 4096, 6]) Depending on what dim1 represents you could redu…
TheOraware
When pytorch builtin optimizer loss.backward() could calculate gradient and it is proven correct in its calculation , even though why we need to check derivative computation? Whats wrong in my following code to check derivative computation in back propagation? Or we check gradient computation when we implement gradient...
ptrblck
This tutorialexplains how to write custom autograd.Fucntions. If you are “just using” built-in PyTorch methods, you are most likely not interested in testing utilities. Yes, since PyTorch is an open source framework with a lot of active developers, things can accidentally break, which is why tes…
zihaog
Hi,I’m trying to do the inference on cpu with torchvision.models.mobilenet_v2If I load a pretrained mobilenet_v2, get rid of some layers of it and retrain, the inference time is very slow when I use my new weights. Here is the code:device = "cpu" parameters = "xxx.pth" model = models.mobilenet_v2(pretrained=False) mode...
ptrblck
Depending on your CPU you might be able to use torch.set_flush_denormal(True) to avoid a slower code path for denormal values (if that’s causing the slowdown, which could be the case based on your description).
djams
Does Pytorch have an equivalent implementation to Tensorflow’stf.signal.frame  |  TensorFlow Core v2.5.0? I’ve been searching everywhere and cannot seem to find anything, even in torchaudio. I know that librosa has an equivalent function, but it requires that the inputs be converted to numpy arrays first
ptrblck
Based on the description I guess thattensor.unfoldwould perform the same operation (with an additional F.pad before if needed).
ADONAI_TZEVAOT
I have integer numbers in ascending order from 1 to n with a difference of 1 like this :1,2,3,4,…, n . I want to get ordered permutation of the desired length of m. for example if n is 3 and m is 2 then the output should be (1,2),(2,3),(1,3).
ptrblck
I guess you could use itertools.permutations to permute your list. PS: this doesn’t seem to be PyTorch-specific, so note that you might get a faster and better answer e.g. on StackOverflow.
aysuda
Hi.I have 3-dimensional input tensor with size (1,128, 100) when the agent selects the action and (batch_size, 128, 100) when the agent trains. The input is a sequence of words that tokenized and get vector for every token from Word2Vec model and concatenate to a tensor. So 128 is the number of tokens and 100 is W2V ve...
ptrblck
nn.Conv2d layers expect a 4-dimensional input tensor in the shape [batch_size, channels, height, width]. Based on your error and description I guess the channel dimension is missing, so you could add it via x = x.unsqueeze(1) before passing the tensor to the model.
Haozhi
The following code causes a RuntimeError ’ unsupported operation: more than one element of the written-to tensor refers to a single memory location. Please clone() the tensor before performing the operation’. Could anyone help me?import torch kx = torch.linspace(-64, 63, 128) kY0, kX0 = torch.meshgrid(kx, kx) kX0 *= 0....
ptrblck
kY0 and kX0 are expanded tensors and as the error message suggest, you could need to clone them before applying inplace operations. Did you try to use the suggested operation? kx = torch.linspace(-64, 63, 128) kY0, kX0 = torch.meshgrid(kx, kx) kX0 = kX0.contiguous() kX0 *= 0.001 kY0 = kY0.clone() …
Kunpeng_GUO
Hi,I try to build a neural network based on BertModel with the implementation from huggingface/transformers.I basically take the bert-base-uncased model for contextual representation and another pretrained embedding layer for token-level representation. And do some operations in the network. I.E. Matrix multiplication ...
ptrblck
Are you sure the gradients are zeros everywhere in the embedding weight parameter? Note that only the selected weight “rows” will get a valid gradient, so depending on the way you’ve check it (e.g. by printing the .grad attribute only) it could look as if it’s all zeros. Here is a small example to…
bkuriach
What is the key difference betweentorch.dist.distributedparallelandhorovod?If my understanding is correct, torch.dist.distributedparallel work on single node with one or more GPUs (it does not distribute workloads across GPUs across more than one node) whereas horovod can work with multi-node multi-gpu.If my understand...
ptrblck
As given in theDDP docs, DistributedDataParallel is able to use multiple machines:DistributedDataParallel(DDP) implements data parallelism at the module level which can run across multiple machines. Applications using DDP should spawn multiple processes and create a single DDP instance per proc…
Florentino
When I save the same value torch tensor or ndarray, save_image() from torchvision and save() from matplotlib respectively give me different image visualization, I know they both do some normalization method but can’t tell the detail algorithms they use.Does anyone know which causes the difference? Thanks
ptrblck
I think it depends on the tensor/array you are passing to these methods and what its values would mean. A normalization is often applied, if you provide data in a “non-image” format. E.g. floating point values in the range [-1, 1] wouldn’t directly represent pixel data (color values) and would thu…
Arthur_Zakirov
Hello everyone,what is a valid way to construct a Hierarchical NN Architecture of subcomponents.The goal is accomplish something like this:class FeedForwardLayer( nn.Module ): def __init__(self): super().__init__() self.lin = nn.Linear( ... ) self.bn = nn.BatchNorm1d( ... ) se...
ptrblck
Your code looks alright, so I’m unsure if you are seeing any issues with it or just would like to have some feedback?
banikr
What is the difference between epoch and iterations?In this 3D multi-class segmentationpaperin section3 Experiments & Resultsthe authors mention“…Training of 20,000 iterations.”Does it mean they ran 20,000 subvolume patches?
ptrblck
An epoch usually refers to using the entire dataset once, while an iteration usually refers to a training step using a batch. In case you know the batch size and number of sample in the Dataset, you could transform “Training of 20,000 iterations” into epochs.
Dazitu616
I try to use rescalingweightintorch.nn.functional.cross_entropy, and find the result very hard to understand. Here is the code:>>> import torch >>> import torch.nn.functional as F >>> pred = torch.tensor([[[0.8054, 0.6918], [0.8704, 0.1927], [0.4033, 0.3574], [0.6289, 0.2227], [0.042...
ptrblck
nn.CrossEntropyLoss normalizes with the used weights, so you would have to change the loss2 calculation to: loss2 = F.cross_entropy(pred, label, reduction='none', weight=weight).sum() / weight[label].sum() loss2 > tensor(1.5594)This postalso describes it using another example.
Doha_Bouallal
i have images with 4-channels that i created by stacking RGB and thermal data. as follow:i1= Image.open('rgb.png') #rgb image i2 = Image.open('th.png') #thermal image img = np.dstack((i1,i2))I am working with pytorch to train a model on these images and at some point I have to process them separately. So I ...
ptrblck
Assuming you are permuting the tensor to the channels-first memory layout and it contains a batch dimension, your code looks correct. A quick check would be: i1 = np.zeros((24, 24, 3)) i2 = np.ones((24, 24, 4)) img = np.dstack((i1, i2)) print(img.shape) > (24, 24, 7) image = torch.from_numpy(img) …
eduardo4jesus
Are the tensor saved for backward as below freed or deleted automatically after the backward pass?ctx.save_for_backward(input, weight, bias)I am trying to get around memory used problems.
ptrblck
Yes, these tensors should be freed after the backward(). To double check it, you could usethis exampleand add some print statements to check the memory: for t in range(5): # To apply our Function, we use Function.apply method. We alias this as 'relu'. relu = MyReLU.apply # Forward p…
avish
Hi, I have a ModuleDictionary where each module take similar size input, x.I have two use cases for it:For a single input x run all module in dictionary and create tensor by stacking all outputs.Give a ordered map of {key, x} run each x to module in dictionary for that key and stack the outputs in that order. I can cha...
ptrblck
I think iterating the dict would be the right approach. If you are concerned about the performance of this loop, you could use a dict comprehension, which could yield a speedup, but I would recommend to profile the code first and check, if this loop is indeed the bottleneck in your code.
Abdelrahman_Akram
I want to make a loss module with trainable parameter, so I made the following:class CostumLoss(torch.nn.Module): def __init__(self): super().__init__() self.gamma = torch.nn.Parameter(torch.FloatTensor([.5])) def forward(self, od_loss, depth_loss): print(self.gamma) loss = od_l...
ptrblck
The trainable parameters will be updated by the optimizer, once gradients were calculated in the backward() pass and optimizer.step() was called. In your current code snippet you are printing the value of self.gamma before and after using it in the forward, so it’s expected that these values weren’…