user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Xanthan
Hello people, I’m fairly new to pytorch and I’m stuck with a problem.I want to input an image into the generator of a DCGAN instead of a noise vector (the reason for this I have mentioned below). You may takethistutorial notebook of pytorch dcgan as your reference to work.As you can see that the generator accepts an in...
ptrblck
Your use case sounds similar to the pix2pix models so you could check some implementations and reuse the logic for the generator.
Jingnan_Jia
I knowtorch.save(net.state_dict(), model_path)can only save the weights, andtorch.save(net, model_path)can save the weightsandthe structure of the network.I know ·torch.load(model_path)· can load the pretrained model.I knownet.load_state_dict(torch.load(model_path))can map the pretrained weights to the current net.But ...
ptrblck
This is currently not possible and will not directly save the structure of the model, but would still depend on the source files (and could thus break in various ways). You could check the experimentaltorch.packageutility, which might fit your use case, but note that it’s experimental and you m…
PersonalFinance004
I built PyTorch from source because I want to contribute to the library. Unfortunately, I can’t runpython test/run_test.pywithout getting errors. I rebuilt three times inside different Anaconda environments with Python versions 3.7, 3.8 and 3.9, but there are always some errors being thrown, not necessarily the same be...
ptrblck
Yes, you should take a look at related tests and could run them only via the -k flag. E.g. if you are working on an torch.nn fix, the test could be located in test_nn.py and you could filter it out via: python test_nn.py -v -k my_test_name You could use grep -r my_test_name to find the related fi…
rahulvigneswaran
Currently am fixing the all seeds by doing the following,random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = FalseI want to train multiple models of the same architecture t...
ptrblck
Setting the seed at the beginning of the script would make the pseudorandom number generator output deterministic “random” values. Creating multiple models in the same script would thus also create different parameters, since the sequence of the random number generation is defined by the seed, but t…
AnhMinhTran
After training a model using a timm library and get a model, I wrote my own script to classify 1 picture. However, it took 7 seconds to classify 1 224x224 image. I thought I had used GPU to predict but it Ross mentioned that I was still using CPU to calculate gradient descent, thats why it took so long.Isnt tensor.cuda...
ptrblck
You would have to reassign the tensor when calling the to() operator: if torch.cuda.is_available(): img_tensor = img_tensor.cuda() Also, you need to call cuda() or to('cuda') on the model as well. Note that Variables are deprecated since PyTorch 0.4, so you can use tensors in newer ve…
lithuak
Hi!I’ve contributed some small Python fixes/additions to PyTorch and now I’m trying to start with a deeper layer of C++ core.To do that I’m trying to run my C++ experimental code linked with PyTorch built from sources with debug info enabled. And I got somewhat stuck with getting it built.My configuration is as followi...
ptrblck
I assume you’ve build PyTorch in the ~/pytorch folder and installed it via pip or conda? In that case, could you try to use: cmake -DCMAKE_PREFIX_PATH=`python -c 'import torch;print(torch.utils.cmake_prefix_path)'` instead of the absolute path to the downloaded libtorch? The small Python inline …
coincheung
Hi,I used torch.cuda.amp.scaler to train my model with mixed precision mode. Part of my code is like this:eps = 1e-8 mag = 0.1 im.requires_grad_(True) optim.zero_grad() with amp.autocast(enabled=args.use_fp16): logits, *logits_aux = net(im) loss_pre = criteria_pre...
ptrblck
You can manually unscale the gradients as shown in theGradient penaltysection of the amp examples: inv_scale = 1./scaler.get_scale() grad_params = [p * inv_scale for p in scaled_grad_params]
ziad
I’m trying to use PyTorch’s Resnet18 model with my image data. Given the complexity of the model as well as the size of the data, I’d like to run it using CUDA. I’m doing the follow:resnet_cnn = models.resnet18(pretrained = True) num_ftrs = resnet_cnn.fc.in_features resnet_cnn.fc = nn.Linear(num_ftrs, 8) criterion = n...
ptrblck
Could you rerun the code via: CUDA_LAUNCH_BLOCKING=1 python script.pt args and post the complete stack trace here, please?
Florentino
I have a .pth model as title says, how can I input a latent vector in the the model and show a correspond images?Thanks
ptrblck
Assuming the *.pth file contains the state_dict of the model, you would need to create an instance of the model and load the state_dict afterwards. Once this is done, you can pass an input tensor to the model to get the output: model = ProGAN() state_dict = torch.load('PATH_TO_STATE_DICT/file.pth')…
sftwre
I am performing transfer learning on a pre-trained version of MobileNet V2. I want to freeze alllayers of the model except for BatchNorm2d modules. I am currently handling this with the following loop:for module in model.modules(): if not isinstance(module, nn.modules.BatchNorm2d): module.requires_g...
ptrblck
If I’m not mistaken, the recursive loop would enable the gradient computation for all nested BatchNorm2d layers even in the custom modules, as they would be reached last. You could verify it manually after using this approach via e.g.: print(model.custom_layer.bn_layer.weight.requires_grad)
nicaushaz
Hello,I am trying to extract 2048-element representations of fMNIST from a pre-trained resnet50. I need to store these vectors, presumably in a [60000,2048] data structure(currently trying tensors) in order to use them in subsequent experiments. My workflow is as below:Load fMNIST from torchvisionCreate dataloadersLoop...
ptrblck
Based on the description it seems that you are storing tensors in e.g. a list, which are still attached to the computation graph. Thus you wouldn’t only store the tensors, but the entire graph with all intermediate tensors in each iteration. If you don’t need to call backward() on the stored tensor…
CaramelCougar
I am doing a final project for a class and I need to do a proof of concept for an idea we have. Implementing the whole idea is out of scope for the course but something we need to do for the proof of concept is to be able to use different feature maps in the backward pass than the forward pass. Right now I only care ab...
ptrblck
You can define a custom autograd.Function as describedhereand use it in a custom nn.Module by falling it inside the forward method of the module.
zcajiayin
Suppose I have a tensorA = [row, col], for example:tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]])Now, the values in some of rows ofAwill be modified to value 0.I have a index tensorBspecifying which column the value should be modified and a‘indicator’te...
ptrblck
This code should work: x = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]]) C = torch.tensor([[1], [0], [1]]).squeeze(1).nonzero().squeeze(1) B = torch.tensor([[1], [7]]).squeeze(1) x[C, B] = 0 print(x) Note …
HitsujiAura
Hello,I was passing some mel arguments into the torchaudio.transforms.MFCC function but it doesn’t seem to recognize the argument “center”. Center is a parameter to the Mel Spectorgram so I don’t understand why it’s not working.Code:melkwargs = { "center": False, "n_fft": n_fft, "hop_length": hop_length, ...
ptrblck
You might need to update torchaudio to 0.8.0, as the center argument doesn’t seem to be available in previous versions.
Sam_Lerman
Say I have two DNN modulesFandG.out = F(G(x_1), x_2)And a loss function likeloss(out, label).I want to disable gradients forFduring one particular update (though not necessarily in others).I tried this during that update:g = G(x_1) with torch.no_grad(): out = F(g, x_2)But (correct me if I’m wrong), it seems gradient...
ptrblck
Your code won’t work and will raise: RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn if you try to call backward() on out or an output of any successive operation on it, since it was calculated in the no_grad block: G = nn.Linear(1, 1) F = nn.Linear(1, 1) x = …
MANISH_GOYAL
I recently switched from windows to ubuntu. I installed miniconda here, created a virtual environment with python 3.8.5, activated that environment and ran “conda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorch”. I ran torch.cuda.is_available() and it says True, but when I run which CUDA/Cuda/cuda or...
ptrblck
The PyTorch conda binaries and pip wheels ship with the specified CUDA (cudnn, NCCL) runtimes, not with a complete CUDA toolkit. To run PyTorch you would thus not need a local installation of these libraries and could use the binaries directly. However, if you want to build PyTorch from source, an…
jorgerodpen
I’m trying to build a multilayer perceptron for sentiment classification. I am using skorch for cross validating and to integrate a pipeline that performs the hashing trick. I want to optimise the number of features in the hashing trick and therefore the input dimension is going to change every time I change that value...
ptrblck
I don’t think it would make a difference, but you could pass the expected input tensor to the __init__ method and get the feature dimension via input_dim = x.size(1) assuming the features are in dim1. Alternatively, you could also reuse your code and use model = MLP(x.size(1), ...) instead.
DKilkenny
Hello,I have been trying to go through all of the loss functions in PyTorch and build them from scratch to gain a better understanding of them and I’ve run into what is either an issue with my recreation, or an issue with PyTorch’s implementation.According to Pytorch’s documentation forSmoothL1Lossit simply states that...
ptrblck
The third argument to smooth_l1_loss is the size_average, so you would have to specify this argument via beta=1e-2 and beta=0.0, which will then give the same loss output as the initial custom code: y_pred=torch.tensor(1.0) y_true=torch.tensor(1.12) loss1=smooth_l1_loss(y_pred, y_true, beta=1e-2, …
_joker
Hello Everyone, I am looking to perform transfer learning by freezing the entire weights of the model and only fine-tuning the last layer of the model. Perhaps, I am not able to map the tutorial instructions by Pytorch on Resnet18 with the Retinaface architecture.The forward function of Retinaface looks like this;def f...
ptrblck
The in_features used in the tutorial represent the number of input features to the last linear layer. Based on your code snippet it seems that the last activations are calculated in: bbox_regressions = torch.cat([self.BboxHead[i](feature) for i, feature in enumerate(features)], dim=1) …
mkserge
Hello,I am running a docker container based on official pytorch/pytorch:1.7.1-cuda11.0-cudnn8-runtime,I am also using onnxruntime-gpu package to serve the models from the container. However onnxruntime fails withFile "/home/mrc/.local/lib/python3.8/site-packages/onnxruntime/__init__.py", line 24, in <module> from o...
ptrblck
No, PyTorch uses the official cudnn release and either links it dynamically or statically. Note that you are using the runtime container, so nvcc isn’t installed either: root@f79b17da2a55:/workspace# nvcc --version bash: nvcc: command not found Also, the lib path is also empty: root@f79b17da2a5…
cpeters
I’ve been trying to convert the vgg16 model trained onthe places365 datasetfrom caffe to pytorch, and eventually triedMMdnn, which successfully read the caffe files, converted them to intermediate representations, and then to python code. However, when it tries to do the last step (load the model and weights together a...
ptrblck
Removing the additional dimensions should work as shown in this code snippet: conv = nn.Conv2d(3, 64, 3, 1, 1) bias = conv.bias.clone() conv.state_dict()['bias'].copy_(bias) # works conv.state_dict()['bias'].copy_(bias[None, None, None, :]) > RuntimeError: output with shape [64] doesn't match the …
andrejankas
I would like to save anin-memorycheckpoint, so to resume training. My question is: Am I saving everything necessary to later continue training with the following code? Also, is it necessary to save the loss?DEVICE = 'cuda' def train(model, optimizer, loss, train_loader, test_loader, epochs): best_model, best_optim...
ptrblck
I think your code won’t work, since the copied optimizer2 will lose its reference to the new copy of model and thus won’t update it anymore. You would thus have to recreate a new optimizer with model2's parameter references and load its state_dict as shown here: def train(model, optimizer, loss, d…
davidlee
Hi,I have my own data with the following dimensions for super resolution tasks.(Batch, channels, 128, 128, 128).ex) predict = (2, 1, 128, 128, 128) / output = (2, 1, 128, 128, 128)torch.nn.MSELoss() or torch.nn.L1Loss() can be directly applied in this voxel case?for instance,criterion = torch.nn.MSELoss() pred = torch....
ptrblck
You can directly apply both mentioned losses, as they would expect the model output and target to have the same shape, which is the case for your use case. Unfortunately, I not sure how SSIM can be used for your use case, but if I’m not mistaken the original implementation uses 2D convs internally,…
Eric_K
When I don’t need a network to update their parameters, I will not put this network’s paramters into optimizer’s parameter argument. And when I run forward,I will warp “with torch.no_grad():” for my “model(input)”.Are there some wrongs in my operations?Thanks…
ptrblck
They might yield the same result, but in specific edge cases you might get different and unexpected results: An optimizer, which doesn’t hold certain parameters, won’t update them. However other optimizers could still update these parameters, if they are passed. If you are using weight decay, have…
jS5t3r
I want to get the feature maps of each input image from each layer after an activation function. The underlying model is ResNet50 (pytorch-cifar100/resnet.py at master · weiaicunzai/pytorch-cifar100 · GitHub)In contrast, the VGG Net (pytorch-cifar100/vgg.py at master · weiaicunzai/pytorch-cifar100 · GitHub) has aself.f...
ptrblck
I usually use forward hooks as describedhere, which can store the intermediate activations. You could then pass these activations to further processing.
Alexander_Koch
I have noticed that torch doesn’t throw an error that a variable was modified by an inplace operation when autocast is turned on. Why is that? And would my example with autocast work as expected?Here is a simple example without autocast. This throws a Runtime error:RuntimeError: one of the variables needed for gradient...
ptrblck
autocast could apply the transformations to FP16 tensors internally and would thus work on a clone of the data (in another data type) and would save you from the error. Generally, if Autocast isn’t raising an error, your operations should work fine.
TSDK
I know this topic has been covered in the past. But I just wanted to make sure that if it is the correct way of what I’m doing. From my understanding of previous post on this:→ Label should be torch.long() type–>We should pass the indicies of the labelfor batch_num, data in enumerate(trainloader, 0): # get the...
ptrblck
In case you are using nn.CrossEntropyLoss or nn.NLLLoss, then yes: the targets are expected as LongTensors containing the class indices in the range [0, nb_classes-1].
Stapo
My data is financial time-series where the stationarity properties of the train set will always be slightly different from the test set. I’m using an LSTM model that uses batch normalization on the final linear layers (LSTM → dropout → batch norm → linear → relu …). I noticed that my test results were way better once I...
ptrblck
I think your understanding is correct and it often comes to the question how this model would be deployed into a real-world use case. I.e. I assume you won’t have future data points when the model is deployed, so you also shouldn’t use it during validation. That sounds reasonable. Alternatively…
Mona_Jalal
What is the reason for this error and how can I fix it? I am running the code from this repo:GitHub - facebookresearch/frankmocap: A Strong and Easy-to-use Single View 3D Hand+Body Pose Estimator(frank) mona@goku:~/research/code/frankmocap$ python -m demo.demo_frankmocap --input_path ./sample_data/han_short.mp4 --out_d...
ptrblck
These issues are sometimes caused by a “dirty” build folder. Could you clean it via python setup.py clean and rebuild the extension? (Assuming you are building the extension manually)
tueboesen
My code requires the autograd to be on even during eval mode, since I need the gradient information of my output with regards to one of my input variables. However this accumulates gradient information somehow when using eval mode. (In training mode this is not a problem, since it also calls loss.backward() and optimiz...
ptrblck
torch.autograd.grad should remove all intermediate tensors after its operation, if retain_graph is not set to True (in the same way tensor.backward() operates).
spacemeerkat
Hi all!I’m wonderingis it possible to perform convolutions during the training of neural networks in which a convolution kernel is detached from the gradient tree.An example would be the autoencoder shown below:image1272×410 8.25 KBIn the example above, a convolution of the reconstructed image (exiting the decoder CNN ...
ptrblck
Yes, that’s possible. You could either use the functional API with a kernel specified as a plain tensor (not an nn.Parameter): kernel = torch.randn(...) out = F.conv2d(input, kernel, ...) or set the requires_grad attribute of the weight (and bias) in the conv layer to False.
Shyam_Gupta196
I just started to practice PyTorchin the train loop if I add the.round()the acc is decreased to 30% in the testing loop .whereas when i remove the.round()i get acc more than 90% or something like that .why is this happening I am not able to understandCheck out the Main train loop where i am facing issues:for i in range...
ptrblck
The round operation will yield a zero gradient almost everywhere as described inthis postwith a potential workaround.
aman26kbm
PyTorch doesn’t create a static graph representation of a neural network. So, we can not iterate through the network’s layers once it is created (and query or print them). Is it possible to get the information about the network structure at runtime? Alternatively, is there a static mode that we can run PyTorch in?Here’...
ptrblck
Scripted or traced model provide a representation of the model, which you could probably use for your experiments. Have you checked the created code from a scripted model and would it be useful in your use case?
user12233
I’m trying to create a LSTM model that will perform binary classification on a custom dataset. The dataset is a CSV file of about 5,000 records. The features are field 0-16 and the 17th field is the label. I’d like the model to be two layers deep with 128 LSTM cells in each layer. Below is the code that I’m trying ...
ptrblck
Could you check the shape of x before feeding it into the self.lstm? Based on the error it might only have two dimensions, while three are expected ([batch_size, seq_len, nb_features] in your case, since you are using batch_first=True).
oasjd7
[Input -> Encoder -> Classifier -> Classifier2]def freeze(...) # defined to freeze the network def unfreeze(...) # defined to unfreeze the network # in train-loop: freeze(encoder) unfreeze(classifier) enc_out = encoder(input) class_out = classifier(enc_out) class_loss = ce(class_out, target) # -> tr...
ptrblck
enc_out would also get gradients, if you pass its output to classifier2 directly and call backward() on the calculated loss. To avoid it, you should detach the tensor: class_out2 = classifier2(enc_out.detach())
Thabang_Lukhetho
I’m trying to build a next frame generation model which behaves in the following manner"During training, the model expects both the input tensors, as well as targets and will return a dict containing the classification and regression losses:loss_dict = model(images, targets)During evaluation, the model requires only th...
ptrblck
Each nn.Module uses the internal self.training flag, which is changed by calling model.train() and model.eval(), and can be used as a condition to use different behaviors inside the module.
light1003
I make a lstm step by step,but I found it not same with the offical one.I got a different results,only input one line data and init with the same params,simple such as:# official import torch import torch.nn as nn import torch.nn.functional as F torch.manual_seed(20) lstm_official = torch.nn.LSTM(6, 2, bidirectional...
ptrblck
I think you are mixing up in_transform and forget_gate. This code should work and I’ve also added my manual implementation, which basically just reuses the formulas from the docs: # nn.LSTM torch.manual_seed(20) lstm_official = torch.nn.LSTM(6, 2, bidirectional=False, num_layers=1, batch_first=Fal…
jerly-hjzhou
import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torchvision import datasets, models, transforms import time import copy def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() best_model_wts = copy.deepcopy(model.stat...
ptrblck
The transforms.Compose transformations wrap the transformations in a nested list, while only a single list is expected. Remove one list ([]) and it should work.
Saguaro
Hello,I have a problem that I cannot understand: even though a module ‘torch_geometric.transforms’ has an attribute ‘AddTrainValTestMask’ according todocumentation, I cannot import it. I keep receiving an errorAttributeError: module 'torch_geometric.transforms' has no attribute 'AddTrainValTestMaskMy Pytorch version is...
ptrblck
Maybe your torch_geometric version is too old. Note that this library is not shipped in the PyTorch installation, but is installed separately, so you would have to check its version.
thomas
Hello,I saw today onthisrepository the practice of puttingoptimizeranddeviceinside the model:import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np class GenericNetwork(nn.Module): def __init__(self, alpha, input_dims, fc1_dims, fc2_dims, ...
ptrblck
I personally don’t use this workflow, as I don’t think that an optimizer is necessarily bound to a model. Of course your use case might use a single model and optimizer and thus this workflow will certainly work for your use case, but it’s “cleaner” to me to use them as separate objects. One poten…
shrutishrestha
Suppose we initialized batchnorm:bn1=nn.BatchNorm2d(64,track_running_stats=False)Can we use this bn1 after every convolution layer that outputs 64 channels?or do we need to do:bn1=nn.BatchNorm2d(64,track_running_stats=False)bn2=nn.BatchNorm2d(64,track_running_stats=False)for using after 2 conv layers with 64 layers out...
ptrblck
You could reuse the same batchnorm layer, but this would indeed reuse the same affine parameters as well as update the running stats with each input, so it’s most likely not what you want. The standard approach would be to create a new batchnorm layer.
songyuc
Hi, guys,I have heard that it would be better to set batch size as a integer power of 2 fortorch.utils.data.DataLoader, and I want to assure whether that is true.Any answer or idea will be appreciated!
ptrblck
Powers of two could be preferred in all dimensions, so number of channels, spatial size etc. However, as described before, internally padding could be used, so that you wouldn’t hit a performance cliff and should thus profile your workloads.
shakasaki
I’ve installed torch on a small server that is to be used by ~10 people. I have a separate user set up where I’m installing all packages for all users using conda. I’ve installed pytorch there, in a virtual environment called pytorch-env.It all works fine when I log on the first time and import torchconda activate pyto...
ptrblck
PyTorch tries to import dataclass from the dataclasses Python library inthis line of code. However, based on the stack trace, it seems that you are also using a Python script called dataclasses.py in your working environment: File "/home/alexisshakas/git/deeplogger/dataclasses.py", line 2, in <mo…
zanussbaum
Hi all,Few questions. First, we want to compute some metrics during training and after each epoch, take the 10% and only apply augmentation to those examples from the dataset. If we have a custom dataset, is it best to subclass the DataLoader class on top of a Dataset class? What’s the best way to be able to change whi...
ptrblck
You could use an internal attribute in your custom Dataset to tag the samples, which should be augmented, and use it in the __getitem__ as a condition. At the beginning you could leave it empty and manipulate it after each epoch via directly accessing the internal dataset through the DataLoader. Th…
twister9458
Hello all;Could you help me creating an equivalent layer of Keras Dense (128,7,7), hence outputting a 3D (128,7,7) layer ? thank you very much.I’ve temptednn.Linear(in_features=100, out_features=(128,7,7), bias=True), but I don’t know if this is correct.I’m working on DCGAN, and my input z is of 100 size.Thank you very...
ptrblck
In your code snippet, 128*7*7 is interpreted as 6272. The way to write the input shape as a multiplication makes instead of the result directly makes it easier to understand the shape. E.g. when this linear layer is preceded by conv layers, you would flatten the conv activation, so that it’ll have…
sangheonlee
Hi,I was running GNMTv2 using pytorch. But I just want to check the 1 iteration time(Forward ~ Optimize). Now If data was loaded, It automatically grabs the size of dataset and it runs many times.I want to know how can I change the dataset size.Thanks for reading this.
ptrblck
The length of a Dataset is defined in it’s __len__() method and you could override it with a custom method returning your desired length or alternatively implement a new custom Dataset with the desired length.
scheon
HelloI’ve been trying to build a custom channel-wise convolution operation with multiplication and sum operation so that I can alter the bit-precision during the convolution process.(I’ve checked several forum articles and all of them told me I should build it with unfold and fold functions.)But when I replace the torc...
ptrblck
Did you compare the forward and backward implementation to the PyTorch implementations and did you see any issues? The forward could be checked by calculating the abs().max() error of the outputs, whiletorch.autograd.gradcheckmight be helpful to check the backward implementation.
Taha_Iftikhar
Hello ,I am having a problem using my own re-trained inception_v3 for real-time inference.First off I have a question. When saving my model after training, is it enough to just save it’s state dictionary withtorch.save(model.state_dict(), ‘model.pth’)or do I also have to save the model with it and then the state dictio...
ptrblck
Yes, saving the state_dict is sufficient to restore the model for your deployment use case. The error message seems to be raised by OpenCV and I don’t know which method is raising it. Are you able to read frames from your cam object using OpenCV?
tcsn_wty
I think I totally understood the tutorial on using the following line of code to do data parallel.model = nn.DataParallel(model)I tested it on my device with 2 GPUs and it worked. However, for a complicated model I recently wrote, it doesn’t truly train on both GPUs when I printed the ‘Inside’ ‘Outside’ debugging messa...
ptrblck
The issue with your code is that you are removing the nn.DataParallel wrapper by calling: model = model.module # For multi-gpu so remove this line of code. After removing it, you would also have to change how the optimizers are created, as you need to either access the internal layers via model.…
turian
LSTMandGRUdocs have the following notes:“If the following conditions are satisfied: 1) cudnn is enabled, 2) input data is on the GPU 3) input data has dtypetorch.float164) V100 GPU is used, 5) input data is not inPackedSequenceformat persistent algorithm can be selected to improve performance.”What is persistent algori...
ptrblck
You cannot select it manually and it will automatically be used, if the specified conditions are met.This GTC talkgives some information on persistent kernels, which basically try to avoid memory “movement” and try to reuse values once they are loaded.
marvosyntactical
I am implementing[2010.02803] A Transformer-based Framework for Multivariate Time Series Representation Learning, a BERT-like model. I wrote my own model+boilerplate, and am using a masked MSE loss for a reconstruction task (fully reconstruct partially masked input):class MaskedMSE(nn.Module): def __init__(self, *a...
ptrblck
I’m not sure, if registering a backward hook in the modules would be triggered before the gradients are accumulated, so the zero gradients might be expected. Could you check the .grad attributes of all parameters directly via: for param in model.parameters(): param.register_hook(lambda grad: p…
JustAGuysInThailand
I have a dataset in the size of [88,498,20] which represent 88 samples with the length of 498, each Time-steps will be represent by 20 classes.My output is [88,498,3] so it’s the same as input only different is now I only have 3 classes to predict.So this is my first time with Pytorch. With Keras, I just simply create ...
ptrblck
nn.CrossEntropyLoss expects raw logits, so you should remove the self.softmax from the forward method. Assuming your current model output represents: [batch_size=88, seq_len=498, nb_classes=3], you would have to permute the output so that it has the shape [batch_size, nb_classes, seq_len] via outpu…
Kallinteris-Andreas
My Module:struct Net : torch::nn::Module { Net(int numIn, int numOut, int numHid, const size_t hid_count=1) { assert(hid_count > 0); first = register_parameter("inputW", torch::rand({numIn, numHid}))/numHid; middle = new torch::Tensor[hid_count]; h_c = hid_count; for (int i = 1; i != hid_count; i++) middl...
ptrblck
You are initializing all parameters and the inputs with torch::rand, which will sample values from a uniform distribution on the interval [0, 1) and will thus yield only positive numbers. Increasing the layer size will thus easily saturate the activation and thus yield these saturated values. Use …
sunder
The below code is causing 100% CPU usage.There’s no GPU.import random from queue import Queue from threading import Thread import torch from torchvision.models import resnet18 import numpy as np from sklearn.metrics.pairwise import cosine_similarity model = resnet18(pretrained=True) model.fc = torch.nn.Identity() #l...
ptrblck
You are not using the GPU, so a high CPU workload is expected.This tutorialexplains how to use the GPU by pushing the model as well as the tensors to the device.
Jhone
File “/home/ali/BioNet_project/pytorch_version/utils.py”, line 90, in trainsoft_score = soft_loss(y, x, beta=0.95)File “/home/ali/BioNet_project/pytorch_version/metrics.py”, line 23, in soft_losscross_entropy = F.nll_loss(y_pred.log(), y_true, size_average=False)AttributeError: ‘numpy.ndarray’ object has no attribute ‘...
ptrblck
Remove the .numpy() operations and pass the tensors to the soft_loss function. As described before, you won’t be able to call backward() on the loss and calculate gradients with it, since you are also explicitly detaching the tensors, but I assume that’s wanted.
HaydenW
I have been working on using a ResNet-50 and have images of shape (3, 256, 256) and I’m trying to run it in batch size of 96, but I keep getting an error stating that it ran out of CUDA memory. I have a 3090 so I find that hard to believe since it has 24GB. So I then tested a very simple structure with this code, which...
ptrblck
A memory usage of ~10GB would be expected for a ResNet50 with the specified input shape. Note that the input itself, all parameters, and especially the intermediate forward activations will use device memory. While the former two might be small the intermediates (which are needed for the gradient …
ammary-mo
I have the same problem reported in the postDifferent batches take different times to load. I am using 3 workers Dataloading workers for loading images from a local folder. And as you can see below, it seems to me that one worker is constantly having a slower time than the other two.The accepted answer suggests using S...
ptrblck
Yes, it seems that the data loading time is large compared to the actual model training time, which would explain the peaks in the data loading time. There might be a potential improvement, if replacing: torch.tensor(self.datasets[index][1], dtype=torch.long) which will trigger a copy with: to…
Augustin
HelloI am currently experiencing an issue during a training, where NaN values appears in every forward pass.Here is a minimal code that reproduces the error:import torch from torch import nn class Net(nn.Sequential): def __init__(self): super(Net, self).__init__( nn.Conv1d(513, 512, kernel_si...
ptrblck
I cannot reproduce the issue on a Pascal GPU using your code snippet. Could you install the CUDA10.2 binaries and rerun the code?
Sayak_Paul
Hi.I am currently trying to figure out how to facilitate mixed-precision training when using transfer learning.Typically, here’s how I am building my custom model using a pre-trained base model:# load up the ResNet50 model model = models.resnet50(pretrained=True) # append a new classification top to our feature extrac...
ptrblck
Since you are working with a ResNet, have a look atits forward. As you can see, there is unfortunately no model.features attribute, so in this case it would be easier to replace model.classifier = nn.Identity() and just call the model directly.
TANKUN_LI
Hi, I am using pytorch to train a GAN.When I just used one GPU, training speed is 0.55 sec/batch with batch size = 8.However, once I used 2 GPUs (nn.DataParallel()), the speed became 1.4 sec/batch with batch size = 16 (batch size 8 in each GPU). Also when I used 4 GPU with batch size = 32 (batch size 8 each GPU), speed...
ptrblck
This might be the case, as you would have to scatter and gather the results for each model. A quick check would be to wrap all models in an nn.Sequential container and pass this to nn.DataParallel. We generally recommend to use DistributedDataParallel with a single process per device, as it would…
Anand_Krish
I came across this quirky thing when playing around with sparse tensors where, a sparse tensor takes lot more memory than a corresponding dense tensor.Example Codeimport torch from pytorch_memlab import MemReporter DEVICE = 'cuda:0' n = 1000 c = .6 t1 = torch.randn(100, n, n).to(DEVICE) t1[torch.rand_like(t1) > c] ...
ptrblck
I think the memory footprint is expected as describedhere. For your sparsity, this would be the memory usage: DEVICE = 'cuda:0' n = 100 c = .6 t1 = torch.randn(100, n, n).to('cuda') t1[torch.rand_like(t1) > c] = 0 t2 = t1.to_sparse() print((t2.indices().nelement() * 8 + t2.values().nelement() …
seankala
Hi. This might sound like a bit of a strange question, but I’m wondering if there’s any way that I can simply skip over samples that cause the device-side assert triggered error.There are a few samples within my dataset that cause that error, and I’m wondering if I have to find the error and debug it or reformulate the...
ptrblck
You shouldn’t disable device assert errors, as they are pointing towards critical errors in your code. E.g. you might run into an illegal memory access (the PyTorch device assert statements should trigger the assertion before hitting the memory violation), which might corrupt your data in all imagi…
Sandeep_Menon
I am using the following Class to implement Tiling as in Caffeclass Tiling(nn.Module): # Tiling layer from orginal caffe-VPGNet def __init__(self, x_dim, tile_dim): super(Tiling, self).__init__() self.b, d, self.h, self.w = x_dim self.tile_dim = tile_dim self.out_d = int(d / (til...
ptrblck
I cannot reproduce the mentioned error using: class Tiling(nn.Module): # Tiling layer from original caffe-VPGNet def __init__(self, x_dim, tile_dim): super(Tiling, self).__init__() self.b, d, self.h, self.w = x_dim self.tile_dim = tile_dim self.out_d = int(d …
otterspace
Hi PyTorch community,I am designing a network with a custom layer, in which I am using a third-party framework that requires numpy arrays. Since my layer was not behaving as expected, I tried to find the problem by drastically simplifying it.At this point I am simply echoing the input to my layer back into the network,...
ptrblck
If you are returning None gradients, you would detach the computation graph at this point and all preceding layers wouldn’t get any gradients, which could explain the issues you are seeing. In case you want to write a “no-op” numpy layer, you could pass on the gradients to the preceding layer.
wall4nce
Hi!I am the new one in python and pytorch. I am trying, to make a CNN on pytorch, which will be able to learn on my own dataset, but getting too much errors every time. I’ve made CNN with MNIST dataset, but i can’t make it with my own.The error isRuntimeError: shape ‘[10, 400]’ is invalid for input of size 595360. Can ...
ptrblck
The error is raised, since the flattened activation output contains more number of features than the first linear layer (self.fc1) expects. This line of code: x = x.view(x.size(0), 16*5*5) creates a tensor in the shape [batch_size, 16*5*5=400], while (based on the error message) it contains 595360 …
hohohihi
I am studying the nvidia torch matmul function.### variable creation a = torch.randn(size=(1,128,3),dtype=torch.float32).to(cuda) b = torch.randn(size=(1,3,32),dtype=torch.float32).to(cuda) ### execution c = torch.matmul(a,b)I profiled this code using pyprof and this gives me the result below.image1691×211 15 KBI cann...
ptrblck
As you’ve already partly exaplained: volta: GPU architecture s = accumulator type: single precision in this case gemm: kernel type: matrix multiplication in this case 128: number of elements per CTA in M dimension of the C matrix 32: number of elements per CTA in N dimension of the C matrix nn: st…
anu
I am trying to calculate the validation loss along with the training set loss while training a simple VAE network. But, I am receiving a CUDA error as follows:<ipython-input-27-5638e9c724e6> in unSupTrain(epoch) 22 recon_batch, mu, sigma = model(data) 23 # Get valloss value ---> 24 ...
ptrblck
Could you rerun the code via: CUDA_LAUNCH_BLOCKING=1 python script.py args and post the complete stack trace here? Alternatively, you could also run the script on the CPU, which might yield a better error message.
Mona_Jalal
I am not sure why sometimes this error is shown when using images. Initially, I thought it is happening because of using JFIF standard jpg images vs EXIF standard jpg images but now I found a case that also happens for EXIF standard jpg images. How can I debug this problem and how can that be solved? I am using PyTorch...
ptrblck
I’m not sure how you are loading the images, but it seems that the used library has trouble loading these problematic image files (e.g. PIL or OpenCV). Based on the error message a None object will be returned which then fails in the torch.stack operation. Could you try to load the mentioned image…
sans_sense
When we use stride, say stride 2, it will pick the 0th, 2nd and so on, is there a way to instead pick 1st, 3rd and so on.Is there a parameter to conv1d or any other way that will help me get with stride 2 same results asF.conv1d(t_input, t_weight, padding=5, stride=1)[0,0,1:10:2]Actual Stride invocation that I am using...
ptrblck
Would it work, if you slice the input starting at index1 in PyTorch? This might not be the most convenient approach, but I don’t think the start index is easily changeable in the backend.
Igo312
I have trained one model in two gpus and saved it.And now I want to reload it just in one gpu,the error cause which saysMissing key(s) in state_dict: “base_network.conv1.weight”,Unexpected key(s) in state_dict: “module.base_network.conv1.weight”It seems save a multi-gpu model will get a prefix namemodule. Is there a mo...
ptrblck
You could save the model.module.state_dict() as described inthis tutorialinstead of model.state_dict(). If you cannot change it now (as the state_dict was already saved), your approach seems to be the correct workaround.
Arturas_Druteika
I’ve seen many tutorials where first atransformobject is created and then it is passed as an argument to ImageFolder() to create dataset. Transform object can normalize data by picking mean and the standart deviation for every channel. An example:transform = transforms.Compose( [transforms.ToTensor(), transfor...
ptrblck
Yes, you could use either this workflow (or the Dataset directly as mentioned by@omarfoq). Note, that calculating the dataset stats would only be needed once (if you have a fixed training, validation, and test split) and you could thus reuse the stats in all future experiments (as is done with th…
RyanElliott
I’ve been messing around with a Transformer using Time2Vec embeddings and have gone down a rabbit hole concerning input tensor shapes. It appears that PyTorch’s input shapes are uniform throughout the API, expecting(seq_len, batch_size, features)for timestep models likenn.Transformer,nn.LSTM,nn.GRU. TensorFlow’s API in...
ptrblck
PyTorch uses the mentioned shape for performance reasons. If you prefer to have the batch dimension in dim0, you could set batch_first=True while creating the module, which could then be easier to port code.
syomantak
I am trying to make an LSTM network from scratch using LSTMCell. 4 layers of LSTMs are stacked and a fully connected layer finally gives a single output for each time step. Here is the model codeclass McG_LSTM(nn.Module): def __init__(self,size=25,BSIZE=32,LEN=512): super(McG_LSTM, self).__init__() ...
ptrblck
I haven’t tested your code, but note that self.y.detach() is not an inplace operation so you might need to either reassign the detached tensor via self.y = self.y.detach() or use the inplace method self.y.detach_().
Bled_Clement
Hi all,I’ve been running my code with num_workers=0 up until recently. I want to see if I can speed things up a bit so I have been trying to test adjusting the number of processes. I had to set:torch.multiprocessing.set_start_method('spawn')to allow me to run num_workers>0.Now I may train my model. But between every ba...
ptrblck
I guess this line of code: torch.set_default_tensor_type('torch.cuda.FloatTensor') might be problematic, as it could use CUDA tensors inside the Dataset and thus inside each process, which could then fail due to using multiprocessing with multiple CUDA context instances.
Eric_Gill
Hi there,I have 3 classes of images, Covid, Normal and Viral Pneumonia(VP) in three different folders. There are roughly 3,600; 12,000; and 1,600 images in each folder respectively. As this set is imbalanced, I would like to split it into training, validation and testing subsets while maintaining the proportion of each...
ptrblck
You could call train_test_split again on train_idx instead of the np.arange input with stratify=class_array[train_idx] to create the train and validation indices. Let me know, if this works.
vadimkantorov
Doyandzcomputation dispatch to the same kernel? Are they the same for efficiency concerns? (also asked inDifference between mean() method and AvgPooling)x = torch.rand(16, 512, 64, 64) y = F.adaptive_avg_pool2d(x, (1, 1)) # should I refactor my code to do this instead of the following line? (it's maybe less flexible) ...
ptrblck
Both approaches would calculate the mean only as seenhere. The dispatch would be a bit different in case you are checking the stack trace.
MarcusNerva
This is my main function:if __name__ == '__main__': args = get_settings() set_random_seed(args.seed) train(args=args) test(args=args) print('===================All is finished====================')Every time I run this code with the same hyper-parameters, I got different performance on test dataset....
ptrblck
Have a look at theReproducibility docsand in particular set torch.use_deterministic_algorithms(True), which would yield an error, if no deterministic algorithms can be found for your workload.
111414
I have a tensor A with shape of (b, 1) and a tensor B with shape of (b, h, w). The question is how could I perform this process quickly by using more efficient codes?for i in range(b): B[i, int(A[i]):] = 0That is, I want to set part of B (a bunch of matrices) to zero, and the beginning row indices are in A.
ptrblck
This code should work: b, h, w, = 3, 4, 4 A = torch.randint(0, h, (b, 1)) B = torch.randn(b, h, w) C = B.clone() idx = torch.zeros(b, h) idx[torch.arange(b), A.squeeze()] = 1. idx = idx.cumsum(1).bool() B[idx] = 0. for i in range(b): C[i, int(A[i]):] = 0 print((B == C).all()) > tensor(True)…
Flock1
So I went through some of the threads and I was able get rid of some issues. But, I am still facing this errorRuntimeError: expected stride to be a single integer value or a list of 1 values to match the convolution dimensions, but got stride=[1, 1]In my case, I have assigned my own weights and I am using a 3rd party l...
ptrblck
Thanks for the code snippet. The simple model is running fine without the modification of the conv1.weight and doesn’t yield any errors. When you are running the conv1.weight.data assignment, you should get an error as: TypeError: cannot assign 'torch.FloatTensor' as parameter 'weight' (torch.nn.…
SiddharthSingi
Hi,I am looking to build a Gan model using pytorch which requires me to load images of different classes seprerately. I have used thetorchvision.datasets.imagefolderto load my dataset. I have images of horses and zebras. Now how can I load the images from only one class of the data. That is, I want to be able to specif...
ptrblck
You could extract all indices for the desired class (e.g. horses) and create a torch.utils.data.Subset using these indices and the dataset before passing it to the DataLoader. Alternatively, you could also pass these indices to a RandomSubsetSampler and assign it to the DataLoader.
avyz
Hi,I am training LeNet for handwritten digit classification on google colab using Pytorch with MNIST data set and saving weights and biases of the network in text files for each layer. Then loading these network parameters to the locally created LeNet (for inference) built using CuDNN library.INPUT->CONV1->POOL1->CONV2...
ptrblck
Unfortunately, I don’t know how cudnn logging can be enabled in Jupyter notebooks or Google Colab and also don’t know if it’s a limitation of the former of latter. One common issue users are seeing when trying to set env variables inside a notebook is the order: e.g. setting CUDA_VISIBLE_DEVICES o…
111491
The background of this question is as same asthis one. I realized that to train that middle layer parameter I can save the input of that layer and do forward from here, so that the training processs could be finished even faster. But I am not sure about how to implement this in pytorch. Do I have to rewrite the .forwar...
ptrblck
I think creating a new custom model with a new forward method would be the cleanest approach. Alternatively, you could also use the modules by directly accessing them via: middle_activation = ... out = model.middle_layer1(middle_activation) out = model.middle_layer2(out) ... but this would basica…
SungmanHong
I’m using video MOS predicting AI with GRU.GRU will feed all of the frame’s data and return one single MOS value.I’ll load pre-trained AI model and predict MOS for one video file.Also, I want to predict another MOS value from another video file.In this case, loading AI model to GPU takes about 20~30secs in my old lapto...
ptrblck
The nn.GRU module expects the initial hidden state as the second input argument and will default it to zeros, if none is provided. In case you are not manually passing the hidden state to it, you are already using the zeroed out hidden state.
Seo
Hello everyone,I am facing some memory issues running my model on multiple GPUs with DDP. I want to report to you the experiments I made to understand the memory utilization of the combination of workers + DDP. In all the experiments I will report in this post I will use always the same model, so the size of the model ...
ptrblck
Using the model or any CUDA operations in the collate_fn is uncommon, I think (at least I haven’t seen a use case so far) and I guess not well tested. The additional CUDA context creation might come from the usage of multiprocessing. I also don’t know what kind of 0MB process is created as I haven…
tagynedlrb
github.comeriklindernoren/PyTorch-YOLOv3Minimal PyTorch implementation of YOLOv3. Contribute to eriklindernoren/PyTorch-YOLOv3 development by creating an account on GitHub.Here’s where I got the code, and run custom training.I ran my code “python3 train.py --model_def config/yolov3-custom.cfg --data_config config/custo...
ptrblck
Could you try to run it via gdb and see, if you would get any proper error? gdb --args python train.py --model.... ... run ... bt
111422
import torch import numpy as np x = torch.rand(4,4) y = torch.rand(4,4) print(x) print(y) print(torch.cat((x,y),0))If I execute this code it will be liketensor([[0.1211, 0.7577, 0.8376, 0.4488], [0.6628, 0.8632, 0.9736, 0.8368], [0.5848, 0.0872, 0.0469, 0.2834], [0.8561, 0.6229, 0.3667, 0...
ptrblck
Alternatively to the loop, you could also interleave the tensors directly as seen here: x = torch.rand(4,4) y = torch.rand(4,4) print(x) print(y) z = torch.cat((x,y),0) test = None for k in range(x.shape[0]): if test is None: test = torch.cat((z[k:k+1],z[k + x.shape[0]:k + x.shape[0]+1]),0)…
Zack_Cheng
My data is normalized, each of them is a number between 0 to 1. When I print out the weight, it is a set of number between -1 to 1. But why? Do weight must be number between -1 to 1?
ptrblck
If you don’t apply any constraints on the parameters, they are not necessarily in the range [-1, 1]. E.g. nn.Linear layers are randomly initialized usingthis methodand thus the initial range might be smaller.
Geoffrey_Payne
With this code;for _, (imgs, captions) in tqdm(enumerate(coco_dataloader), total=len(coco_dataloader), leave=False): imgs = imgs.to(Constants.device) captions = captions.to(Constants.device) outputs = model(imgs, captions[:-1]) outputs1 = outputs.reshape(-1, outputs.shape[2]) ca...
ptrblck
Thanks for the update. I don’t know how the PyCharm debugger is working, but regarding the error you are seeing: Indexing.cu:605: block: [1,0,0], thread: [127,0,0] Assertion `srcIndex < srcSelectDimSize` failed. an indexing operation is failing. You could either execute the code on the CPU to get…
seloufian
Hi,I have a small issue that I’m struggling with, and for which I didn’t find an adequate solution.Having two two-dimensional tensors of different shape, I want to get the maximum between each element of the first tensor and all elements of the second tensor. As an example, I define two tensors:t1 = torch.randn(3, 4) t...
ptrblck
You could also use broadcasting on both tensors: t1 = torch.randn(3, 4) t2 = torch.randn(5, 4) maxs = [] for line in t1: # Current maximum has shape of (5, 4) curr_max = torch.maximum(line, t2) maxs.append(curr_max) # 'maxs' will have shape of (3, 5, 4) maxs = torch.stack(maxs) # use broa…
Noam_Salomonski
I have a time series classification task in which I should output a classification of 3 classes for every time stamp t.All data is labeled per frame.In the data set are more than 3 classes [which are also imbalanced].I want to useCrossEntropyLoss.My net should see all samples sequentially, because it uses that for hist...
ptrblck
You could move all classes, which should be ignores to a fixed class index and pass it as ignore_index to nn.CrossEntropyLoss: batch_size = 100 nb_classes = 3 output = torch.randn(batch_size, nb_classes, requires_grad=True) target = torch.randint(0, nb_classes+10, (batch_size,)) # move all unwanted…
Laura_Montalvo
Hi there! I want to know if somone could help me:I have a pretrained linear encoder that i would like to add before my real model but I dont know how to do it.Let me explain a little bit better:I have trained a encoder NN with my dataset and I have saved the parameters withtorch.save(model.state_dict(), ‘guada_withvali...
ptrblck
In your code snippet it seems you are creating model_encoder as the nn.Module class, not an object of your actual model definition. To properly load it, you would need to create the object first and then call .load_state_dict() on it: model_encoder = MyModelEncoder(my_arguments) model_encoder.load…
ronnie
for example if you have ;input= torch.rand([0,1,1,66650])m=nn.MaxPool2d(1,110)output=m(input1)why do i get the following error?RuntimeError: non-empty 3D or 4D input tensor expected but got ndim: 4
ptrblck
You are creating an empty tensor in: input = torch.rand([0,1,1,66650]) print(input) > tensor([], size=(0, 1, 1, 66650)) by setting the size of dim0 to zero. As the error message suggests, a non-empty tensor would be required.
Siddharth_Tandon
Hi,I am working with MSD (Medical Segmentation Decathlon) dataset for a segmentation problem.In Dataset’sinitmethod I am storing all filenames in list, and ingetitemreading the files, applying transformation, etc…I am facing some issue with GPU utilization:Problem is, nvidia-sme command is showing only 1 process (where...
ptrblck
The num_workers specified in the DataLoader are executed on the CPU using multiprocessing and will not be shown on nvidia-smi. The GPU utilization might be low, if you are facing bottlenecks in your code, such as data loading. Take a look atthis post, which explains it well and suggests some per…
Geoffrey_Payne
I am using Torchvision FasterRCNN to apply object detection in the MS Coco dataset. I am using the instance_train2017.json annotation file.My code for loading the dataloader is;# selected class ids: extract class id from the annotation coco_data_args = {'datalist':im_ids, 'coco_interface':coco_interface, 'coco_clas...
ptrblck
Based on the error it seems that this particular bounding box has a width of 0, so you might want to filter out these images.
Yasser_Khalil
Hello,I have a problem that I solved. However, my solution is extremely slow. If someone could help me speed up the solution I would be extremely grateful.So I am trying to compute the average of certain elements in an array using indices of another array. Please note that the same indices may exist multiple times. The...
ptrblck
I’m sure there are better approaches and you could speed it up more, but you could use index_put_ with the accumulate=True argument instead of the for loop and precompute some indices. Here is a code snippet: def fun1(): result = torch.full(( 32, 256, 256), -1.) data = torch.full(( 32, 400…
tlim
Hi there,My custom dataset code (multilabel classifier):class MultiLabelDataset(Dataset): def __init__(self,csv_path,image_path,transform=None): super().__init__() self.data = pd.read_csv(csv_path) self.labels = np.asarray(self.data.drop(['ID'],axis=1)) self.i...
ptrblck
Thanks for the code! I cannot reproduce the cudnn issue on a 2080 using the 1.8.0+CUDA10.2+cudnn7.6.5 and 1.8.0+CUDA11.1+cudnn8.0.5 conda binaries for all shapes in [1, 32]: for bs in torch.arange(1, 33): x = torch.randn(bs, 3, 224, 224, device=device) out = model(x) print(out.device) …
Superklez
Is there any difference in training on the spectrogram of a waveform as compared to training on the waveform itself? Does training on the waveform generate better results in general?
ptrblck
I think the difference would be quite large, as the sampling rate could be high in the time domain and make the training quite challenging. If I remember correctly, one way to make some models work on waveforms directly was to use a stack of conv layers with a specific dilation, so that the input si…
matrix
I trying to train a object detector on my custom data. Data I have has issue of class imbalance, meaning only 10% of images have objects in it, other 90% images doesn’t contain any objects. So here is what I want to do to solve imbalance issue,At every epoch, augment those 10% images by some factor s.t. it’s qty. is sa...
ptrblck
If you want a predefined number of samples from each class, you could implement a custom sampler, which would yield the batch indices using your desired logic. On the other hand, if your use case would allow weighted random sampling with replacement, you could use a WeightedRandomSampler as describ…
ajwitty
I only want to resize images that are smaller than my desired input size. Is there way to reshape images that are smaller than a certain size and ignore all others?
ptrblck
Using theDatasetclass, you can lazily load your images in the __getitem__ method. Here is a small example: class TrainDataset(Dataset): def __init__(self, image_paths, targets): self.image_paths = image_paths self.targets = targets def __getitem__(self, index): i…
jerly-hjzhou
I want to build a convolutional neural network to recognize digits. And I already have the structure and the parameters of weight and bias stored in the format of “txt”. How should I use them to implement a network?
ptrblck
You could create the model first, load the parameters from the .txt file, transform them to floats and then tensors, and load each parameter manually via: with torch.no_grad(): model.layerX.weight.copy_(layerX_weight) model.layerX.bias.copy_(layerX_bias) Note that his approach is a bit ted…