name stringlengths 15 255 | question stringlengths 20 1.77k | questionUpvotes int64 0 23 | timeCreated stringlengths 24 24 | answer stringlengths 9 1.09k | answerUpvotes int64 0 75 | timeAnswered stringlengths 24 24 | answerURL stringlengths 50 285 | context stringlengths 244 1.73k | answer_start int64 0 3.45k | answers stringlengths 46 1.14k |
|---|---|---|---|---|---|---|---|---|---|---|
How to use focalloss in segmentation? | Hello, I’m doing a project about semantic segmentation with 2 class using U-net , but my data was unbalanced, so I think maybe use focalloss is a good idea for my project, and I was use BCEloss, so changed the final layer from 1 channel to 2 channels, and use this code <a href="https://github.com/doiken23/pytorch_toolb... | 0 | 2018-07-25T10:16:29.269Z | Where did you modify the code? In your first post or the github repo?
I’m not sure about this line:
label = label[:, :, np.newaxis]
Are you trying to add a batch dimension to your target?
If so, the batch dimension should be at dim0, i.e. the first dimension.
Make sure your label is of type lon… | 0 | 2018-07-25T12:01:56.033Z | https://discuss.pytorch.org/t/how-to-use-focalloss-in-segmentation/21695/4 | Could you try to run the code in the environment with numpy==1.18.1 please? Where did you modify the code? In your first post or the github repo?
I’m not sure about this line:
label = label[:, :, np.newaxis]
Are you trying to add a batch dimension to your target?
If so, the batch dimension should be at dim0, i.e. t... | 935 | {'text': ['Where did you modify the code? In your first post or the github repo?\n\nI’m not sure about this line:\n\nlabel = label[:, :, np.newaxis]\n\nAre you trying to add a batch dimension to your target?\n\nIf so, the batch dimension should be at dim0, i.e. the first dimension.\n\nMake sure your label is of type lo... |
How to convert RGB images with many different colors (not only red, green, blue) into classes for segmentation training?, The mask is linked below | <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/a/9/a980cb8fb82c6d65899808e2fe8d846d6e844b98.png" data-download-href="https://discuss.pytorch.org/uploads/default/a980cb8fb82c6d65899808e2fe8d846d6e844b98" title="TCGA-2Z-A9J9-01A-01-TS1">[TCGA-2Z-A9J9-01A-01-TS1]</a> | 0 | 2021-01-27T06:00:56.290Z | <a href="https://discuss.pytorch.org/t/training-semantic-segmentation/49275/4">This code</a> shows an example of the transformation from colors to class indices. | 2 | 2021-01-28T09:02:24.379Z | https://discuss.pytorch.org/t/how-to-convert-rgb-images-with-many-different-colors-not-only-red-green-blue-into-classes-for-segmentation-training-the-mask-is-linked-below/110102/2 | Could you try to run the code in the environment with numpy==1.18.1 please? Where did you modify the code? In your first post or the github repo?
I’m not sure about this line:
label = label[:, :, np.newaxis]
Are you trying to add a batch dimension to your target?
If so, the batch dimension should be at dim0, i.e. t... | 385 | {'text': ['<a href="https://discuss.pytorch.org/t/training-semantic-segmentation/49275/4">This code</a> shows an example of the transformation from colors to class indices.'], 'answer_start': [385]} |
Creating ANY vectors/tensors to gpu directly | I need to create a random vector with a specific distribution each iteration and run it in gpu/cuda. I know one can do x.cuda() on it but that seems rather slow based on me playing around with it. Is there a better way to do this so that it starts of in GPU or something of that sort? Especially cuz … | 0 | 2018-03-29T18:12:25.353Z | For now use this pattern torch.cuda.*Tensor(*shape).inplace_sampling_method_here_(). Here are the available inplace sampling methods: <a href="http://pytorch.org/docs/master/torch.html#in-place-random-sampling">http://pytorch.org/docs/master/torch.html#in-place-random-sampling</a>. Notice that these are the basic build... | 1 | 2018-04-01T01:48:18.213Z | https://discuss.pytorch.org/t/creating-any-vectors-tensors-to-gpu-directly/15674/9 | For now use this pattern torch.cuda.*Tensor(*shape).inplace_sampling_method_here_(). Here are the available inplace sampling methods: <a href="http://pytorch.org/docs/master/torch.html#in-place-random-sampling">http://pytorch.org/docs/master/torch.html#in-place-random-sampling</a>. Notice that these are the basic build... | 1,092 | {'text': ['For now use this pattern torch.cuda.*Tensor(*shape).inplace_sampling_method_here_(). Here are the available inplace sampling methods: <a href="http://pytorch.org/docs/master/torch.html#in-place-random-sampling">http://pytorch.org/docs/master/torch.html#in-place-random-sampling</a>. Notice that these are the ... |
Trying xgboost inside forward , neural net | import torch
import torch.nn as nn
import timm
from xgboost import XGBClassifier
model_name = 'swin_base_patch4_window7_224'
out_dim = 1
class get_model(torch.nn.Module):
def __init__(self):
super().__init__()
self.model = timm.create_model(model_name, pretrained=False)
… | 0 | 2021-12-25T18:13:38.938Z | If you are trying to make x to be the same as target ?
Why don’t you just
def forward(self, features,targets):
x = self.model.head(features)
x = self.last(x)
x = self.depth1(x)
x = self.depth2(x)
loss = some_loss_function(x, targets)
return x, loss
T… | 2 | 2021-12-25T19:07:01.138Z | https://discuss.pytorch.org/t/trying-xgboost-inside-forward-neural-net/140228/10 | For now use this pattern torch.cuda.*Tensor(*shape).inplace_sampling_method_here_(). Here are the available inplace sampling methods: <a href="http://pytorch.org/docs/master/torch.html#in-place-random-sampling">http://pytorch.org/docs/master/torch.html#in-place-random-sampling</a>. Notice that these are the basic build... | 936 | {'text': ['If you are trying to make x to be the same as target ?\n\nWhy don’t you just\n\ndef forward(self, features,targets):\n\nx = self.model.head(features)\n\nx = self.last(x)\n\nx = self.depth1(x)\n\nx = self.depth2(x)\n\nloss = some_loss_function(x, targets)\n\nreturn x, loss\n\nT…'], 'answer_start': [936... |
Binary classification Different input sizes error | Hello, doing binary classification with BCELoss()
this is my dataset gettiem()
def getitem(self,index):
x=torch.tensor(self.df.iloc[index,:-1])
y_label=torch.tensor(self.df.iloc[index,-1])
return (x.float(),y_label.float())
this is my Model
class Credit_Module(nn.Module):
def __init__(… | 0 | 2021-04-27T13:10:22.586Z | I don’t really know what you are trying to do here using BCELoss, so I will guess according to the info you have given.
Since you said you want to do binary classification and your target is of size torch.Size([10]), I’m guessing it is filled with ones and zeros and you want your network to predict… | 0 | 2021-04-27T13:58:51.303Z | https://discuss.pytorch.org/t/binary-classification-different-input-sizes-error/119583/2 | For now use this pattern torch.cuda.*Tensor(*shape).inplace_sampling_method_here_(). Here are the available inplace sampling methods: <a href="http://pytorch.org/docs/master/torch.html#in-place-random-sampling">http://pytorch.org/docs/master/torch.html#in-place-random-sampling</a>. Notice that these are the basic build... | 658 | {'text': ['I don’t really know what you are trying to do here using BCELoss, so I will guess according to the info you have given.\n\nSince you said you want to do binary classification and your target is of size torch.Size([10]), I’m guessing it is filled with ones and zeros and you want your network to predict&hellip... |
Custom methods in DistributedDataParallel | I am trying to do multi gpu training with DistributedDataParallel. I wrap it around my model. However my model has a custom function that now i call by doing model.module.function(x). I was wondering if this is ok and if something bad will happen. Thanks | 0 | 2020-04-16T22:18:31.745Z | Yes, I think the gradients should be fine. | 1 | 2020-04-17T14:08:40.862Z | https://discuss.pytorch.org/t/custom-methods-in-distributeddataparallel/77114/10 | Yes, I think the gradients should be fine. I’m afraid not. There is no constraints to make them positive right? Maybe you can try with different things torch.relu, torch.abs. But that’s another question. In that case, your shapes should be [batch_size, seq_length, nb_classes].
Try to permute your ourput using output =... | 1,932 | {'text': ['Yes, I think the gradients should be fine.'], 'answer_start': [1932]} |
Custom loss function with trainable parameters | Hi everyone,
I need help.
I am trying to create a custom loss function with two trainable parameters.
class MyCustomLoss(nn.Module):
def __init__(self, my_parameter1, my_parameter2):
super(MyCustomLoss, self).__init__()
self.A = my_parameter1
self.B = my_parameter2
def forw… | 1 | 2022-03-05T19:53:34.690Z | I’m afraid not. There is no constraints to make them positive right? Maybe you can try with different things torch.relu, torch.abs. But that’s another question. | 0 | 2022-03-06T21:40:38.057Z | https://discuss.pytorch.org/t/custom-loss-function-with-trainable-parameters/145706/12 | Yes, I think the gradients should be fine. I’m afraid not. There is no constraints to make them positive right? Maybe you can try with different things torch.relu, torch.abs. But that’s another question. In that case, your shapes should be [batch_size, seq_length, nb_classes].
Try to permute your ourput using output =... | 1,009 | {'text': ['I’m afraid not. There is no constraints to make them positive right? Maybe you can try with different things torch.relu, torch.abs. But that’s another question.'], 'answer_start': [1009]} |
Build a neural composer using RNN | import torch
import torch.nn as nn
import helpers.dataset as dataset
from torch.autograd import Variable
input_size = 128
hidden_size = 128
num_layers = 2
output_size = 128
batch_size = 1
num_epochs = 2
learning_rate = 0.01
# Dataset
train_dataset = dataset.pianoroll_dataset_batch('./datasets/tra&hellip... | 0 | 2018-11-23T02:53:13.378Z | In that case, your shapes should be [batch_size, seq_length, nb_classes].
Try to permute your ourput using output = output.permute(1, 0, 2) and squeeze the additional dimension in your target target = target.squeeze(2).
Where does dim2 in your target come from? | 0 | 2018-11-23T16:47:38.207Z | https://discuss.pytorch.org/t/build-a-neural-composer-using-rnn/30314/10 | Yes, I think the gradients should be fine. I’m afraid not. There is no constraints to make them positive right? Maybe you can try with different things torch.relu, torch.abs. But that’s another question. In that case, your shapes should be [batch_size, seq_length, nb_classes].
Try to permute your ourput using output =... | 204 | {'text': ['In that case, your shapes should be [batch_size, seq_length, nb_classes].\n\nTry to permute your ourput using output = output.permute(1, 0, 2) and squeeze the additional dimension in your target target = target.squeeze(2).\n\nWhere does dim2 in your target come from?'], 'answer_start': [204]} |
Custom kernels values pytorch | Friends I get this error:RuntimeError: expected stride to be a single integer value or a list of 1 values to match the convolution dimensions, but got stride=[1, 1]
This apperar in : y_pred = CNNmodel(X_train)
How can I customize the kernel values in this code please
kn = torch.Tensor([[1… | 0 | 2020-04-02T17:07:19.557Z | Your kernel shape in kn is wrong, as nn.Conv2d uses a weight with the shape [out_channels, in_channels, height, width].
This code should work:
kn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]).unsqueeze(0).unsqueeze(0)
class ConvolutionalNetwork(nn.Module):
def __init__(self):
su… | 0 | 2020-04-04T02:16:00.064Z | https://discuss.pytorch.org/t/custom-kernels-values-pytorch/75131/2 | Your kernel shape in kn is wrong, as nn.Conv2d uses a weight with the shape [out_channels, in_channels, height, width].
This code should work:
kn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]).unsqueeze(0).unsqueeze(0)
class ConvolutionalNetwork(nn.Module):
def __init__(self):
su… Sorry for not being c... | 934 | {'text': ['Your kernel shape in kn is wrong, as nn.Conv2d uses a weight with the shape [out_channels, in_channels, height, width].\n\nThis code should work:\n\nkn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]).unsqueeze(0).unsqueeze(0)\n\nclass ConvolutionalNetwork(nn.Module):\n\ndef __init__(self):\n\nsu…'... |
Conditional VAE - concactanate | Hi,
If i have a one hot vector of shape [25,6] and a data input of [25,1,260,132] how do i concatanate into a single tensor to feed in to the encoder of a convolutional VAE?
like wise the lat_dim tensor is [25,100] how to concatanate to feed into the decoder of the convolutional VAE?
Chaslie | 0 | 2020-05-29T13:28:13.122Z | Sorry for not being clear enough.
You could pass both tensors to the forward method and concatenate the activations as seen in this dummy code:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv = nn.Conv2d(1, 1, 3, 1, 1)
self.lin = … | 0 | 2020-06-05T09:12:42.524Z | https://discuss.pytorch.org/t/conditional-vae-concactanate/83369/9 | Your kernel shape in kn is wrong, as nn.Conv2d uses a weight with the shape [out_channels, in_channels, height, width].
This code should work:
kn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]).unsqueeze(0).unsqueeze(0)
class ConvolutionalNetwork(nn.Module):
def __init__(self):
su… Sorry for not being c... | 766 | {'text': ['Sorry for not being clear enough.\n\nYou could pass both tensors to the forward method and concatenate the activations as seen in this dummy code:\n\nclass MyModel(nn.Module):\n\ndef __init__(self):\n\nsuper(MyModel, self).__init__()\n\nself.conv = nn.Conv2d(1, 1, 3, 1, 1)\n\nself.lin = …'], 'answer_s... |
Freeing buffer strange behavior | I’ve tried to run WGAN model and meet some strange behavior. I’m not sure is it my bug, or pytorch bug. I made a <a href="https://gist.github.com/RomanSteinberg/9ca64be01ff8c8d02a225bd56c41fb5d" rel="nofollow noopener">minimal example</a> to discuss it here.
So, we have an error
RuntimeError: Trying to backward throu... | 0 | 2018-12-12T13:12:09.915Z | Hi,
Yes this comment was more to explain the details of the issue without writing too long stuff on the github PR.
You can either use inplace=False or use the version of relu that I gave you above with inplace=True. | 0 | 2018-12-17T10:39:58.155Z | https://discuss.pytorch.org/t/freeing-buffer-strange-behavior/31955/10 | Your kernel shape in kn is wrong, as nn.Conv2d uses a weight with the shape [out_channels, in_channels, height, width].
This code should work:
kn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]).unsqueeze(0).unsqueeze(0)
class ConvolutionalNetwork(nn.Module):
def __init__(self):
su… Sorry for not being c... | 584 | {'text': ['Hi,\n\nYes this comment was more to explain the details of the issue without writing too long stuff on the github PR.\n\nYou can either use inplace=False or use the version of relu that I gave you above with inplace=True.'], 'answer_start': [584]} |
Num_workers dead threads | Hello, I have faced a problem with num_workers while training my models. I have made a simple transfer learning task with densenet121 and CIFAR10 resized to the ImageNet resolution of 224:
class DenseNet(nn.Module):
def __init__(self):
super(DenseNet, self).__init__()
#… | 0 | 2019-02-01T00:04:49.943Z | Ok it seems to work judging by the nvidia-smi:
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/0/0d0025efa2c51d792f890784466cf742d516fbe8.png" data-download-href="https://discuss.pytorch.org/uploads/default/0d0025efa2c51d792f890784466cf742d516fbe8" title="image.png">[image]</a>
The d... | 0 | 2019-02-05T01:38:37.863Z | https://discuss.pytorch.org/t/num-workers-dead-threads/36100/17 | Ok it seems to work judging by the nvidia-smi:
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/0/0d0025efa2c51d792f890784466cf742d516fbe8.png" data-download-href="https://discuss.pytorch.org/uploads/default/0d0025efa2c51d792f890784466cf742d516fbe8" title="image.png">[image]</a>
The d... | 1,602 | {'text': ['Ok it seems to work judging by the nvidia-smi:\n\n<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/0/0d0025efa2c51d792f890784466cf742d516fbe8.png" data-download-href="https://discuss.pytorch.org/uploads/default/0d0025efa2c51d792f890784466cf742d516fbe8" title="image.png">[imag... |
Higher CPU usage while torchvision.transforms | CPU usage is around 250%(ubuntu top command) was using torchvision transforms to convert cv2 image to torch
normalize_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ])
def normalizeCvImage(image_cv, device):
return normalize_trans… | 0 | 2019-02-24T23:59:15.620Z | I see. So you are not using DataLoader or anything like that but just calling that function on each image separately?
In your function
def normalizeCvImage(image_cv, device):
image = torch.Tensor(image_cv).to(device)
image = image.permute(2, 0, 1).unsqueeze(0)
image = (image - 127.5) /… | 0 | 2019-02-25T02:10:20.295Z | https://discuss.pytorch.org/t/higher-cpu-usage-while-torchvision-transforms/38131/6 | Ok it seems to work judging by the nvidia-smi:
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/0/0d0025efa2c51d792f890784466cf742d516fbe8.png" data-download-href="https://discuss.pytorch.org/uploads/default/0d0025efa2c51d792f890784466cf742d516fbe8" title="image.png">[image]</a>
The d... | 1,466 | {'text': ['I see. So you are not using DataLoader or anything like that but just calling that function on each image separately?\n\nIn your function\n\ndef normalizeCvImage(image_cv, device):\n\nimage = torch.Tensor(image_cv).to(device)\n\nimage = image.permute(2, 0, 1).unsqueeze(0)\n\nimage = (image - 127.5) /…... |
Faster R-CNN transformed input | Torchivison’s model uses ResNet51+FPN as a feature extractor.
I usually transform images by first converting them to a tensor, and then multiplying again by 255
t_ = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(img_size),
… | 0 | 2020-01-31T10:24:50.705Z | No, it’s common to normalize the inputs for a lot of machine learning models, as this might accelerate and stabilize the training.
Some methods e.g. RandomForest classifiers are not sensitive to the input range, while e.g. neural networks are.
You would have to check the dataset creation (or just … | 0 | 2020-02-07T19:16:53.958Z | https://discuss.pytorch.org/t/faster-r-cnn-transformed-input/68227/13 | Ok it seems to work judging by the nvidia-smi:
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/0/0d0025efa2c51d792f890784466cf742d516fbe8.png" data-download-href="https://discuss.pytorch.org/uploads/default/0d0025efa2c51d792f890784466cf742d516fbe8" title="image.png">[image]</a>
The d... | 965 | {'text': ['No, it’s common to normalize the inputs for a lot of machine learning models, as this might accelerate and stabilize the training.\n\nSome methods e.g. RandomForest classifiers are not sensitive to the input range, while e.g. neural networks are.\n\nYou would have to check the dataset creation (or just &hell... |
Difference between transform, target_transform and transforms in VOC_DETECTION_DATASET | Hi,
I was checking the documentation of the <a href="https://pytorch.org/docs/stable/torchvision/datasets.html#torchvision.datasets.VOCDetection" rel="nofollow noopener">VOC dataset</a> provided by pytorch. I saw that there are three parameters very similar: transform, target_transform and transforms. As far as I unde... | 1 | 2020-06-21T13:28:15.316Z | You could either define a custom transformation, which accepts the image and target or use e.g. the <a href="https://github.com/pytorch/vision/blob/master/references/segmentation/transforms.py">segmentation transformations</a>, which also accept these two arguments. | 0 | 2020-06-22T07:58:44.670Z | https://discuss.pytorch.org/t/difference-between-transform-target-transform-and-transforms-in-voc-detection-dataset/86281/2 | You could either define a custom transformation, which accepts the image and target or use e.g. the <a href="https://github.com/pytorch/vision/blob/master/references/segmentation/transforms.py">segmentation transformations</a>, which also accept these two arguments. At this point, eager mode quantization might require ... | 2,546 | {'text': ['You could either define a custom transformation, which accepts the image and target or use e.g. the <a href="https://github.com/pytorch/vision/blob/master/references/segmentation/transforms.py">segmentation transformations</a>, which also accept these two arguments.'], 'answer_start': [2546]} |
Am I correct in concluding that resnet that comes with pytorch can't be quantized by pytorch? | Greetings. I have gone through two quantization attempts for resnet50 that comes with pytorch and had mixed results:
dynamic quantization works but is limited to the only Linear layer used in ResNet, thus the resulting improvements in model size and inference latency are just a few percent.
st… | 0 | 2020-05-22T01:00:41.404Z | At this point, eager mode quantization might require changes to the model in order to make it work. Here is an example of how resnet50 is quantized in pytorch - <a href="https://github.com/pytorch/vision/blob/master/torchvision/models/quantization/resnet.py" rel="nofollow noopener">https://github.com/pytorch/vision/blo... | 1 | 2020-05-28T16:46:10.548Z | https://discuss.pytorch.org/t/am-i-correct-in-concluding-that-resnet-that-comes-with-pytorch-cant-be-quantized-by-pytorch/82405/4 | You could either define a custom transformation, which accepts the image and target or use e.g. the <a href="https://github.com/pytorch/vision/blob/master/references/segmentation/transforms.py">segmentation transformations</a>, which also accept these two arguments. At this point, eager mode quantization might require ... | 1,540 | {'text': ['At this point, eager mode quantization might require changes to the model in order to make it work. Here is an example of how resnet50 is quantized in pytorch - <a href="https://github.com/pytorch/vision/blob/master/torchvision/models/quantization/resnet.py" rel="nofollow noopener">https://github.com/pytorch... |
Pruning vs Dropout | How weight pruning is different from dropout? | 0 | 2021-08-29T18:11:13.967Z | Sorry for diverting your thread.
Yes, the pruning seems to rename weights (appending _orig probably is the most common), you can get the current set of weight names using
print([n for n, p in module.named_parameters()])
There is an equivalent named_buffers for non-parameters that gets masks.
Als… | 2 | 2021-08-30T06:01:11.012Z | https://discuss.pytorch.org/t/pruning-vs-dropout/130574/8 | You could either define a custom transformation, which accepts the image and target or use e.g. the <a href="https://github.com/pytorch/vision/blob/master/references/segmentation/transforms.py">segmentation transformations</a>, which also accept these two arguments. At this point, eager mode quantization might require ... | 702 | {'text': ['Sorry for diverting your thread.\n\nYes, the pruning seems to rename weights (appending _orig probably is the most common), you can get the current set of weight names using\n\nprint([n for n, p in module.named_parameters()])\n\nThere is an equivalent named_buffers for non-parameters that gets masks.\n\nAls&... |
Higher order: gradient of optimization procedure of whole nn.Module | Hi, I’m trying to differentiate through an optimization procedure of another neural net. The code below shows 2 functions:
a working version where instead of neural nets we just have single tensors
the version with neural nets with 3 attempted solutions commented out.
Both should be equivalent.
… | 0 | 2018-08-29T18:31:18.924Z | I found a solution: Updating the Module._parameters dictionary directly:
# Inner optimization
for k in range(n_inner_opt):
true_objective2 = game_NN.true_objective(net2_, net1)
grad2 = torch.autograd.grad(true_objective2, net2_.parameters(), create_graph=True)
'In the following li… | 0 | 2018-08-31T15:26:23.057Z | https://discuss.pytorch.org/t/higher-order-gradient-of-optimization-procedure-of-whole-nn-module/24163/9 | I found a solution: Updating the Module._parameters dictionary directly:
# Inner optimization
for k in range(n_inner_opt):
true_objective2 = game_NN.true_objective(net2_, net1)
grad2 = torch.autograd.grad(true_objective2, net2_.parameters(), create_graph=True)
'In the following li… Could you check the c... | 2,020 | {'text': ['I found a solution: Updating the Module._parameters dictionary directly:\n\n# Inner optimization\n\nfor k in range(n_inner_opt):\n\ntrue_objective2 = game_NN.true_objective(net2_, net1)\n\ngrad2 = torch.autograd.grad(true_objective2, net2_.parameters(), create_graph=True)\n\n'In the following li…'... |
CUDA out of memory error when allocating one number to GPU memory | I am getting an out of memory error for CUDA when running the following code:
import torch
assert torch.cuda.is_available() == 1
x = torch.randn(1)
x.cuda() # RuntimeError: CUDA error: out of memory
Running on GeForce GTX 750, Ubuntu 18.04. How can there not be enough memory for one float? | 1 | 2020-03-25T07:47:07.281Z | Could you check the current memory usage on the device via nvidia-smi and make sure that no other processes are running?
Note that besides the tensor you would need to allocate the CUDA context on the device, which might take a few hundred MBs. | 0 | 2020-03-26T03:46:57.306Z | https://discuss.pytorch.org/t/cuda-out-of-memory-error-when-allocating-one-number-to-gpu-memory/74318/2 | I found a solution: Updating the Module._parameters dictionary directly:
# Inner optimization
for k in range(n_inner_opt):
true_objective2 = game_NN.true_objective(net2_, net1)
grad2 = torch.autograd.grad(true_objective2, net2_.parameters(), create_graph=True)
'In the following li… Could you check the c... | 1,309 | {'text': ['Could you check the current memory usage on the device via nvidia-smi and make sure that no other processes are running?\n\nNote that besides the tensor you would need to allocate the CUDA context on the device, which might take a few hundred MBs.'], 'answer_start': [1309]} |
Creating Custom Dataset from inbuilt pytorch datasets along with data transformations | Hi I am quite new to pytorch. I was trying to implement transfer learning with CIFAR10 and resnet18 model built in. For that what I am intending to do is first download original dataset and apply some transformations onto it and the take 500 samples from each class among the 10 classes and create a … | 0 | 2019-10-15T09:42:46.454Z | Hey, I wrote this dataset for you that gets a subset of CIFAR10 :slight_smile:. Just set the n_images_per_class to 500 and it should be ready to use!
from torchvision import datasets
from collections import defaultdict, deque
import itertools
class Cifar5000(datasets.CIFAR10):
def __init__(se… | 0 | 2019-10-15T12:13:14.828Z | https://discuss.pytorch.org/t/creating-custom-dataset-from-inbuilt-pytorch-datasets-along-with-data-transformations/58270/2 | I found a solution: Updating the Module._parameters dictionary directly:
# Inner optimization
for k in range(n_inner_opt):
true_objective2 = game_NN.true_objective(net2_, net1)
grad2 = torch.autograd.grad(true_objective2, net2_.parameters(), create_graph=True)
'In the following li… Could you check the c... | 545 | {'text': ['Hey, I wrote this dataset for you that gets a subset of CIFAR10 :slight_smile:. Just set the n_images_per_class to 500 and it should be ready to use!\n\nfrom torchvision import datasets\n\nfrom collections import defaultdict, deque\n\nimport itertools\n\nclass Cifar5000(datasets.CIFAR10):\n\ndef __init__(se&... |
Recording gradients in RNNs at each point in time | Hi,
I am trying to record the values of the gradients as they propagate in time through an RNN. Initially I thought this would be easily accomplished using the register_hook function by calling it to each parameter, yet I now realize that for some reason, the hook is not called at each step in tim… | 0 | 2019-11-27T18:33:42.076Z | The hook will give you the gradient at the point where the hook is registered.
If you want to get it after every computation, you need to register one after every computation. | 1 | 2019-11-27T19:35:31.821Z | https://discuss.pytorch.org/t/recording-gradients-in-rnns-at-each-point-in-time/62339/2 | The hook will give you the gradient at the point where the hook is registered.
If you want to get it after every computation, you need to register one after every computation. Hi,
From the error message, the problem is that in some operations, you’re mixing single precision and double precision numbers.
If you did n... | 1,702 | {'text': ['The hook will give you the gradient at the point where the hook is registered.\n\nIf you want to get it after every computation, you need to register one after every computation.'], 'answer_start': [1702]} |
[Beginner] Data loading, weights initialization | training_samples = TensorDataset(X_train, y_train)
test_samples = TensorDataset(X_test, y_test)
train_loader = DataLoader(training_samples, batch_size=64, shuffle=True)
valid_loader = DataLoader(test_samples, batch_size=64, shuffle=True)
class DynamicNet(torch.nn.Module):
def __init__(self, D_… | 0 | 2018-01-15T13:24:02.204Z | Hi,
From the error message, the problem is that in some operations, you’re mixing single precision and double precision numbers.
If you did not change the default tensor type, your network should be in single precision, is your dataset double precision?
If so, do one of the two below, depending o… | 0 | 2018-01-15T13:34:23.850Z | https://discuss.pytorch.org/t/beginner-data-loading-weights-initialization/12334/3 | The hook will give you the gradient at the point where the hook is registered.
If you want to get it after every computation, you need to register one after every computation. Hi,
From the error message, the problem is that in some operations, you’re mixing single precision and double precision numbers.
If you did n... | 1,028 | {'text': ['Hi,\n\nFrom the error message, the problem is that in some operations, you’re mixing single precision and double precision numbers.\n\nIf you did not change the default tensor type, your network should be in single precision, is your dataset double precision?\n\nIf so, do one of the two below, depending o&he... |
Cannot load state dict even though sizes are the same | I have run this code:
z = torch.load(load_path)
for k, v in z.items():
print(z)
model.load_state_dict(z)
..........('base_loss', tensor([[0.]], device='cuda:0')),
('b', tensor(5., device='cuda:0')),
('x_grid',
tensor([[[[[-1.0000, -1.0000, -1.0000, -1.… | 0 | 2020-03-29T01:25:31.024Z | Could you try to call .contiguous() on all expanded tensors?
I’ve seen a similar issue before and will create an issue in a moment to track it. | 1 | 2020-03-29T06:36:10.334Z | https://discuss.pytorch.org/t/cannot-load-state-dict-even-though-sizes-are-the-same/74652/3 | The hook will give you the gradient at the point where the hook is registered.
If you want to get it after every computation, you need to register one after every computation. Hi,
From the error message, the problem is that in some operations, you’re mixing single precision and double precision numbers.
If you did n... | 486 | {'text': ['Could you try to call .contiguous() on all expanded tensors?\n\nI’ve seen a similar issue before and will create an issue in a moment to track it.'], 'answer_start': [486]} |
NVIDIA Tensor Cores not being used for nn.Conv3d (3D Convolutions) | Hi,
TLDR; “Conv2d uses tensor cores, Conv3D doesn’t when using apex AMP or FP16”
According to NVIDIA, cudnn 8 does support tensor core operations for 3D convolutions.
To be sure if tensor cores are really being used (HMMA instructions) I am checking this with the nvidia profiler with the sm__inst… | 0 | 2020-07-23T09:12:03.215Z | Solution:
Verified that this is a bug inside cudnn 8.0.1 via official bug report.
Building torch from source with cudnn 8.0.2 fixes the problem. | 2 | 2020-08-24T12:18:08.867Z | https://discuss.pytorch.org/t/nvidia-tensor-cores-not-being-used-for-nn-conv3d-3d-convolutions/90253/12 | Solution:
Verified that this is a bug inside cudnn 8.0.1 via official bug report.
Building torch from source with cudnn 8.0.2 fixes the problem. momentum would be such an internal state, which uses the previous gradients to update the parameters even with a zero gradients.
Here is a small example showing this behavi... | 1,260 | {'text': ['Solution:\n\nVerified that this is a bug inside cudnn 8.0.1 via official bug report.\n\nBuilding torch from source with cudnn 8.0.2 fixes the problem.'], 'answer_start': [1260]} |
How to freeze or fix the specific(subset, partial) weight in convolution filter | <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/f/f/ff0dd54b806beefe14711cb973f4205b63549c90.png" data-download-href="https://discuss.pytorch.org/uploads/default/ff0dd54b806beefe14711cb973f4205b63549c90" title="torch forum1">[torch forum1]</a>
Above is my code for trying to fix, freez... | 0 | 2020-04-09T14:34:58.982Z | momentum would be such an internal state, which uses the previous gradients to update the parameters even with a zero gradients.
Here is a small example showing this behavior:
# Setup
model = nn.Conv2d(1, 10, 3, 1, 1)
weight_reference = model.weight.clone()
optimizer = torch.optim.SGD(model.parame… | 1 | 2020-04-10T04:09:43.968Z | https://discuss.pytorch.org/t/how-to-freeze-or-fix-the-specific-subset-partial-weight-in-convolution-filter/76050/4 | Solution:
Verified that this is a bug inside cudnn 8.0.1 via official bug report.
Building torch from source with cudnn 8.0.2 fixes the problem. momentum would be such an internal state, which uses the previous gradients to update the parameters even with a zero gradients.
Here is a small example showing this behavi... | 777 | {'text': ['momentum would be such an internal state, which uses the previous gradients to update the parameters even with a zero gradients.\n\nHere is a small example showing this behavior:\n\n# Setup\n\nmodel = nn.Conv2d(1, 10, 3, 1, 1)\n\nweight_reference = model.weight.clone()\n\noptimizer = torch.optim.SGD(model.pa... |
Still overfitting, no matter how strong i regularize | Hi all,
my net (a multimodal transformer for text and vision) vastly overfitted the validation set after 4 epochs. I added all kinds of combinations of different dropout strengths, weight decays, learning rate schedulings, and so on…
the only thing that changed is the amount of epochs until the tr… | 0 | 2021-10-11T21:15:35.784Z | two observations:
“My model is a simple bi-encoder (vit for the images, bert for the linguisric component) with a late fusion” => if we check the <a href="https://scontent-sjc3-1.xx.fbcdn.net/v/t39.2365-6/96772393_581552399130415_3226887050644946944_n.png?_nc_cat=100&ccb=1-5&_nc_sid=ad8a9d&_nc_ohc=cMwWN... | 1 | 2021-10-17T22:44:05.460Z | https://discuss.pytorch.org/t/still-overfitting-no-matter-how-strong-i-regularize/133976/29 | Solution:
Verified that this is a bug inside cudnn 8.0.1 via official bug report.
Building torch from source with cudnn 8.0.2 fixes the problem. momentum would be such an internal state, which uses the previous gradients to update the parameters even with a zero gradients.
Here is a small example showing this behavi... | 459 | {'text': ['two observations:\n\n“My model is a simple bi-encoder (vit for the images, bert for the linguisric component) with a late fusion” => if we check the <a href="https://scontent-sjc3-1.xx.fbcdn.net/v/t39.2365-6/96772393_581552399130415_3226887050644946944_n.png?_nc_cat=100&ccb=1-5&_nc_sid=ad8a9d&... |
Libtorch on Windows prebuilt binaries questions | Hi all,
I am using prebuilt libtorch libraries for Windows in my C++ programs, everything works just fine. Two questions here:
How are the cuda files (*.cu) compiled in these binaries? I am especially interested in the -gencode parameter values passed to NVCC compiler when creating these binarie… | 0 | 2018-12-19T10:54:44.838Z | Glad it’s working for you. As for the static build, I guess you’ll need to append -DTORCH_BUILD_STATIC_LIBS to the compiler flags when compiling your cpp extension that uses libtorch. | 0 | 2019-01-17T13:17:28.753Z | https://discuss.pytorch.org/t/libtorch-on-windows-prebuilt-binaries-questions/32560/9 | Glad it’s working for you. As for the static build, I guess you’ll need to append -DTORCH_BUILD_STATIC_LIBS to the compiler flags when compiling your cpp extension that uses libtorch. In that case you could lower the batch size to 1 and check, if it’s still running out of memory.
If that’s the case, keep the batch siz... | 2,144 | {'text': ['Glad it’s working for you. As for the static build, I guess you’ll need to append -DTORCH_BUILD_STATIC_LIBS to the compiler flags when compiling your cpp extension that uses libtorch.'], 'answer_start': [2144]} |
About large datasize, 3D data and patches | Hello All,
I am working on 3D data of 114 images each of dimensions [180x256x256]. Since such a large image can not be fed directly to the network, I am using overlapping patches of size [64x64x64]. Now there are around 22,000 patches in total for 114 images. which can not be loaded into the Datalo… | 0 | 2021-02-22T18:37:49.414Z | In that case you could lower the batch size to 1 and check, if it’s still running out of memory.
If that’s the case, keep the batch size at 1, split the batch in the DataLoader loop in dim0 and loop over smaller input tensors.
Alternatively, you could also try to create the patches from each image… | 1 | 2021-02-25T06:11:14.138Z | https://discuss.pytorch.org/t/about-large-datasize-3d-data-and-patches/112630/10 | Glad it’s working for you. As for the static build, I guess you’ll need to append -DTORCH_BUILD_STATIC_LIBS to the compiler flags when compiling your cpp extension that uses libtorch. In that case you could lower the batch size to 1 and check, if it’s still running out of memory.
If that’s the case, keep the batch siz... | 1,256 | {'text': ['In that case you could lower the batch size to 1 and check, if it’s still running out of memory.\n\nIf that’s the case, keep the batch size at 1, split the batch in the DataLoader loop in dim0 and loop over smaller input tensors.\n\nAlternatively, you could also try to create the patches from each image&hell... |
Why is the output of a linear layer different when the batch size is 1? | Hi,
I am trying to debug a network and noticed that for some reason, the outputs of a linear layer are slightly different depending on the batch size of the input tensor.
Minimal working example:
import torch
from torch import nn
torch.manual_seed(72)
ll = nn.Linear(4, 8)
data = torch.rand((16, … | 0 | 2020-08-20T16:28:08.428Z | Hi,
From the point of view of floating point arithmetic, these two numbers are actually the same.
We are doing some extra optimizations when the batch one is 1 leading to a different order for some accumulations. And since floating point accumulation is not associative, you see these kinds of arti… | 1 | 2020-08-20T16:32:43.585Z | https://discuss.pytorch.org/t/why-is-the-output-of-a-linear-layer-different-when-the-batch-size-is-1/93515/2 | Glad it’s working for you. As for the static build, I guess you’ll need to append -DTORCH_BUILD_STATIC_LIBS to the compiler flags when compiling your cpp extension that uses libtorch. In that case you could lower the batch size to 1 and check, if it’s still running out of memory.
If that’s the case, keep the batch siz... | 493 | {'text': ['Hi,\n\nFrom the point of view of floating point arithmetic, these two numbers are actually the same.\n\nWe are doing some extra optimizations when the batch one is 1 leading to a different order for some accumulations. And since floating point accumulation is not associative, you see these kinds of arti&hell... |
Autograd isn't functioning when networks's parameters are taken from other networks | I have 3 networks with same architecture - A, B & C
The weights of C are set as convex combination of weights of A & B as shown below
for a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
c_param.data = weight * a_p… | 0 | 2018-10-17T05:24:07.480Z | Does the following work ?
for a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
# Don't use data of A and B params for the gradient to flow back to them
# Use .copy_ here to change the value of the params of C, d… | 1 | 2018-10-17T11:28:43.857Z | https://discuss.pytorch.org/t/autograd-isnt-functioning-when-networkss-parameters-are-taken-from-other-networks/27424/6 | Does the following work ?
for a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
# Don't use data of A and B params for the gradient to flow back to them
# Use .copy_ here to change the value of the params of C, d… <a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks fo... | 1,602 | {'text': ['Does the following work ?\n\nfor a_param, b_param, c_param in zip(a.parameters(), b.parameters(),\n\nc.parameters()):\n\n# Don't use data of A and B params for the gradient to flow back to them\n\n# Use .copy_ here to change the value of the params of C, d…'], 'answer_start': [1602]} |
Different forward and backward weights | I have a use case, where I need to use a different set of weights to compute the backward pass. An instance of where this is used is in this work <a href="https://www.nature.com/articles/ncomms13276" rel="nofollow noopener">https://www.nature.com/articles/ncomms13276</a> and numerous follow up works. Or this <a href="h... | 0 | 2019-08-07T16:24:44.090Z | <a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks for your reply. I actually figured out the right way to do this. I basically wrote my own Autograd Function class, similar to here: <a href="https://pytorch.org/docs/stable/notes/extending.html" rel="nofollow noopener">https://pytorch.org/docs/stable/notes/extend... | 1 | 2019-08-09T18:40:49.471Z | https://discuss.pytorch.org/t/different-forward-and-backward-weights/52800/3 | Does the following work ?
for a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
# Don't use data of A and B params for the gradient to flow back to them
# Use .copy_ here to change the value of the params of C, d… <a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks fo... | 1,062 | {'text': ['<a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks for your reply. I actually figured out the right way to do this. I basically wrote my own Autograd Function class, similar to here: <a href="https://pytorch.org/docs/stable/notes/extending.html" rel="nofollow noopener">https://pytorch.org/docs/stable/n... |
Why LSTM stops learning if I do not set a hidden state to zero? | If I remove 2 lines h0=torch.zeros.. c0=torch.zeros and batch_first=True my network stops learning.
I thought that a zero initial hidden state is by default in nn.LSTM if you don’t pass in a hidden state .
class ModelLSTMFSM(nn.Module):
def __init__(self, input_size=MAX_STRING_SIZE, hidden_siz… | 0 | 2020-08-13T17:58:49.308Z | [image] odats:
batch_first=True
If your remove batch_first=True it’s of course batch_first=False by default. In this case you would need to change out = self.fc(out[:, -1, :]) to out = self.fc(out[-1])
I don’t what you’re trying to learn and how your data looks like, but x = x.reshape(-1, I… | 1 | 2020-08-13T23:40:48.871Z | https://discuss.pytorch.org/t/why-lstm-stops-learning-if-i-do-not-set-a-hidden-state-to-zero/92725/2 | Does the following work ?
for a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
# Don't use data of A and B params for the gradient to flow back to them
# Use .copy_ here to change the value of the params of C, d… <a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks fo... | 702 | {'text': ['[image] odats:\n\nbatch_first=True\n\nIf your remove batch_first=True it’s of course batch_first=False by default. In this case you would need to change out = self.fc(out[:, -1, :]) to out = self.fc(out[-1])\n\nI don’t what you’re trying to learn and how your data looks like, but x = x.reshape(-1, I…... |
Help with writing out neural network inference test code | For <a href="https://gitlab.com/promach/Pruning-CNN/blob/master/SqueezeNet-Pruning/finetune.py#L261" rel="nofollow noopener">this SqueezeNet Pruning python code</a> , What do ‘batch’ and ‘label’ do ? I have <a href="https://paste.ubuntu.com/p/gWQvTYVv9W/" rel="nofollow noopener">printed them out</a>, but I cannot figur... | 0 | 2018-12-08T10:24:00.627Z | <a class="mention" href="/u/amrit_das">@Amrit_Das</a> <a class="mention" href="/u/alband">@albanD</a>
I have solved all problems and it looks like I can do the <a href="https://gist.github.com/promach/186438ad7d2e6c1ec15d9ce5d8435c13" rel="nofollow noopener">predict.py</a> without any more problems
Please see the upd... | 0 | 2018-12-23T12:55:37.593Z | https://discuss.pytorch.org/t/help-with-writing-out-neural-network-inference-test-code/31618/19 | <a class="mention" href="/u/amrit_das">@Amrit_Das</a> <a class="mention" href="/u/alband">@albanD</a>
I have solved all problems and it looks like I can do the <a href="https://gist.github.com/promach/186438ad7d2e6c1ec15d9ce5d8435c13" rel="nofollow noopener">predict.py</a> without any more problems
Please see the upd... | 2,010 | {'text': ['<a class="mention" href="/u/amrit_das">@Amrit_Das</a> <a class="mention" href="/u/alband">@albanD</a>\n\nI have solved all problems and it looks like I can do the <a href="https://gist.github.com/promach/186438ad7d2e6c1ec15d9ce5d8435c13" rel="nofollow noopener">predict.py</a> without any more problems\n\nPle... |
Module registering None parameters | I just want to make sure that I am understanding this part correctly. I see in the MultiheadAttention module (<a href="https://pytorch.org/docs/stable/_modules/torch/nn/modules/activation.html#MultiheadAttention" rel="nofollow noopener">https://pytorch.org/docs/stable/_modules/torch/nn/modules/activation.html#Multihead... | 0 | 2020-02-23T10:53:50.842Z | This means that they are defined but don’t have values.
This is useful to make sure that user code won’t try to use this attribute (as it is already reserved to be a Parameter) leading to weird behavior later.
Note that torch.empty(<size>) actually returns a Tensor, but it contains uninitialized m… | 1 | 2020-02-23T18:55:40.817Z | https://discuss.pytorch.org/t/module-registering-none-parameters/70757/2 | <a class="mention" href="/u/amrit_das">@Amrit_Das</a> <a class="mention" href="/u/alband">@albanD</a>
I have solved all problems and it looks like I can do the <a href="https://gist.github.com/promach/186438ad7d2e6c1ec15d9ce5d8435c13" rel="nofollow noopener">predict.py</a> without any more problems
Please see the upd... | 1,503 | {'text': ['This means that they are defined but don’t have values.\n\nThis is useful to make sure that user code won’t try to use this attribute (as it is already reserved to be a Parameter) leading to weird behavior later.\n\nNote that torch.empty(<size>) actually returns a Tensor, but it contains uninitialized ... |
Using ignite with torchtext | Is it possible to use ignite with torchtext similar to the MNIST example <a href="https://github.com/pytorch/ignite/blob/master/examples/mnist/mnist.py" rel="nofollow noopener">here</a>? In this example, once you have constructed your DataLoader and model, the code is essentially
model = Net()
opt = optim.SGD(model.p... | 0 | 2018-08-28T20:55:08.239Z | So, complete example with ignite will be
import torch
from torch import nn, optim
import torch.nn.functional as F
from torchtext.data import Field, BucketIterator
from torchtext.datasets import IMDB
from ignite.engine import Events, Engine, create_supervised_evaluator
from ignite.metrics import Ca… | 1 | 2018-08-29T21:09:13.824Z | https://discuss.pytorch.org/t/using-ignite-with-torchtext/24093/8 | <a class="mention" href="/u/amrit_das">@Amrit_Das</a> <a class="mention" href="/u/alband">@albanD</a>
I have solved all problems and it looks like I can do the <a href="https://gist.github.com/promach/186438ad7d2e6c1ec15d9ce5d8435c13" rel="nofollow noopener">predict.py</a> without any more problems
Please see the upd... | 813 | {'text': ['So, complete example with ignite will be\n\nimport torch\n\nfrom torch import nn, optim\n\nimport torch.nn.functional as F\n\nfrom torchtext.data import Field, BucketIterator\n\nfrom torchtext.datasets import IMDB\n\nfrom ignite.engine import Events, Engine, create_supervised_evaluator\n\nfrom ignite.metrics... |
RPC behavior difference between pytorch 1.7.0 vs 1.9.0 | Hello,
I have a use case where I create one process per available gpu along with multiple e.g. 15 processes that only run on the CPU. Here is the minimalistic working example that works in pytorch 1.7.0 but fails in 1.9.0. However, if I only use 3 or less GPUs rather than 4 while keeping the number… | 0 | 2021-06-22T23:01:14.080Z | Looks like this is an issue with the SHM transport. I bumped up the UV transport priority to over-shadow SHM, and this problem disappeared.
<a href="https://github.com/pytorch/pytorch/blob/ad1041576aeb7cd9f8065acb26b596ade8e6ecaa/torch/csrc/distributed/rpc/tensorpipe_agent.h#L46" target="_blank" rel="noopener nofollow... | 0 | 2021-06-23T21:00:06.579Z | https://discuss.pytorch.org/t/rpc-behavior-difference-between-pytorch-1-7-0-vs-1-9-0/124772/5 | Looks like this is an issue with the SHM transport. I bumped up the UV transport priority to over-shadow SHM, and this problem disappeared.
<a href="https://github.com/pytorch/pytorch/blob/ad1041576aeb7cd9f8065acb26b596ade8e6ecaa/torch/csrc/distributed/rpc/tensorpipe_agent.h#L46" target="_blank" rel="noopener nofollow... | 2,252 | {'text': ['Looks like this is an issue with the SHM transport. I bumped up the UV transport priority to over-shadow SHM, and this problem disappeared.\n\n<a href="https://github.com/pytorch/pytorch/blob/ad1041576aeb7cd9f8065acb26b596ade8e6ecaa/torch/csrc/distributed/rpc/tensorpipe_agent.h#L46" target="_blank" rel="noop... |
Very weird behavior when converting to torch.tensor | I’m pretty new to PyTorch so, please excuse me if this question is too remedial. I have the following code for inference of my trained model which takes an image, does some pre-processing on it, converts to a tensor and finally performs a forward pass through the network.
img = np.array(Image.op… | 0 | 2020-02-02T06:35:43.409Z | Hi,
The issue comes from the [None] I think. You change this line to first convert to a Tensor then .unsqueeze(0) to get the exact same result:
img_inp = torch.tensor(prepare_img(img).transpose(2, 0, 1)).float().unsqueeze(0) | 1 | 2020-02-03T16:00:57.207Z | https://discuss.pytorch.org/t/very-weird-behavior-when-converting-to-torch-tensor/68389/11 | Looks like this is an issue with the SHM transport. I bumped up the UV transport priority to over-shadow SHM, and this problem disappeared.
<a href="https://github.com/pytorch/pytorch/blob/ad1041576aeb7cd9f8065acb26b596ade8e6ecaa/torch/csrc/distributed/rpc/tensorpipe_agent.h#L46" target="_blank" rel="noopener nofollow... | 1,590 | {'text': ['Hi,\n\nThe issue comes from the [None] I think. You change this line to first convert to a Tensor then .unsqueeze(0) to get the exact same result:\n\nimg_inp = torch.tensor(prepare_img(img).transpose(2, 0, 1)).float().unsqueeze(0)'], 'answer_start': [1590]} |
How to resolve - RuntimeError: size mismatch, m1: [100 x 228], m2: [152 x 36] | Hi!
I am trying to build a Convolutional Neural Network and am facing a problem. The network has 3 Conv. layers, ReLU activated, pooled, batch normalized and then flattened. Here’s the model code:
in_features = 152 #in_features for Flatten(linear) layer calculated
class Net(nn.Module):
def __… | 0 | 2019-12-19T07:04:52.759Z | <a href="https://pytorch.org/docs/stable/nn.html?highlight=cross#torch.nn.CrossEntropyLoss" rel="nofollow noopener">Here</a>’s the documentation about CrossEntropyLoss.
outputs: shape (N, 3), type Float or Double or Half, without softmax
batch_y: shape (N,), type Long, the labels.
CrossEntropyLoss equals to LogSoftm... | 1 | 2019-12-19T08:42:34.410Z | https://discuss.pytorch.org/t/how-to-resolve-runtimeerror-size-mismatch-m1-100-x-228-m2-152-x-36/64503/9 | Looks like this is an issue with the SHM transport. I bumped up the UV transport priority to over-shadow SHM, and this problem disappeared.
<a href="https://github.com/pytorch/pytorch/blob/ad1041576aeb7cd9f8065acb26b596ade8e6ecaa/torch/csrc/distributed/rpc/tensorpipe_agent.h#L46" target="_blank" rel="noopener nofollow... | 691 | {'text': ['<a href="https://pytorch.org/docs/stable/nn.html?highlight=cross#torch.nn.CrossEntropyLoss" rel="nofollow noopener">Here</a>’s the documentation about CrossEntropyLoss.\n\noutputs: shape (N, 3), type Float or Double or Half, without softmax\n\nbatch_y: shape (N,), type Long, the labels.\n\nCrossEntropyLoss e... |
'shuffle' in dataloader | I noticed one strange thing that the loss value would be increased simply when I turn ‘shuffle’ off like below:
torch.utils.data.DataLoader(dataset_test, batch_size=batch_size, **shuffle=False**, num_workers=num_workers, drop_last=True) .
It’s about from 0.02 to 0.09. I didn’t change anything else… | 0 | 2020-05-21T15:28:02.945Z | Ow! In first post I asked about training loss or test loss, now I can get what you mean. Actually, after training for a while you are trying to validate your model so, this can be considered as testing. You have to use same configuration with testing which is using model.eval and torch.no_grad for l… | 1 | 2020-05-22T19:09:12.771Z | https://discuss.pytorch.org/t/shuffle-in-dataloader/82335/8 | Ow! In first post I asked about training loss or test loss, now I can get what you mean. Actually, after training for a while you are trying to validate your model so, this can be considered as testing. You have to use same configuration with testing which is using model.eval and torch.no_grad for l… Hi <a class... | 2,046 | {'text': ['Ow! In first post I asked about training loss or test loss, now I can get what you mean. Actually, after training for a while you are trying to validate your model so, this can be considered as testing. You have to use same configuration with testing which is using model.eval and torch.no_grad for l…'... |
Module output slightly off on Android | I’m learning how to port a module onto an Android app, but I’ve found that the output is a bit different on Android compared to the Python script.
Here’s my model:
class Dummy(nn.Module):
def __init__(self):
super(Dummy, self).__init__()
self.fc = nn.Linear(416 * 416 * 3, 10)
… | 0 | 2019-12-03T06:44:23.938Z | Hi <a class="mention" href="/u/minhduc0711">@minhduc0711</a> <a class="mention" href="/u/ljk53">@ljk53</a> I remember somebody posted a very similar issue for iOS couple of months ago, not sure it’s related, but worth looking into - <a href="https://github.com/pytorch/pytorch/issues/27813" rel="nofollow noopener">htt... | 1 | 2019-12-06T20:29:15.939Z | https://discuss.pytorch.org/t/module-output-slightly-off-on-android/62838/8 | Ow! In first post I asked about training loss or test loss, now I can get what you mean. Actually, after training for a while you are trying to validate your model so, this can be considered as testing. You have to use same configuration with testing which is using model.eval and torch.no_grad for l… Hi <a class... | 1,332 | {'text': ['Hi <a class="mention" href="/u/minhduc0711">@minhduc0711</a> <a class="mention" href="/u/ljk53">@ljk53</a> I remember somebody posted a very similar issue for iOS couple of months ago, not sure it’s related, but worth looking into - <a href="https://github.com/pytorch/pytorch/issues/27813" rel="nofollow no... |
Multi-GPU backward error | Hello,
A model has time-series structure.
So, I’ve split each time-step into each gpu, due to insufficiency of gpu memory.
But I got an error when calling loss.backward():
File "/home/xxx/.local/lib/python3.7/site-packages/torch/autograd/__init__.py", line 99, in backward
allow_unreachable=T… | 0 | 2020-03-16T17:24:19.251Z | Well the issue is that the backward formula has not been updated to reflect this… You can see <a href="https://github.com/pytorch/pytorch/blob/51d969e86ac0fad226f4e70889df0d3c6114ae4e/tools/autograd/templates/Functions.cpp#L523">here</a> that it assumes that all inputs are on the same device. | 1 | 2020-03-17T14:29:23.443Z | https://discuss.pytorch.org/t/multi-gpu-backward-error/73427/11 | Ow! In first post I asked about training loss or test loss, now I can get what you mean. Actually, after training for a while you are trying to validate your model so, this can be considered as testing. You have to use same configuration with testing which is using model.eval and torch.no_grad for l… Hi <a class... | 728 | {'text': ['Well the issue is that the backward formula has not been updated to reflect this… You can see <a href="https://github.com/pytorch/pytorch/blob/51d969e86ac0fad226f4e70889df0d3c6114ae4e/tools/autograd/templates/Functions.cpp#L523">here</a> that it assumes that all inputs are on the same device.'], 'answer_star... |
Pytorch DQN tutorial - where is autograd? | <a href="https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html" class="onebox" target="_blank" rel="nofollow noopener">https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html</a>
while the comments in the tutorial specify that autograd is used, it is never explicitly declared (that ... | 0 | 2018-08-19T21:03:08.328Z | I haven’t explored the tutorial in detail, but from what I know state_action_values are the output of the model, and should already require gradients.
Could you check it with state_action_values.requires_grad?
Also, if you re-wrap a Tensor, it will lose it’s associated computation graph and you ar… | 0 | 2018-08-19T23:32:37.046Z | https://discuss.pytorch.org/t/pytorch-dqn-tutorial-where-is-autograd/23460/6 | I haven’t explored the tutorial in detail, but from what I know state_action_values are the output of the model, and should already require gradients.
Could you check it with state_action_values.requires_grad?
Also, if you re-wrap a Tensor, it will lose it’s associated computation graph and you ar… Hi <a class... | 2,042 | {'text': ['I haven’t explored the tutorial in detail, but from what I know state_action_values are the output of the model, and should already require gradients.\n\nCould you check it with state_action_values.requires_grad?\n\nAlso, if you re-wrap a Tensor, it will lose it’s associated computation graph and you ar&hell... |
Concatenate two tensors with different sizes | Dear senior programmers,
I have obtained the following network structure by modifying someone’s else network. I have added the dilation keyword so as to obtain dilated convolutional layer. However, given that there were some concatenation in the “forward part” of the network, I have not been … | 0 | 2020-06-20T02:32:58.357Z | Hi <a class="mention" href="/u/patrice">@Patrice</a>,
*Rule1: If you want to concatenate the layer, it has to have only 1 dimension that is different from the other (i.e. NxDiff1xHxW and NxDiff2xHxW or NxCxDiff1xW and NxCxDiff2xW, etc)
in your case, what you are trying to do:
suppose our input x: 1x3x28x28
what you... | 0 | 2020-06-20T03:18:17.648Z | https://discuss.pytorch.org/t/concatenate-two-tensors-with-different-sizes/86136/2 | I haven’t explored the tutorial in detail, but from what I know state_action_values are the output of the model, and should already require gradients.
Could you check it with state_action_values.requires_grad?
Also, if you re-wrap a Tensor, it will lose it’s associated computation graph and you ar… Hi <a class... | 1,330 | {'text': ['Hi <a class="mention" href="/u/patrice">@Patrice</a>,\n\n*Rule1: If you want to concatenate the layer, it has to have only 1 dimension that is different from the other (i.e. NxDiff1xHxW and NxDiff2xHxW or NxCxDiff1xW and NxCxDiff2xW, etc)\n\nin your case, what you are trying to do:\n\nsuppose our input x: 1x... |
Initialize weights using the matrix multiplication result from two nn.Parameter | I have two tensor matrix, A $\in R^{nxm})$, and B $\in R^{mx1}$
a = nn.Parameter(A, requires_grad=True)
b = nn.Parameter(B, requires_grad=True)
Is it possible to use the matrix multiplication result from A*B = C $\in R^{nx1}$ as the initialize weights for the nn.Linear layer?
linear_weights = nn… | 0 | 2021-05-07T11:21:07.734Z | For your questions, just do some test to get the answer. Here is the code that supports the answers below.
import torch
class Model(torch.nn.Module) :
def __init__(self) :
super().__init__()
torch.manual_seed(0)
n, m = 1, 1
A = torch.rand((n, m))
B = torc… | 1 | 2021-05-07T14:07:02.764Z | https://discuss.pytorch.org/t/initialize-weights-using-the-matrix-multiplication-result-from-two-nn-parameter/120557/2 | I haven’t explored the tutorial in detail, but from what I know state_action_values are the output of the model, and should already require gradients.
Could you check it with state_action_values.requires_grad?
Also, if you re-wrap a Tensor, it will lose it’s associated computation graph and you ar… Hi <a class... | 658 | {'text': ['For your questions, just do some test to get the answer. Here is the code that supports the answers below.\n\nimport torch\n\nclass Model(torch.nn.Module) :\n\ndef __init__(self) :\n\nsuper().__init__()\n\ntorch.manual_seed(0)\n\nn, m = 1, 1\n\nA = torch.rand((n, m))\n\nB = torc…'], 'answer_start': [6... |
Deploy pytorch model on webcam | I am trying to deploy PyTorch classifier on webcam, but always getting errors, mostly “AttributeError: ‘collections.OrderedDict’ object has no attribute ‘load_state_dict’”. The classifier is a binary classifier. Saved the model as .pt file. Hope for your support to resolve the issue. Here are the co… | 0 | 2021-02-02T16:01:34.797Z | Ok then you still need to define the model in this file and then do load state dict. The model load function won’t work because you didn’t save the entire model. | 0 | 2021-02-02T16:27:56.775Z | https://discuss.pytorch.org/t/deploy-pytorch-model-on-webcam/110715/4 | Ok then you still need to define the model in this file and then do load state dict. The model load function won’t work because you didn’t save the entire model. <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/d/5/d5afba2458d90f4466709e074c7639360021f7a9.png" data-download-href="https:... | 1,858 | {'text': ['Ok then you still need to define the model in this file and then do load state dict. The model load function won’t work because you didn’t save the entire model.'], 'answer_start': [1858]} |
No embbeding.grad.data | as mentioned in the title, no grad.data is present in nn.embedding, so how do we train the embeddings? | 0 | 2020-01-06T21:39:06.716Z | <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/d/5/d5afba2458d90f4466709e074c7639360021f7a9.png" data-download-href="https://discuss.pytorch.org/uploads/default/d5afba2458d90f4466709e074c7639360021f7a9" title="Screenshot_2020-01-07 Google Colaboratory(3)">[Screenshot_2020-01-07 Google... | 0 | 2020-01-07T09:20:41.539Z | https://discuss.pytorch.org/t/no-embbeding-grad-data/65940/16 | Ok then you still need to define the model in this file and then do load state dict. The model load function won’t work because you didn’t save the entire model. <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/d/5/d5afba2458d90f4466709e074c7639360021f7a9.png" data-download-href="https:... | 1,091 | {'text': ['<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/d/5/d5afba2458d90f4466709e074c7639360021f7a9.png" data-download-href="https://discuss.pytorch.org/uploads/default/d5afba2458d90f4466709e074c7639360021f7a9" title="Screenshot_2020-01-07 Google Colaboratory(3)">[Screenshot_2020-0... |
Cannot import name 'random_split' | I got this
>>> from torch.utils.data import Dataset, DataLoader, random_split
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'random_split'
error
It means my installation of torch exists some issue?
torchvision ... | 0 | 2020-07-26T15:09:41.383Z | I used conda and tried to install the updated version:
conda install pytorch==1.1.0 torchvision==0.3.0 cudatoolkit=9.0 -c pytorch
The problem solved. | 0 | 2020-07-26T15:36:39.462Z | https://discuss.pytorch.org/t/cannot-import-name-random-split/90587/2 | Ok then you still need to define the model in this file and then do load state dict. The model load function won’t work because you didn’t save the entire model. <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/d/5/d5afba2458d90f4466709e074c7639360021f7a9.png" data-download-href="https:... | 756 | {'text': ['I used conda and tried to install the updated version:\n\nconda install pytorch==1.1.0 torchvision==0.3.0 cudatoolkit=9.0 -c pytorch\n\nThe problem solved.'], 'answer_start': [756]} |
Runtime error while running a python code(Input and Target does not match) | I have attached the screenshots of my code and the error. Can anyone tell me where I am going wrong?
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/0/0fd1dbe9aa2f7e8d1729dd3a4589bdc6ae4d30c3.png" data-download-href="https://discuss.pytorch.org/uploads/default/0fd1dbe9aa2f7e8d1729dd3a... | 0 | 2018-08-30T11:54:59.802Z | You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3.
You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem.
Are you dealing with gray-scale imag… | 1 | 2018-08-31T09:18:03.419Z | https://discuss.pytorch.org/t/runtime-error-while-running-a-python-code-input-and-target-does-not-match/24204/4 | You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3.
You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem.
Are you dealing with gray-scale imag… To make sur... | 1,814 | {'text': ['You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3.\n\nYou can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem.\n\nAre you dealing with gray-scale imag&hell... |
Add neurons to an existing layer | I am trying an approach to solve a specific problem that requires me to add n neurons to the last layer of a pre-trained model. The tricky part is that it has to be on the same layer. I found an example in the forums here: <a href="https://discuss.pytorch.org/t/possible-to-add-initialize-new-nodes-to-hidden-layer-partw... | 0 | 2020-05-03T22:53:45.720Z | To make sure the old weights are present, you could simply print the old and new weight tensor and compare them or use a proper comparison via old_weight == new_weight[:, :old_weight_num].
I’m not sure how ix etc. is defined, so cannot see, if the creation is correct.
I would recommend to avoid us… | 0 | 2020-05-04T08:39:00.614Z | https://discuss.pytorch.org/t/add-neurons-to-an-existing-layer/79583/2 | You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3.
You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem.
Are you dealing with gray-scale imag… To make sur... | 1,216 | {'text': ['To make sure the old weights are present, you could simply print the old and new weight tensor and compare them or use a proper comparison via old_weight == new_weight[:, :old_weight_num].\n\nI’m not sure how ix etc. is defined, so cannot see, if the creation is correct.\n\nI would recommend to avoid us&hell... |
Torch.cuda.is_available() returns False on ssh server with NVIDIA GPU | I am using my Institute GPU through ssh server (Pardon the terms, I am a newbie). I have been trying for so long but PyTorch torch.cuda.is_available() returns False.
Here is the output of nvidia-smi:
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/e/9/e90006b08d8987e0ece906dc6d5314d3... | 0 | 2021-11-02T21:33:52.583Z | I finally solved the problem. The problem was not due to drivers or anything. My college senior gave me a piece of code to write at the beginning of the file that I wanted to run. Here is the code:
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"... | 0 | 2021-11-05T20:16:49.698Z | https://discuss.pytorch.org/t/torch-cuda-is-available-returns-false-on-ssh-server-with-nvidia-gpu/135762/14 | You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3.
You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem.
Are you dealing with gray-scale imag… To make sur... | 618 | {'text': ['I finally solved the problem. The problem was not due to drivers or anything. My college senior gave me a piece of code to write at the beginning of the file that I wanted to run. Here is the code:\n\nimport os\n\nos.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"\n\nos.environ["CUDA_VIS... |
RuntimeError: CUDA out of memory. Tried to allocate 2.18 GiB (GPU 0; 15.92 GiB total capacity; 13.71 GiB already allocated; 1.25 GiB free; 13.74 GiB reserved in total by PyTorch) | File "d:\anaconda3\lib\site-packages\fire\core.py", line 138, in Fire
component_trace = _Fire(component, args, parsed_flag_args, context, name)
File "d:\anaconda3\lib\site-packages\fire\core.py", line 468, in _Fire
target=component.__name__)
File "d:\anaconda3\lib\site-packages\fire\core&he... | 0 | 2020-11-14T08:20:17.681Z | [image] tianle-BigRice:
I don’t understand why the new data set can’t work properly, is it because the input and output are too large? But I also reduced the batchsize and still can’t run
Yes, most likely. If neither a batch size of 1 can run nor you are able to use checkpointing, you could t… | 0 | 2020-11-16T08:36:04.795Z | https://discuss.pytorch.org/t/runtimeerror-cuda-out-of-memory-tried-to-allocate-2-18-gib-gpu-0-15-92-gib-total-capacity-13-71-gib-already-allocated-1-25-gib-free-13-74-gib-reserved-in-total-by-pytorch/102762/16 | [image] tianle-BigRice:
I don’t understand why the new data set can’t work properly, is it because the input and output are too large? But I also reduced the batchsize and still can’t run
Yes, most likely. If neither a batch size of 1 can run nor you are able to use checkpointing, you could t… Problem is the d... | 1,936 | {'text': ['[image] tianle-BigRice:\n\nI don’t understand why the new data set can’t work properly, is it because the input and output are too large? But I also reduced the batchsize and still can’t run\n\nYes, most likely. If neither a batch size of 1 can run nor you are able to use checkpointing, you could t…']... |
Faster RCNN extremely slow training | Starting from <a href="https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html" rel="nofollow noopener">this</a> tutorial, I am trying to train a Faster R-CNN ResNet50 network on a custom dataset.
The train partition contains 26188 images that are 512x512 but, when loaded, they get resized at 240x240. To ... | 0 | 2020-06-05T16:57:37.960Z | Problem is the dataloader, I have no idea why. Using a custom generator works fine. | 0 | 2020-06-05T22:05:10.571Z | https://discuss.pytorch.org/t/faster-rcnn-extremely-slow-training/84321/3 | [image] tianle-BigRice:
I don’t understand why the new data set can’t work properly, is it because the input and output are too large? But I also reduced the batchsize and still can’t run
Yes, most likely. If neither a batch size of 1 can run nor you are able to use checkpointing, you could t… Problem is the d... | 1,272 | {'text': ['Problem is the dataloader, I have no idea why. Using a custom generator works fine.'], 'answer_start': [1272]} |
Which is the right loss? | Should i use softmax on the last layer with Cross entropy loss for a binary classification? Is there a cheat sheet out there on how to pair up the last layer and loss criteria? | 0 | 2019-11-15T22:52:16.580Z | You can use:
raw logits (no activation function at the end, just the raw output of the last layer) + nn.CrossEntropyLoss
F_log_softmax on the model output + nn.NLLLoss
If you need to see the probabilities for debug/printing purpose:
use softmax and print the output
use exp() and print the ou… | 0 | 2019-11-16T01:22:09.545Z | https://discuss.pytorch.org/t/which-is-the-right-loss/61135/11 | [image] tianle-BigRice:
I don’t understand why the new data set can’t work properly, is it because the input and output are too large? But I also reduced the batchsize and still can’t run
Yes, most likely. If neither a batch size of 1 can run nor you are able to use checkpointing, you could t… Problem is the d... | 388 | {'text': ['You can use:\n\nraw logits (no activation function at the end, just the raw output of the last layer) + nn.CrossEntropyLoss\n\nF_log_softmax on the model output + nn.NLLLoss\n\nIf you need to see the probabilities for debug/printing purpose:\n\nuse softmax and print the output\n\nuse exp() and print the ou&h... |
Size Mismatch in conv2d | im facing a runtime error when trying to implement cnn <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/c/4/c4065ea799f7fbefd745e8a2cc7c8ec2e1035f29.png" data-download-href="https://discuss.pytorch.org/uploads/default/c4065ea799f7fbefd745e8a2cc7c8ec2e1035f29" title="Screenshot from 20... | 0 | 2020-04-06T23:59:34.785Z | Permute the input, so that the channel dimension is in dim1 and set the in_channels to the number of input channels, not the height. | 0 | 2020-04-07T03:28:30.728Z | https://discuss.pytorch.org/t/size-mismatch-in-conv2d/75627/9 | Permute the input, so that the channel dimension is in dim1 and set the in_channels to the number of input channels, not the height. This is how I’m sampling equally from each class of the dataset
def _create_samples(dataset, num_classes):
N = int(np.ceil(k_samp / num_classes)) # k_samp is the number of total samples... | 1,386 | {'text': ['Permute the input, so that the channel dimension is in dim1 and set the in_channels to the number of input channels, not the height.'], 'answer_start': [1386]} |
How can I sample from the EMNIST letters dataset? | Hi,
I am trying to create a smaller dataset from the EMNIST letters dataset by sampling x samples from each class of the dataset.
I’ve loaded the dataset using datasets.EMNIST(root='./emnist_data/', split = 'letters', train=True, transform=transform, download=True)
I have tried using the built in&hel... | 0 | 2021-05-25T20:38:03.817Z | This is how I’m sampling equally from each class of the dataset
def _create_samples(dataset, num_classes):
N = int(np.ceil(k_samp / num_classes)) # k_samp is the number of total samples I need
indices = np.arange(len(dataset))
train_indices, test_indices = train_test_split(… | 0 | 2021-06-01T17:40:57.254Z | https://discuss.pytorch.org/t/how-can-i-sample-from-the-emnist-letters-dataset/122355/11 | Permute the input, so that the channel dimension is in dim1 and set the in_channels to the number of input channels, not the height. This is how I’m sampling equally from each class of the dataset
def _create_samples(dataset, num_classes):
N = int(np.ceil(k_samp / num_classes)) # k_samp is the number of total samples... | 826 | {'text': ['This is how I’m sampling equally from each class of the dataset\n\ndef _create_samples(dataset, num_classes):\n\nN = int(np.ceil(k_samp / num_classes)) # k_samp is the number of total samples I need\n\nindices = np.arange(len(dataset))\n\ntrain_indices, test_indices = train_test_split(…'], 'answer_sta... |
[Urgent Help required] Installed self-compiled PyTorch CUDA-enabled Pointnet2 Extension Module have conflicting CUDA library (.so file) version requirements when imported in Python 3.6 | Hello, first time posting here so apologies firsthand if it’s an already asked question or any mistakes made.
I’m currently trying to compile a pointnet2 PyTorch implementation as a function library/module from <a href="https://github.com/qiqihaer/3DSSD-pytorch" rel="noopener nofollow ugc">this repo</a> which borrowed... | 0 | 2020-12-15T21:00:41.793Z | Hi, sorry for the very late reply as I was trying to resolve the issue on my end.
I believe I’ve sort of resolved the issue, apparently for whatever reason the NVCC didn’t trigger for the <a href="https://github.com/qiqihaer/3DSSD-pytorch" rel="noopener nofollow ugc">3DSSD repo</a> which I was focusing on, but instead... | 0 | 2020-12-18T09:38:21.396Z | https://discuss.pytorch.org/t/urgent-help-required-installed-self-compiled-pytorch-cuda-enabled-pointnet2-extension-module-have-conflicting-cuda-library-so-file-version-requirements-when-imported-in-python-3-6/106247/9 | Permute the input, so that the channel dimension is in dim1 and set the in_channels to the number of input channels, not the height. This is how I’m sampling equally from each class of the dataset
def _create_samples(dataset, num_classes):
N = int(np.ceil(k_samp / num_classes)) # k_samp is the number of total samples... | 420 | {'text': ['Hi, sorry for the very late reply as I was trying to resolve the issue on my end.\n\nI believe I’ve sort of resolved the issue, apparently for whatever reason the NVCC didn’t trigger for the <a href="https://github.com/qiqihaer/3DSSD-pytorch" rel="noopener nofollow ugc">3DSSD repo</a> which I was focusing on... |
Model Loading issue in android | My model contains nn.Functional.interpolate layer and it is converted properly to .pt model using jit.
But Loading same model in android giving issues.
This is happening in case of interpolate layer only.
Edit - Error trace
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.p… | 0 | 2019-11-14T15:13:35.986Z | For anyone who is following this thread, the issue was resolved at <a href="https://github.com/pytorch/pytorch/issues/29806" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/29806</a> | 0 | 2019-12-03T19:26:40.604Z | https://discuss.pytorch.org/t/model-loading-issue-in-android/60990/10 | For anyone who is following this thread, the issue was resolved at <a href="https://github.com/pytorch/pytorch/issues/29806" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/29806</a> The master is the current actively developed branch. So it is newer than 0.2.0. The patch is after 0.2.0 so it is only ... | 1,896 | {'text': ['For anyone who is following this thread, the issue was resolved at <a href="https://github.com/pytorch/pytorch/issues/29806" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/29806</a>'], 'answer_start': [1896]} |
Improved WGAN Scatter is not differentiable twice | I get Scatter is not differentiable twice when trying to backward the gradient penalty suggested in the WGAN paper. I’m running the latest version of pytorch and the models are using DataParallel!
# discriminator
d_real_out = disc(mixed, clean)
d_fake = disc(fake)
loss_real, loss_fa… | 0 | 2017-10-27T20:30:33.719Z | The master is the current actively developed branch. So it is newer than 0.2.0. The patch is after 0.2.0 so it is only in master right now. Sorry for letting you have to build from source to solve this. | 0 | 2017-10-30T19:53:52.661Z | https://discuss.pytorch.org/t/improved-wgan-scatter-is-not-differentiable-twice/9161/6 | For anyone who is following this thread, the issue was resolved at <a href="https://github.com/pytorch/pytorch/issues/29806" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/29806</a> The master is the current actively developed branch. So it is newer than 0.2.0. The patch is after 0.2.0 so it is only ... | 1,149 | {'text': ['The master is the current actively developed branch. So it is newer than 0.2.0. The patch is after 0.2.0 so it is only in master right now. Sorry for letting you have to build from source to solve this.'], 'answer_start': [1149]} |
Training data becomes nan after several epochs | Hi everyone,
In a semantic segmentation network, I use a type of data, normalized between 0 and 1, saved as pickle. After 23 epochs, at least one sample of this data becomes nan before entering to the network as input. By changing learning rate nothing changes, but by changing one of the convolutio… | 0 | 2021-07-14T18:24:51.521Z | Thanks to you, I found out that padding and interpolation inside resizing creates nan values in the segmented input image. By eliminating these two transformations network works well! | 0 | 2021-07-19T19:49:52.229Z | https://discuss.pytorch.org/t/training-data-becomes-nan-after-several-epochs/126760/11 | For anyone who is following this thread, the issue was resolved at <a href="https://github.com/pytorch/pytorch/issues/29806" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/29806</a> The master is the current actively developed branch. So it is newer than 0.2.0. The patch is after 0.2.0 so it is only ... | 404 | {'text': ['Thanks to you, I found out that padding and interpolation inside resizing creates nan values in the segmented input image. By eliminating these two transformations network works well!'], 'answer_start': [404]} |
'tuple' object is not callable | This was the error:
----> 1 model_conv = train_model(model_conv,train_dl, val_dl, criterion, optimizer_conv,exp_lr_scheduler, num_epochs=25)
4 frames
<ipython-input-43-2490278d3bb0> in train_model(model, train_dl, val_dl, criterion, optimizer, scheduler, num_epochs)
13 print('-' * 10)&helli... | 0 | 2022-03-25T09:57:47.224Z | After deleting the comma at the end of your transform definition I do not get that error (I do get OTHER errors, but not the same).
Can you confirm if its the same error in the same line? | 1 | 2022-03-25T12:17:55.565Z | https://discuss.pytorch.org/t/tuple-object-is-not-callable/147411/8 | After deleting the comma at the end of your transform definition I do not get that error (I do get OTHER errors, but not the same).
Can you confirm if its the same error in the same line? HI,
You can check the doc about how we manage the CUDA memory <a href="https://pytorch.org/docs/stable/notes/cuda.html#memory-mana... | 1,174 | {'text': ['After deleting the comma at the end of your transform definition I do not get that error (I do get OTHER errors, but not the same).\n\nCan you confirm if its the same error in the same line?'], 'answer_start': [1174]} |
CUDA Out of Memory even though the model and input fit into memory | there’s this weird thing happening with me, i have a custom Residual UNet, that has about 34M params, and 133MB, and input is of batch size 512, (6, 192, 192), everything should fit into memory, although it doesn’t, it crashes consuming the entire gpu memory
here’s the model: <a href="https://gist.github.com/satyajitg... | 0 | 2020-05-18T11:04:23.065Z | HI,
You can check the doc about how we manage the CUDA memory <a href="https://pytorch.org/docs/stable/notes/cuda.html#memory-management">here</a>.
In particular, this will explain why the memory is not returned to the OS when you delete your model.
For trying batch sizes, there are many things that can change the w... | 1 | 2020-05-18T15:27:01.289Z | https://discuss.pytorch.org/t/cuda-out-of-memory-even-though-the-model-and-input-fit-into-memory/81798/6 | After deleting the comma at the end of your transform definition I do not get that error (I do get OTHER errors, but not the same).
Can you confirm if its the same error in the same line? HI,
You can check the doc about how we manage the CUDA memory <a href="https://pytorch.org/docs/stable/notes/cuda.html#memory-mana... | 776 | {'text': ['HI,\n\nYou can check the doc about how we manage the CUDA memory <a href="https://pytorch.org/docs/stable/notes/cuda.html#memory-management">here</a>.\n\nIn particular, this will explain why the memory is not returned to the OS when you delete your model.\n\nFor trying batch sizes, there are many things that... |
[Memory problem] Replace input by another tensor in the forward pass | Hi everyone,
I am trying to extend a Linear Function by the following link: <a href="https://pytorch.org/docs/stable/autograd.html#module-torch.autograd" rel="nofollow noopener"> torch.autograd </a>.
In the forward pass, my goal is to discard the input and replace it by another tensors, i.e., a, b, c, after performi... | 0 | 2019-11-07T17:11:54.793Z | I think my comment above is relevant:
Here, the input to your model, data is the same Tensor as input that you get during forward. But even if you don’t store input, you still hold onto data in your training loop, so it cannot be freed.
Changing to
output = mode(data)
del data
should help.
Als… | 1 | 2019-11-08T15:36:51.851Z | https://discuss.pytorch.org/t/memory-problem-replace-input-by-another-tensor-in-the-forward-pass/60298/9 | After deleting the comma at the end of your transform definition I do not get that error (I do get OTHER errors, but not the same).
Can you confirm if its the same error in the same line? HI,
You can check the doc about how we manage the CUDA memory <a href="https://pytorch.org/docs/stable/notes/cuda.html#memory-mana... | 578 | {'text': ['I think my comment above is relevant:\n\nHere, the input to your model, data is the same Tensor as input that you get during forward. But even if you don’t store input, you still hold onto data in your training loop, so it cannot be freed.\n\nChanging to\n\noutput = mode(data)\n\ndel data\n\nshould help.\n\n... |
Extract deep features from inception_v3 | When I tried to extract deep features using trained inception_v3 model
model = torchvision.models.inception_v3(pretrained=True)
model.fc = nn.Linear(2048, 1)
model.load_state_dict(torch.load(’./models/Beauty_inception_reg.pt’))
feature_extractor = torch.nn.Sequential(*list(model.children())[:-1]… | 0 | 2020-06-01T23:29:53.451Z | Wrapping child modules into an nn.Sequential container will only work in simple use cases, where each module is called sequentially and no functional calls are used in the forward method.
As you can see <a href="https://github.com/pytorch/vision/blob/34810c0c8e192caf29f05d7e4a02f36a9e9ebc02/torchvision/models/inceptio... | 2 | 2020-06-02T07:41:23.846Z | https://discuss.pytorch.org/t/extract-deep-features-from-inception-v3/83774/2 | Wrapping child modules into an nn.Sequential container will only work in simple use cases, where each module is called sequentially and no functional calls are used in the forward method.
As you can see <a href="https://github.com/pytorch/vision/blob/34810c0c8e192caf29f05d7e4a02f36a9e9ebc02/torchvision/models/inceptio... | 1,772 | {'text': ['Wrapping child modules into an nn.Sequential container will only work in simple use cases, where each module is called sequentially and no functional calls are used in the forward method.\n\nAs you can see <a href="https://github.com/pytorch/vision/blob/34810c0c8e192caf29f05d7e4a02f36a9e9ebc02/torchvision/mo... |
Optimizer dont update weights | Hello, thank for attention I ran into the following problem, the weights before and after did not change, here is the code:
class fastRCNN(torch.nn.Module):
def __init__(self, params):
super(fastRCNN, self).__init__()
# roi pooling size
self.rsize = params['roi']['output_size']
… | 0 | 2020-05-01T00:36:55.831Z | Have you checked the input to torch.log? As mentioned before, negative inputs will give you Nan outputs.
This will also detach your tensors and your model won’t get valid gradients. You should not recreate tensors, but use them directly.
See 2. | 2 | 2020-05-02T03:54:39.389Z | https://discuss.pytorch.org/t/optimizer-dont-update-weights/79190/10 | Wrapping child modules into an nn.Sequential container will only work in simple use cases, where each module is called sequentially and no functional calls are used in the forward method.
As you can see <a href="https://github.com/pytorch/vision/blob/34810c0c8e192caf29f05d7e4a02f36a9e9ebc02/torchvision/models/inceptio... | 1,331 | {'text': ['Have you checked the input to torch.log? As mentioned before, negative inputs will give you Nan outputs.\n\nThis will also detach your tensors and your model won’t get valid gradients. You should not recreate tensors, but use them directly.\n\nSee 2.'], 'answer_start': [1331]} |
Model Loading issue in iOS | I get the following error when trying to initialize a traced model with the iOS framework:
PyTorchDemo[25132:6735005] false CHECK FAILED at /Users/distiller/project/c10/core/Backend.h (tensorTypeIdToBackend at /Users/distiller/project/c10/core/Backend.h:106)
(no backtrace available)
The error app… | 0 | 2019-12-06T00:30:49.676Z | Hi <a class="mention" href="/u/kennywalker">@kennywalker</a>, we’re going to publish 1.4 in Jan (Hopefully). Could you give a solution mark on this? If there is any questions, feel free to leave a comment. | 0 | 2019-12-10T19:12:32.808Z | https://discuss.pytorch.org/t/model-loading-issue-in-ios/63179/7 | Wrapping child modules into an nn.Sequential container will only work in simple use cases, where each module is called sequentially and no functional calls are used in the forward method.
As you can see <a href="https://github.com/pytorch/vision/blob/34810c0c8e192caf29f05d7e4a02f36a9e9ebc02/torchvision/models/inceptio... | 692 | {'text': ['Hi <a class="mention" href="/u/kennywalker">@kennywalker</a>, we’re going to publish 1.4 in Jan (Hopefully). Could you give a solution mark on this? If there is any questions, feel free to leave a comment.'], 'answer_start': [692]} |
How to backward the average of multiple losses? | I am trying to train a model using multiple data loaders.
The code I use is as follows:
loss_list = list()
for epoch in range(cfg.start_epoch, cfg.max_epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
losses_exist = AverageMe… | 0 | 2021-03-09T09:22:01.794Z | So you wanted to do is multi-scale training?
Then perhaps you could do:
for batch1, batch2, batch3 in zip(daloaders[0], dataloaders[1], dataloaders[2]):
input1, label1 = batch1
input2, label2 = batch2
input3, label3 = batch3
pred1 = model(input1)
pred2 = model(input2)
pred… | 0 | 2021-03-10T06:47:15.200Z | https://discuss.pytorch.org/t/how-to-backward-the-average-of-multiple-losses/114175/13 | So you wanted to do is multi-scale training?
Then perhaps you could do:
for batch1, batch2, batch3 in zip(daloaders[0], dataloaders[1], dataloaders[2]):
input1, label1 = batch1
input2, label2 = batch2
input3, label3 = batch3
pred1 = model(input1)
pred2 = model(input2)
pred… Here you go
import torch
fro... | 1,796 | {'text': ['So you wanted to do is multi-scale training?\n\nThen perhaps you could do:\n\nfor batch1, batch2, batch3 in zip(daloaders[0], dataloaders[1], dataloaders[2]):\n\ninput1, label1 = batch1\n\ninput2, label2 = batch2\n\ninput3, label3 = batch3\n\npred1 = model(input1)\n\npred2 = model(input2)\n\npred…'], ... |
Modifying the state_dict changes the values of the parameters | Hello,
I am currently trying to map the parameters of a pre-trained network to another network of the exact same architecture, but with a different arrangement of sub-modules. Here is how I am doing it:
def _load_parameters(self):
self.old_state_dict = torch.load(f = self.param_pa… | 0 | 2020-07-13T17:52:43.417Z | Here you go
import torch
from torch import nn
import csv
import copy
class Net(nn.Module):
def __init__(self, old_state_dict, state_dict_map):
# run nn.Module's constructor
super(Net, self).__init__()
# --------------------------------------------------------------… | 0 | 2020-07-18T16:04:29.649Z | https://discuss.pytorch.org/t/modifying-the-state-dict-changes-the-values-of-the-parameters/89030/10 | So you wanted to do is multi-scale training?
Then perhaps you could do:
for batch1, batch2, batch3 in zip(daloaders[0], dataloaders[1], dataloaders[2]):
input1, label1 = batch1
input2, label2 = batch2
input3, label3 = batch3
pred1 = model(input1)
pred2 = model(input2)
pred… Here you go
import torch
fro... | 1,188 | {'text': ['Here you go\n\nimport torch\n\nfrom torch import nn\n\nimport csv\n\nimport copy\n\nclass Net(nn.Module):\n\ndef __init__(self, old_state_dict, state_dict_map):\n\n# run nn.Module's constructor\n\nsuper(Net, self).__init__()\n\n# --------------------------------------------------------------…'], '... |
Training slows down with loop like x=f(x) | Here x is a tensor, f is an nn.Module model. Both are on cuda:
x = x.to(torch.device('cuda'))
f = f.to(torch.device('cuda'))
The main loop looks like this:
while(some condition):
x = f(x)
I noticed that pretty quickly training slows down. I believe this feedforward mechanism could be a pro… | 0 | 2019-10-29T10:31:17.539Z | yep
[image]
<a href="https://discuss.pytorch.org/t/help-clarifying-repackage-hidden-in-word-language-model/226/2">Help clarifying repackage_hidden in word_language_model</a>
Every variable has a .creator attribute that is an entry point to a graph, that encodes the operation history. This allows autograd to replay i... | 0 | 2019-10-29T21:49:43.751Z | https://discuss.pytorch.org/t/training-slows-down-with-loop-like-x-f-x/59454/12 | So you wanted to do is multi-scale training?
Then perhaps you could do:
for batch1, batch2, batch3 in zip(daloaders[0], dataloaders[1], dataloaders[2]):
input1, label1 = batch1
input2, label2 = batch2
input3, label3 = batch3
pred1 = model(input1)
pred2 = model(input2)
pred… Here you go
import torch
fro... | 577 | {'text': ['yep\n\n[image]\n\n<a href="https://discuss.pytorch.org/t/help-clarifying-repackage-hidden-in-word-language-model/226/2">Help clarifying repackage_hidden in word_language_model</a>\n\nEvery variable has a .creator attribute that is an entry point to a graph, that encodes the operation history. This allows aut... |
Higher Order Derivatives - Meta Learning | I am trying to write code for some of the Meta-Learning algorithms. I understand that there are a few packages available for easy and hassle-free implementation of Meta-Learning algorithms (<a href="https://github.com/facebookresearch/higher" rel="nofollow noopener">higher</a>, <a href="https://github.com/tristandeleu/... | 0 | 2020-08-17T06:48:10.762Z | I think what you are trying to say is that if I want the nn.Parameters to “record” history, the example I talked about above uses register_buffer instead of nn.Parameter as a neat hack.
I think it’s starting to make sense now. Here’s what I think is going on (code: <a href="https://github.com/danieltan07/learning-to-r... | 0 | 2020-09-02T12:52:23.521Z | https://discuss.pytorch.org/t/higher-order-derivatives-meta-learning/93051/7 | I think what you are trying to say is that if I want the nn.Parameters to “record” history, the example I talked about above uses register_buffer instead of nn.Parameter as a neat hack.
I think it’s starting to make sense now. Here’s what I think is going on (code: <a href="https://github.com/danieltan07/learning-to-r... | 1,928 | {'text': ['I think what you are trying to say is that if I want the nn.Parameters to “record” history, the example I talked about above uses register_buffer instead of nn.Parameter as a neat hack.\n\nI think it’s starting to make sense now. Here’s what I think is going on (code: <a href="https://github.com/danieltan07/... |
Segfault in libtorch_cpu running fastai | Hello, all,
I’m trying to get a local install of fastai running…I was hoping that using the fastai docker images would spare me having to install and manage the fastai and pytorch libraries myself, but I’m running into a segfault in pytorch, which I’m not sure how to fix.
My setup:
CPU: Intel® Co… | 1 | 2020-10-07T14:35:55.392Z | Thanks everyone for your help.
Fastai patched this weekend to support torch 1.7, and that seems to have been enough to support the master branch of pytorch. I manually built torch and torchvision from master, with ENABLE_NNPACK=0 set as an environment variable to avoid the “Unsupported Hardware” er… | 0 | 2020-11-01T19:24:21.772Z | https://discuss.pytorch.org/t/segfault-in-libtorch-cpu-running-fastai/98570/11 | I think what you are trying to say is that if I want the nn.Parameters to “record” history, the example I talked about above uses register_buffer instead of nn.Parameter as a neat hack.
I think it’s starting to make sense now. Here’s what I think is going on (code: <a href="https://github.com/danieltan07/learning-to-r... | 1,459 | {'text': ['Thanks everyone for your help.\n\nFastai patched this weekend to support torch 1.7, and that seems to have been enough to support the master branch of pytorch. I manually built torch and torchvision from master, with ENABLE_NNPACK=0 set as an environment variable to avoid the “Unsupported Hardware” er&hellip... |
Model not being trained | I’m trying to train a model for image classification. However, the training just doesn’t take place.
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2)
self.conv2 = nn.Conv2d(64, 192, kernel_size=7, … | 1 | 2019-09-14T03:42:12.735Z | can you try defining optim after moving model to gpu?
model.to(device)
optimizer = optim.Adam(model.parameters()) | 0 | 2019-09-14T17:43:36.291Z | https://discuss.pytorch.org/t/model-not-being-trained/55904/13 | I think what you are trying to say is that if I want the nn.Parameters to “record” history, the example I talked about above uses register_buffer instead of nn.Parameter as a neat hack.
I think it’s starting to make sense now. Here’s what I think is going on (code: <a href="https://github.com/danieltan07/learning-to-r... | 804 | {'text': ['can you try defining optim after moving model to gpu?\n\nmodel.to(device)\n\noptimizer = optim.Adam(model.parameters())'], 'answer_start': [804]} |
SLURM cluster CUDA error: all CUDA-capable devices are busy or unavailable | I’m using a pre-trained Inception network to get some GAN metrics, and I have the following code to move the model to a GPU for evaluation:
def __init__(self, ...):
...
self._model = InceptionV3(...)
if cuda.is_available():
self._model.to('cuda')
When I run this code on an HPC,… | 0 | 2021-03-12T18:47:47.490Z | I think I resolved it. I registered the Inception network as a part of my main model and then they were able to be on the same device. | 0 | 2021-04-09T19:14:41.452Z | https://discuss.pytorch.org/t/slurm-cluster-cuda-error-all-cuda-capable-devices-are-busy-or-unavailable/114622/14 | I think I resolved it. I registered the Inception network as a part of my main model and then they were able to be on the same device. You can add this line:
advantages_minib = advantages_minib.detach()
after:
if self.normalize_adv:
advantages_minib = (advantages_minib - advantages_minib.mean()) / (advantages_minib... | 1,838 | {'text': ['I think I resolved it. I registered the Inception network as a part of my main model and then they were able to be on the same device.'], 'answer_start': [1838]} |
Backward error, although there are two different networks for actor and critic. (PPO implementation) | I have seen the topics discussed about this error,
RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
but I think in my case is different. I have implemented a PPO algorithm wher… | 0 | 2020-08-16T13:46:06.281Z | You can add this line:
advantages_minib = advantages_minib.detach()
after:
if self.normalize_adv:
advantages_minib = (advantages_minib - advantages_minib.mean()) / (advantages_minib.std() + 1e-8) | 1 | 2020-08-16T14:14:12.254Z | https://discuss.pytorch.org/t/backward-error-although-there-are-two-different-networks-for-actor-and-critic-ppo-implementation/92999/6 | I think I resolved it. I registered the Inception network as a part of my main model and then they were able to be on the same device. You can add this line:
advantages_minib = advantages_minib.detach()
after:
if self.normalize_adv:
advantages_minib = (advantages_minib - advantages_minib.mean()) / (advantages_minib... | 1,054 | {'text': ['You can add this line:\n\nadvantages_minib = advantages_minib.detach()\n\nafter:\n\nif self.normalize_adv:\n\nadvantages_minib = (advantages_minib - advantages_minib.mean()) / (advantages_minib.std() + 1e-8)'], 'answer_start': [1054]} |
Delete samples from loss in a differentiable way | I would like to remove “easy” samples with negligible error from the loss, so that they do not dominate the mean loss value. Focal loss in the RetinaNet paper uses weighting to address the issue. I just want to remove those samples.
I suppose, the following is not right, as it changes the loss valu… | 0 | 2019-09-10T18:30:35.623Z | Hi,
Actually your example does not do any inplace operation ! It would if you were doing loss[loss > 1e-6].zero_().
So your code should work without issue and the entries that were not selected by your mask will just have gradients of 0 in the rest of the network. | 0 | 2019-09-10T20:36:38.516Z | https://discuss.pytorch.org/t/delete-samples-from-loss-in-a-differentiable-way/55634/2 | I think I resolved it. I registered the Inception network as a part of my main model and then they were able to be on the same device. You can add this line:
advantages_minib = advantages_minib.detach()
after:
if self.normalize_adv:
advantages_minib = (advantages_minib - advantages_minib.mean()) / (advantages_minib... | 335 | {'text': ['Hi,\n\nActually your example does not do any inplace operation ! It would if you were doing loss[loss > 1e-6].zero_().\n\nSo your code should work without issue and the entries that were not selected by your mask will just have gradients of 0 in the rest of the network.'], 'answer_start': [335]} |
How to calculate F1 score, Precision in DDP | Hi, I am new to the concept of DDP. I am currently training my model on two GPUs.
If I train on a single GPU with a batch size of b, do I need to divide this batch size by the number of GPUs available for training in DDP.
How can I calculate F1 score, Precision, Recall for a model being traine… | 0 | 2021-01-26T21:25:12.505Z | I see. In that case, DDP alone won’t be sufficient, as DDP’s output and loss are local to each process. If you only need to calculate the globally loss, one option is to gather the outputs instead of loss, and then calculated loss on the gathered outputs. If you also need back propagation from the g… | 0 | 2021-02-01T15:58:15.147Z | https://discuss.pytorch.org/t/how-to-calculate-f1-score-precision-in-ddp/110065/10 | I see. In that case, DDP alone won’t be sufficient, as DDP’s output and loss are local to each process. If you only need to calculate the globally loss, one option is to gather the outputs instead of loss, and then calculated loss on the gathered outputs. If you also need back propagation from the g… In CentOS 7... | 1,208 | {'text': ['I see. In that case, DDP alone won’t be sufficient, as DDP’s output and loss are local to each process. If you only need to calculate the globally loss, one option is to gather the outputs instead of loss, and then calculated loss on the gathered outputs. If you also need back propagation from the g…'... |
Vertices=torch.matmul(vertices.unsqueeze(0), rotations_init), RuntimeError: CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling `cublasSgemmStridedBatched in CentOS | How can I fix this?
(phosa) [jalal@goku phosa]$ python demo.py --filename input/dark_bat.jpg --class_name bat
2021-03-26 16:55:48,497 INFO Calling with args: Namespace(class_name='bat', filename='input/dark_bat.jpg', lw_collision=None, lw_depth=None, lw_inter=None, lw_inter_part=None, lw_scale=&he... | 0 | 2021-03-26T21:15:51.919Z | In CentOS 7, installed Python 3.8.5 and installed the version of PyTorch 1.8.1 that works with CUDA 10.2, and the problem is resolved. Running with batch size 128 below.
(phosa) [jalal@goku phosa]$ python demo.py --filename input/bat_sidehold.jpg --class_name bat
2021-03-31 03:41:53,935 INFO Ca… | 0 | 2021-03-31T07:51:03.754Z | https://discuss.pytorch.org/t/vertices-torch-matmul-vertices-unsqueeze-0-rotations-init-runtimeerror-cuda-error-cublas-status-execution-failed-when-calling-cublassgemmstridedbatched-in-centos/116123/13 | I see. In that case, DDP alone won’t be sufficient, as DDP’s output and loss are local to each process. If you only need to calculate the globally loss, one option is to gather the outputs instead of loss, and then calculated loss on the gathered outputs. If you also need back propagation from the g… In CentOS 7... | 913 | {'text': ['In CentOS 7, installed Python 3.8.5 and installed the version of PyTorch 1.8.1 that works with CUDA 10.2, and the problem is resolved. Running with batch size 128 below.\n\n(phosa) [jalal@goku phosa]$ python demo.py --filename input/bat_sidehold.jpg --class_name bat\n\n2021-03-31 03:41:53,935 INFO Ca&hel... |
Whats the difference between nn.relu() vs F.relu() | whats the difference between nn.relu() vs nn.functional.relu()
and if there no difference so why such duplication…? | 9 | 2018-10-19T13:21:45.170Z | nn.ReLU() creates an nn.Module which you can add e.g. to an nn.Sequential model.
nn.functional.relu on the other side is just the functional API call to the relu function, so that you can add it e.g. in your forward method yourself.
Generally speaking it might depend on your coding style if you pr… | 35 | 2018-10-19T13:28:13.115Z | https://discuss.pytorch.org/t/whats-the-difference-between-nn-relu-vs-f-relu/27599/2 | I see. In that case, DDP alone won’t be sufficient, as DDP’s output and loss are local to each process. If you only need to calculate the globally loss, one option is to gather the outputs instead of loss, and then calculated loss on the gathered outputs. If you also need back propagation from the g… In CentOS 7... | 619 | {'text': ['nn.ReLU() creates an nn.Module which you can add e.g. to an nn.Sequential model.\n\nnn.functional.relu on the other side is just the functional API call to the relu function, so that you can add it e.g. in your forward method yourself.\n\nGenerally speaking it might depend on your coding style if you pr&hell... |
In binary_cross_entropy, RuntimeError: CUDA error: device-side assert triggered | hi,
Hoping someone can help, In a GAN, I get the error:
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [0,0,0], thread: [0,0,0] Assertion `input_val >= zero && input_val <= one` failed.
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [&hell... | 0 | 2021-06-20T15:51:54.033Z | I have finally got to the bottom of this problem. If you are seeing
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [0,0,0], thread: [0,0,0] Assertion `input_val >= zero && input_val <= one` failed.
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:10&hell... | 0 | 2021-11-01T12:09:29.548Z | https://discuss.pytorch.org/t/in-binary-cross-entropy-runtimeerror-cuda-error-device-side-assert-triggered/124569/13 | I have finally got to the bottom of this problem. If you are seeing
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [0,0,0], thread: [0,0,0] Assertion `input_val >= zero && input_val <= one` failed.
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:10&hell... | 1,854 | {'text': ['I have finally got to the bottom of this problem. If you are seeing\n\nC:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [0,0,0], thread: [0,0,0] Assertion `input_val >= zero && input_val <= one` failed.\n\nC:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/... |
First semantic segmentation: Tensor dimension wrong | Hello,
I am trying to train a semantic segmentation network for the first time and in general I am still quite new with PyTorch.
My inputs are RGB-images and corresponding grayscale images. In them the grayscale intensity corresponds to the pixel class.
Please see my first try in the following.
… | 0 | 2020-02-17T16:59:25.048Z | Are you sure you are using the same because I don’t get any errors. In your original code, you are having a line “criterion = nn.BCEWithLogitsLoss().cuda”, you need to change it to “criterion = nn.BCEWithLogitsLoss().cuda()” or “criterion = nn.BCEWithLogitsLoss()”. But I am not sure if you need to … | 1 | 2020-02-19T05:22:24.789Z | https://discuss.pytorch.org/t/first-semantic-segmentation-tensor-dimension-wrong/70073/8 | I have finally got to the bottom of this problem. If you are seeing
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [0,0,0], thread: [0,0,0] Assertion `input_val >= zero && input_val <= one` failed.
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:10&hell... | 1,251 | {'text': ['Are you sure you are using the same because I don’t get any errors. In your original code, you are having a line “criterion = nn.BCEWithLogitsLoss().cuda”, you need to change it to “criterion = nn.BCEWithLogitsLoss().cuda()” or “criterion = nn.BCEWithLogitsLoss()”. But I am not sure if you need to …'... |
Simple CNN for object counting only works with batch size 1 | Hello!
For the last 2 weeks I’ve been stuck trying to count balls from a synthetic dataset I generated.
When I set a batch size higher than 1, the network predicts the average value all the time.
Otherwise, the network works great in train/val
Dataset: 5000 images with grey background and blue … | 0 | 2020-05-22T09:00:03.176Z | Thanks for the executable code, that was really helpful.
You are accidentally broadcasting the loss, since you have a mismatch in the output and target tensors.
While your output has the shape [batch_size, 1], the target has [batch_size].
This yields to a broadcasting as seen here:
# your code w… | 3 | 2020-05-22T22:10:41.921Z | https://discuss.pytorch.org/t/simple-cnn-for-object-counting-only-works-with-batch-size-1/82450/9 | I have finally got to the bottom of this problem. If you are seeing
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:102: block: [0,0,0], thread: [0,0,0] Assertion `input_val >= zero && input_val <= one` failed.
C:/cb/pytorch_1000000000000/work/aten/src/ATen/native/cuda/Loss.cu:10&hell... | 633 | {'text': ['Thanks for the executable code, that was really helpful.\n\nYou are accidentally broadcasting the loss, since you have a mismatch in the output and target tensors.\n\nWhile your output has the shape [batch_size, 1], the target has [batch_size].\n\nThis yields to a broadcasting as seen here:\n\n# your code w&... |
Scheduling Forward and Backward in separate GPU cores | Hi,
Is there a specific scheduling capability where I can define forward pass and backward pass to run on specific GPU devices? With model parallelism, it is clear that we can schedule the layers to be in specific GPU devices. But could we go further into the details? Without overriding, the backwa… | 0 | 2020-02-25T00:38:23.632Z | This overhead is mainly the discovery of what needs to be done to compute gradients. So it needs to traverse all the graph of computation, which takes a bit of time.
Note that if you’re simply experimenting, this overhead won’t kill you. But it won’t be 0. | 1 | 2020-02-25T18:55:22.960Z | https://discuss.pytorch.org/t/scheduling-forward-and-backward-in-separate-gpu-cores/70922/10 | This overhead is mainly the discovery of what needs to be done to compute gradients. So it needs to traverse all the graph of computation, which takes a bit of time.
Note that if you’re simply experimenting, this overhead won’t kill you. But it won’t be 0. Perhaps there is a problem in the data. Could you try to add a... | 1,882 | {'text': ['This overhead is mainly the discovery of what needs to be done to compute gradients. So it needs to traverse all the graph of computation, which takes a bit of time.\n\nNote that if you’re simply experimenting, this overhead won’t kill you. But it won’t be 0.'], 'answer_start': [1882]} |
Loss diverges while training unet | I am trying to generate potrait images, using image segmentation. I am using unet with the following architecture.
import torch
import torch.nn as nn
class Unet(nn.Module):
'''U-Net Architecture'''
def __init__(self,inp,out):
super(Unet,self).__init__()
self.c1=self.contract… | 0 | 2020-03-11T18:36:51.770Z | Perhaps there is a problem in the data. | 1 | 2020-03-17T21:03:43.620Z | https://discuss.pytorch.org/t/loss-diverges-while-training-unet/72911/16 | This overhead is mainly the discovery of what needs to be done to compute gradients. So it needs to traverse all the graph of computation, which takes a bit of time.
Note that if you’re simply experimenting, this overhead won’t kill you. But it won’t be 0. Perhaps there is a problem in the data. Could you try to add a... | 1,199 | {'text': ['Perhaps there is a problem in the data.'], 'answer_start': [1199]} |
Size mismatch of input if more than one CUDA device | Hey guys,
I’m implementing some RL and got stuck at a, in my opinion, weird behaviour.
I’ll use DataParallel and the device-tag to move my Nets/ Data to the available device(s).
Using CPU and one CUDA device everything works fine, but if I use more than one device, I’ll get the following error:
… | 0 | 2018-07-25T11:39:44.191Z | Could you try to add a batch dimension to your data?
For a batch size of 1, your input shape should be [1, in_features].
I assume 72 is your feature dimension.
If so, nn.DataParallel might split on the wrong dimension. | 0 | 2018-07-25T13:54:42.039Z | https://discuss.pytorch.org/t/size-mismatch-of-input-if-more-than-one-cuda-device/21697/7 | This overhead is mainly the discovery of what needs to be done to compute gradients. So it needs to traverse all the graph of computation, which takes a bit of time.
Note that if you’re simply experimenting, this overhead won’t kill you. But it won’t be 0. Perhaps there is a problem in the data. Could you try to add a... | 298 | {'text': ['Could you try to add a batch dimension to your data?\n\nFor a batch size of 1, your input shape should be [1, in_features].\n\nI assume 72 is your feature dimension.\n\nIf so, nn.DataParallel might split on the wrong dimension.'], 'answer_start': [298]} |
Doubt in the code of Faster RCNN implemenation on GitHub | I am trying to implement Faster RCNN for Object Detection. I am following <a href="https://github.com/jwyang/faster-rcnn.pytorch" rel="nofollow noopener">this</a> particular GitHub repo for implementation. However, I have a doubt from <a href="https://github.com/tdchaitanya/MMTOD/blob/master/lib/model/faster_rcnn/resne... | 0 | 2020-03-24T14:27:40.960Z | That’s correct. Note that other (custom) layers might also change their behavior via train()/eval(), if they use the self.training argument internally.
Not necessarily. L274 sets the base to eval(), while L275+ sets the 5th and 6th module back to train. Afterwards all batchnorm layers are reset… | 0 | 2020-03-26T03:55:53.288Z | https://discuss.pytorch.org/t/doubt-in-the-code-of-faster-rcnn-implemenation-on-github/74243/7 | That’s correct. Note that other (custom) layers might also change their behavior via train()/eval(), if they use the self.training argument internally.
Not necessarily. L274 sets the base to eval(), while L275+ sets the 5th and 6th module back to train. Afterwards all batchnorm layers are reset… Your new use ca... | 1,038 | {'text': ['That’s correct. Note that other (custom) layers might also change their behavior via train()/eval(), if they use the self.training argument internally.\n\nNot necessarily. L274 sets the base to eval(), while L275+ sets the 5th and 6th module back to train. Afterwards all batchnorm layers are reset…'],... |
Correct way to build and get encodings from siamese using pretrained model | I am trying to build a small siamese network (with an aim to get encodings from the last/pre-last layer) and would like to use a pretrained model + the extra layers needed to get the encodings.
I have something like this at the moment, but the results dont look great, so I now wonder if this is the… | 0 | 2020-05-26T17:20:50.022Z | Your new use case seems to use the penultimate activation tensors as an extracted feature.
While your approach would return the feature tensor before the pooling layer (which will thus be bigger), my proposed approach would apply the pooling and thus yield a smaller activation.
I don’t know, how y… | 0 | 2020-06-01T07:38:03.251Z | https://discuss.pytorch.org/t/correct-way-to-build-and-get-encodings-from-siamese-using-pretrained-model/82984/13 | That’s correct. Note that other (custom) layers might also change their behavior via train()/eval(), if they use the self.training argument internally.
Not necessarily. L274 sets the base to eval(), while L275+ sets the 5th and 6th module back to train. Afterwards all batchnorm layers are reset… Your new use ca... | 824 | {'text': ['Your new use case seems to use the penultimate activation tensors as an extracted feature.\n\nWhile your approach would return the feature tensor before the pooling layer (which will thus be bigger), my proposed approach would apply the pooling and thus yield a smaller activation.\n\nI don’t know, how y&hell... |
Pytorch appears to be crashing due to OOM prematurely? | I’ve got a model with 110M parameters, and I’m training it on a very small dataset (like 500 examples).
Yet that is enough to crash Pytorch on a K80 GPU with 11GB VRAM.
What is going on here? 110M x 4 (float size) = 440M = 0.440 GB + minuscule dataset size != 11GB VRAM…
Thanks for your help | 0 | 2021-09-03T08:57:43.384Z | [image] sad_robot:
You think those other things could increase the memory burden roughly x20?
The memory usage is model-dependent and often the majority of the memory is used by the forward activations, not the parameters or gradients.
E.g. in <a href="https://discuss.pytorch.org/t/how-to-deal-with-excessive-memory-... | 0 | 2021-09-03T21:37:05.380Z | https://discuss.pytorch.org/t/pytorch-appears-to-be-crashing-due-to-oom-prematurely/131039/7 | That’s correct. Note that other (custom) layers might also change their behavior via train()/eval(), if they use the self.training argument internally.
Not necessarily. L274 sets the base to eval(), while L275+ sets the 5th and 6th module back to train. Afterwards all batchnorm layers are reset… Your new use ca... | 614 | {'text': ['[image] sad_robot:\n\nYou think those other things could increase the memory burden roughly x20?\n\nThe memory usage is model-dependent and often the majority of the memory is used by the forward activations, not the parameters or gradients.\n\nE.g. in <a href="https://discuss.pytorch.org/t/how-to-deal-with-... |
Inspecting memory usage with DDP and workers | 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 … | 0 | 2021-03-11T14:34:00.499Z | 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… | 0 | 2021-03-16T19:27:11.169Z | https://discuss.pytorch.org/t/inspecting-memory-usage-with-ddp-and-workers/114478/10 | 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… If you term... | 2,044 | {'text': ['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.\n\nThe additional CUDA context creation might come from the usage of multiprocessing.\n\nI also don’t know what kind of 0MB process is created as I haven&hell... |
Error: address family mismatch | hi, I try to run the <a href="https://pytorch.org/tutorials/intermediate/rpc_param_server_tutorial.html" rel="noopener nofollow ugc">tutorial example</a> in two machines.
One is my local mac(IP: 192.168.1.57), the other is a docker container(ubuntu) in a linux server(server IP: 192.168.60.67). I use a vpn to visit the... | 0 | 2021-10-14T11:02:50.692Z | If you terminate the processes (e.g., Ctrl+C) you should be able to see a backtrace telling you where they are stuck. Is it at the init_rpc function?
If so, <a class="mention" href="/u/mrshenli">@mrshenli</a> do you know if we have a way to get more verbose logging information from the TCPStore to see what’s going on?... | 1 | 2021-10-18T12:17:30.364Z | https://discuss.pytorch.org/t/error-address-family-mismatch/134220/6 | 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… If you term... | 1,331 | {'text': ['If you terminate the processes (e.g., Ctrl+C) you should be able to see a backtrace telling you where they are stuck. Is it at the init_rpc function?\n\nIf so, <a class="mention" href="/u/mrshenli">@mrshenli</a> do you know if we have a way to get more verbose logging information from the TCPStore to see wha... |
Using DataParallel when the input to the model is a dict | Hello,
I am trying to train a multi-modal model on multiple GPUs using torch.nn.DataParallel.
However, I have multiple modalities so the input to the model is a dictionary.
Is there any way to make this work on multiple GPUs? As far as I’ve understood DataParallel only works if the input to the m… | 0 | 2020-11-10T13:22:47.902Z | Sol 1: define your own class for your inputs and inplement the to() function
Sol2:
self.data = {k: v.to(device) for k, v in self.data.items()}
Ref:
[image]
<a href="https://huggingface.co/transformers/_modules/transformers/tokenization_utils_base.html" target="_blank" rel="noopener nofollow ugc">transformers.token... | 1 | 2020-11-10T15:16:43.651Z | https://discuss.pytorch.org/t/using-dataparallel-when-the-input-to-the-model-is-a-dict/102281/2 | 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… If you term... | 660 | {'text': ['Sol 1: define your own class for your inputs and inplement the to() function\n\nSol2:\n\nself.data = {k: v.to(device) for k, v in self.data.items()}\n\nRef:\n\n[image]\n\n<a href="https://huggingface.co/transformers/_modules/transformers/tokenization_utils_base.html" target="_blank" rel="noopener nofollow ug... |
Weird Cuda out of memory error when I decrease the input size | I was training my model using Yolo v3
When I set my input size = 416, I can train my model with batch size = 9 without any errors.
However, when I decrease my input size to 320, I ran into Cuda memory error even when my batch size = 7.
I found this particularly strange, has anyone encountered an… | 0 | 2018-12-11T06:49:34.017Z | Ho,
What happens if you add torch.backends.cudnn.enabled=False at the beginning of your code? Does the error still occurs? | 1 | 2018-12-13T14:43:54.975Z | https://discuss.pytorch.org/t/weird-cuda-out-of-memory-error-when-i-decrease-the-input-size/31818/7 | Ho,
What happens if you add torch.backends.cudnn.enabled=False at the beginning of your code? Does the error still occurs? It should be possible. And there are several levels of APIs that you can use:
send/recv APIs: <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.send" rel="nofollow noope... | 2,074 | {'text': ['Ho,\n\nWhat happens if you add torch.backends.cudnn.enabled=False at the beginning of your code? Does the error still occurs?'], 'answer_start': [2074]} |
Distributed pagerank with pytorch | I am trying to implement Pagerank with libtorch. I finished the OpenMPI version with Pagerank. I try to read libtorch documents <a href="https://pytorch.org/tutorials/intermediate/dist_tuto.html" rel="nofollow noopener">here</a>.
However, I did not see any function like RPC in OpenMPI.
Is there possible to implement ... | 0 | 2020-04-26T16:58:47.382Z | It should be possible. And there are several levels of APIs that you can use:
send/recv APIs: <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.send" rel="nofollow noopener">https://pytorch.org/docs/stable/distributed.html#torch.distributed.send</a>
collective communication APIs: <a href="ht... | 0 | 2020-04-26T19:59:01.487Z | https://discuss.pytorch.org/t/distributed-pagerank-with-pytorch/78529/2 | Ho,
What happens if you add torch.backends.cudnn.enabled=False at the beginning of your code? Does the error still occurs? It should be possible. And there are several levels of APIs that you can use:
send/recv APIs: <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.send" rel="nofollow noope... | 1,161 | {'text': ['It should be possible. And there are several levels of APIs that you can use:\n\nsend/recv APIs: <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.send" rel="nofollow noopener">https://pytorch.org/docs/stable/distributed.html#torch.distributed.send</a>\n\ncollective communication AP... |
Two dimensional lognormal plot | this may be a bit of a random question but it relates to the inputs i want to give to my neural network. Does anyone know how to create a 2 dimensional lognorm distribution, and then visualizing it as a 3d surface plot in python? i need to do this to understand a component of my network, any help is… | 0 | 2018-10-25T01:05:29.171Z | Sorry for reply you late.
I can draw figure like this
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/4/4225ff485edef29755a932a82bbce194ee16464c.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/4225ff485edef29755a932a82bbce194ee16464c" title="image.jpg">[image]</... | 0 | 2018-10-25T15:34:42.161Z | https://discuss.pytorch.org/t/two-dimensional-lognormal-plot/27972/8 | Ho,
What happens if you add torch.backends.cudnn.enabled=False at the beginning of your code? Does the error still occurs? It should be possible. And there are several levels of APIs that you can use:
send/recv APIs: <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.send" rel="nofollow noope... | 737 | {'text': ['Sorry for reply you late.\n\nI can draw figure like this\n\n<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/4/4225ff485edef29755a932a82bbce194ee16464c.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/4225ff485edef29755a932a82bbce194ee16464c" title="image... |
C10/macros/cmake_macros.h not exists | Hi,
I’m trying to include pytorch/script.h in my CPP android project.
I’m using ndk21 and C++14.
I cloned the repository and used “git submodule update --init --recursive” to update sub=modules.
I’m getting the following compilation error:
In file included from C:\REPOS\pytorch\torch/script.h:3… | 0 | 2020-05-12T14:21:27.662Z | [image] Aviais:
namespace named ‘prim’ in namespace ‘c10’; did you mean simply ‘prim’?
I found a related post. <a href="https://discuss.pytorch.org/t/compilation-error-in-jit-ir-ir-h/80694/2" class="inline-onebox">Compilation error in 'jit/ir/ir.h'</a> | 0 | 2020-06-11T08:05:01.285Z | https://discuss.pytorch.org/t/c10-macros-cmake-macros-h-not-exists/80859/10 | [image] Aviais:
namespace named ‘prim’ in namespace ‘c10’; did you mean simply ‘prim’?
I found a related post. <a href="https://discuss.pytorch.org/t/compilation-error-in-jit-ir-ir-h/80694/2" class="inline-onebox">Compilation error in 'jit/ir/ir.h'</a> This was the problem! Now working with this:
B, _, H, W ... | 2,610 | {'text': ['[image] Aviais:\n\nnamespace named ‘prim’ in namespace ‘c10’; did you mean simply ‘prim’?\n\nI found a related post. <a href="https://discuss.pytorch.org/t/compilation-error-in-jit-ir-ir-h/80694/2" class="inline-onebox">Compilation error in 'jit/ir/ir.h'</a>'], 'answer_start': [2610]} |
Different network output with using batch or not | I train my model with batch size 128, however if I don’t use batch in the evaluation phase, the network output is wrong.
If the network’s input is in batches:
crit = nn.MSELoss(reduction='mean')
target = []
netout = []
model.eval() # To handle drop out layers and batch norm
for A, M, label in dat… | 0 | 2019-09-25T09:30:43.160Z | This was the problem! Now working with this:
B, _, H, W = A.shape
norm = 2*tr.norm(mask1, p=1, dim=(1,2,3))
norm = norm.reshape(B, 1, 1, 1)
mask1 = tr.div(mask1*H*W, norm)
Thank you for your help! | 0 | 2019-09-25T16:23:47.927Z | https://discuss.pytorch.org/t/different-network-output-with-using-batch-or-not/56785/10 | [image] Aviais:
namespace named ‘prim’ in namespace ‘c10’; did you mean simply ‘prim’?
I found a related post. <a href="https://discuss.pytorch.org/t/compilation-error-in-jit-ir-ir-h/80694/2" class="inline-onebox">Compilation error in 'jit/ir/ir.h'</a> This was the problem! Now working with this:
B, _, H, W ... | 1,568 | {'text': ['This was the problem! Now working with this:\n\nB, _, H, W = A.shape\n\nnorm = 2*tr.norm(mask1, p=1, dim=(1,2,3))\n\nnorm = norm.reshape(B, 1, 1, 1)\n\nmask1 = tr.div(mask1*H*W, norm)\n\nThank you for your help!'], 'answer_start': [1568]} |
Track .grad gradient graph | Maybe the title is confusing. Here is the small example:
w = torch.tensor([3.2], requires_grad=True)
p = torch.tensor([2.0, 1, 7], requires_grad=True)
g = torch.sum(p ** 2)
e = w * g
e.backward(retain_graph=True)
f = p.grad
l = e + 0.5 * f.mean()
l.backward()
here f is the funciton of w, however … | 0 | 2020-06-25T00:47:44.712Z | Hi,
You want to do e.backward(create_graph=True) that will make sure the backward pass run in a differentiable manner.
Also creating a .grad that requires grad is usually not recommended because when you do l.backward() here, you will accumulate in the same p.grad which can easily become confusing… | 0 | 2020-06-25T14:35:40.410Z | https://discuss.pytorch.org/t/track-grad-gradient-graph/86804/2 | [image] Aviais:
namespace named ‘prim’ in namespace ‘c10’; did you mean simply ‘prim’?
I found a related post. <a href="https://discuss.pytorch.org/t/compilation-error-in-jit-ir-ir-h/80694/2" class="inline-onebox">Compilation error in 'jit/ir/ir.h'</a> This was the problem! Now working with this:
B, _, H, W ... | 466 | {'text': ['Hi,\n\nYou want to do e.backward(create_graph=True) that will make sure the backward pass run in a differentiable manner.\n\nAlso creating a .grad that requires grad is usually not recommended because when you do l.backward() here, you will accumulate in the same p.grad which can easily become confusing&hell... |
How to load a model properly? | I’ve trained my model and saved it as model.pt file and now I would like to use it to predict new records.
So I’m trying to do the same as my tensorflow code:
model = keras.models.load_model('path/to/location')
prediction = model.predict(my_new_record)
but when I do with pytorch:
model = torch.l… | 0 | 2021-09-14T14:55:53.949Z | Ah my apologises, I should’ve phrased the last statement more clearly. I meant to try the for key, value in state_dict expression for your original torch.save object. It makes sense it requires model_state_dict as that’s the key we use to save the model’s state_dict!
When loading the model you’re u… | 2 | 2021-09-14T17:23:13.625Z | https://discuss.pytorch.org/t/how-to-load-a-model-properly/131947/11 | Ah my apologises, I should’ve phrased the last statement more clearly. I meant to try the for key, value in state_dict expression for your original torch.save object. It makes sense it requires model_state_dict as that’s the key we use to save the model’s state_dict!
When loading the model you’re u… In your app... | 1,548 | {'text': ['Ah my apologises, I should’ve phrased the last statement more clearly. I meant to try the for key, value in state_dict expression for your original torch.save object. It makes sense it requires model_state_dict as that’s the key we use to save the model’s state_dict!\n\nWhen loading the model you’re u&hellip... |
VGG Feature Maps Rescaled | So, I have been reading a paper saying that VGG feature maps were rescaled by 1/12.75. I have two questions regarding this:
I assume this just means that all weights and biases have been rescaled, am I right?
The original paper was done using Theano and Lasagne. I wonder if the rescale factor … | 0 | 2020-04-15T21:56:51.890Z | In your approach you are only rescaling the final output activation of the base vgg model, while it seems that multiple activation maps are scaled and summed to the vgg loss in the paper:
We define the VGG loss based on the ReLU activation layers of the pre-trained 19 layer VGG network described i… | 1 | 2020-04-18T01:25:23.315Z | https://discuss.pytorch.org/t/vgg-feature-maps-rescaled/76938/8 | Ah my apologises, I should’ve phrased the last statement more clearly. I meant to try the for key, value in state_dict expression for your original torch.save object. It makes sense it requires model_state_dict as that’s the key we use to save the model’s state_dict!
When loading the model you’re u… In your app... | 1,083 | {'text': ['In your approach you are only rescaling the final output activation of the base vgg model, while it seems that multiple activation maps are scaled and summed to the vgg loss in the paper:\n\nWe define the VGG loss based on the ReLU activation layers of the pre-trained 19 layer VGG network described i…... |
How to perform repeat padding for variable length data? | I have variable length data and want to pack it to batches with size of max sample len in batch repeating shorter samples.
For example like this
[[0, 1, 2, 3, 4], [0, 1, 2]] => [[0, 1, 2, 3, 4], [0, 1, 2, 0, 1]] | 0 | 2020-04-01T13:20:54.774Z | Oh sorry, I apparently missed the most important part of the question.
I’m not sure, if there is a function for this, but this code snippet should work:
x = [torch.tensor([0, 1, 2, 3, 4]), torch.tensor([0, 1, 2])]
max_len = max([t.size(0) for t in x])
res = [torch.cat((t, t[:max_len-t.size(0)])) f… | 0 | 2020-04-02T22:05:36.274Z | https://discuss.pytorch.org/t/how-to-perform-repeat-padding-for-variable-length-data/75006/4 | Ah my apologises, I should’ve phrased the last statement more clearly. I meant to try the for key, value in state_dict expression for your original torch.save object. It makes sense it requires model_state_dict as that’s the key we use to save the model’s state_dict!
When loading the model you’re u… In your app... | 617 | {'text': ['Oh sorry, I apparently missed the most important part of the question.\n\nI’m not sure, if there is a function for this, but this code snippet should work:\n\nx = [torch.tensor([0, 1, 2, 3, 4]), torch.tensor([0, 1, 2])]\n\nmax_len = max([t.size(0) for t in x])\n\nres = [torch.cat((t, t[:max_len-t.size(0)])) ... |
3D CT images - Resizing and Resampling | I loaded 3D CT images as .npy files to 2D UNet with a spatial dimension 512, 512. How can I ensure the information is preserved when resizing to 256, 256 - maybe the choice of interpolation and others when saving as .npy files | 0 | 2020-11-25T23:46:54.140Z | Yes, resizing in general changes the pixel values. For resizing targets (e.g. segmentation masks) we usually apply “nearest” interpolation mode. In this mode, resizing is approx equivalent to removing columns and lines => that new pixels are exactly the same to the source. For other modes, new pixel… | 1 | 2020-11-26T09:29:12.400Z | https://discuss.pytorch.org/t/3d-ct-images-resizing-and-resampling/104115/5 | Yes, resizing in general changes the pixel values. For resizing targets (e.g. segmentation masks) we usually apply “nearest” interpolation mode. In this mode, resizing is approx equivalent to removing columns and lines => that new pixels are exactly the same to the source. For other modes, new pixel… It seems... | 1,854 | {'text': ['Yes, resizing in general changes the pixel values. For resizing targets (e.g. segmentation masks) we usually apply “nearest” interpolation mode. In this mode, resizing is approx equivalent to removing columns and lines => that new pixels are exactly the same to the source. For other modes, new pixel&helli... |
How to optimise nn.Embedding in backpropagation? | Hi, I am writing a PyTorch program on cross-domain recommendations.
I would like to summarise my model as
input: users and items interacted, retrieve embeddings, pass it through the model, and get the output.
#Initialisation
self.U = nn.Embedding(self.nUser, self.edim_u)
self.param = [self.U + … | 0 | 2020-11-18T16:40:58.565Z | It seems that I have found the cause of your problem.
self.U.parameters() is not a parameter, but a list of parameters (see comments below).
import torch
from torch import nn
from torch.autograd import Variable
class Model(nn.Module) :
def __init__(self, nUser, edim_u, lr = 3e-4):
sup… | 1 | 2020-11-19T16:23:37.697Z | https://discuss.pytorch.org/t/how-to-optimise-nn-embedding-in-backpropagation/103294/10 | Yes, resizing in general changes the pixel values. For resizing targets (e.g. segmentation masks) we usually apply “nearest” interpolation mode. In this mode, resizing is approx equivalent to removing columns and lines => that new pixels are exactly the same to the source. For other modes, new pixel… It seems... | 1,239 | {'text': ['It seems that I have found the cause of your problem.\n\nself.U.parameters() is not a parameter, but a list of parameters (see comments below).\n\nimport torch\n\nfrom torch import nn\n\nfrom torch.autograd import Variable\n\nclass Model(nn.Module) :\n\ndef __init__(self, nUser, edim_u, lr = 3e-4):\n\nsup&he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.