instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
How can I select all values of a multi dimensional tensor based on a mask with PyTorch? | I have a tensor pred, which has a .size() of [4, 53, 161]. I have another tensor mask, which has a .size() of [4, 53].
The mask is only 0's and 1's. What I want to do is get the values of pred where mask has a value of 1. You'll notice that pred has one more dimension than mask. How can I accomplish this?
| mask = mask.unsqueeze(2)
new_pred = pred * mask
That will add extra dimension. It will be now [4, 53, 1]. Rest will be taken care of the broadcasting. (if you do some operation)
Suppose you have a tensor of shape[4, 53, 164] and now you want to reduce it to [4, 53] then you can apply arithmetic operations like this new_pred.mean(2).
| https://stackoverflow.com/questions/60904665/ |
How can I change part of a PyTorch tensor based on the values of another tensor? | This question may not be clear, so please ask for clarification in the comments and I will expand.
I have the following tensors of the following shape:
mask.size() == torch.Size([1, 400])
clean_input_spectrogram.size() == torch.Size([1, 400, 161])
output.size() == torch.Size([1, 400, 161])
mask is comprised only of 0 and 1. Since it's a mask, I want to set the elements of output equal to clean_input_spectrogram where that relevant mask value is 1.
How would I do that?
| You can do something like this, where:
m is your mask;
x is your spectogram;
o is your output;
import torch
torch.manual_seed(2020)
m = torch.tensor([[0, 1, 0]]).to(torch.int32)
x = torch.rand((1, 3, 2))
o = torch.rand((1, 3, 2))
print(o)
# tensor([[[0.5899, 0.8105],
# [0.2512, 0.6307],
# [0.5403, 0.8033]]])
print(x)
# tensor([[[0.4869, 0.1052],
# [0.5883, 0.1161],
# [0.4949, 0.2824]]])
o[:, m[0].to(torch.bool), :] = x[:, m[0].to(torch.bool), :]
# or
# o[:, m[0] == 1, :] = x[:, m[0] == 1, :]
print(o)
# tensor([[[0.5899, 0.8105],
# [0.5883, 0.1161],
# [0.5403, 0.8033]]])
| https://stackoverflow.com/questions/60906284/ |
Create a specific tensor from another tensor | q_pred = self.Q.forward(states) gives me the following output :
tensor([[-4.4713e-02, 4.2878e-03],
[-2.2801e-01, 2.2295e-01],
[-9.8098e-03, -1.0766e-01],
[-1.4654e-01, 1.2742e-01],
[-1.6224e-01, 1.6565e-01],
[-3.6515e-02, 3.1022e-02],
[-4.5094e-02, 1.4848e-02],
[-1.4157e-01, 1.3974e-01],
[-3.0593e-03, -4.2342e-02],
[-4.1689e-02, 2.9376e-02],
[-9.3629e-02, 1.0297e-01],
[-5.2163e-04, -7.4799e-02],
[-2.8944e-02, -1.2417e-01]], grad_fn=<AddmmBackward>)
and actions gives me the the following output
tensor([1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1], dtype=torch.int32)
From the two above output, how can I can the following result :
tensor([4.2878e-03, -2.2801e-01, -1.0766e-01, 1.2742e-01, -1.6224e-01, 3.1022e-02, 1.4848e-02,
-1.4157e-01, -4.2342e-02, -4.1689e-02, -9.3629e-02, -7.4799e-02,, -1.2417e-01], grad_fn=<AddmmBackward>)
?
UPDATE
Here is how self.Q is implemented :
class LinearDeepQNetwork(nn.Module):
def __init__(self, lr, n_actions, input_dims):
super(LinearDeepQNetwork, self).__init__()
self.fc1 = nn.Linear(*input_dims, 128)
self.fc2 = nn.Linear(128, n_actions)
self.optimizer = optim.Adam(self.parameters(), lr=lr)
self.loss = nn.MSELoss()
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.to(self.device)
def forward(self, state):
layer1 = F.relu(self.fc1(state))
actions = self.fc2(layer1)
return actions
| you can use:
q_pred[torch.arange(q_pred.size(0)), actions.type(torch.LongTensor)]
| https://stackoverflow.com/questions/60908462/ |
Slicing torch tensors with list of indeces | I'm doing a reinforcement learning project, and I'm trying to get a tensor that represents the expected reward of all the given actions. I have a long tensor of chosen actions of size batch with values of either zero or one (the two potential actions). I have a tensor of expected rewards for each action of size batch * action_size, and I want a tensor of size batch.
For example, if batch size was 4, then I have
action = tensor([1,0,0,1])
expectedReward = tensor([[3,7],[5,9],[-1,12],[0,1]])
and what I want is
rewardForActions = tensor([7,5,-1,1])
I thought this would answer my question, but it's not the same at all, because if I went with that solution, it would end up with a 4*4 tensor, selecting from each row 4 times, instead of once.
Any ideas?
| You could do
rewardForActions = expectedReward.index_select(1, action).diagonal()
# tensor([ 7, 5, -1, 1])
| https://stackoverflow.com/questions/60909311/ |
Why do we need clone the grad_output and assign it to grad_input when defining a ReLU autograd function? | I'm walking through the autograd part of pytorch tutorials. I have two questions:
Why do we need clone the grad_output and assign it to grad_input other than simple assignment during backpropagation?
What's the purpose of grad_input[input < 0] = 0? Does it mean we don't update the gradient when input less than zero?
Here's the code:
class MyReLU(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
ctx.save_for_backward(input)
return input.clamp(min=0)
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
input, = ctx.saved_tensors
grad_input = grad_output.clone()
grad_input[input < 0] = 0
return grad_input
Link here:
https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-defining-new-autograd-functions
Thanks a lot in advance.
|
Why do we need clone the grad_output and assign it to grad_input other than simple assignment during backpropagation?
tensor.clone() creates a copy of tensor that imitates the original tensor's requires_grad field. clone is a way to copy the tensor while still keeping the copy as a part of the computation graph it came from.
So, grad_input is part of the same computation graph as grad_output and if we compute the gradient for grad_output, then the same will be done for grad_input.
Since we make changes in grad_input, we clone it first.
What's the purpose of 'grad_input[input < 0] = 0'? Does it mean we don't update the gradient when input less than zero?
This is done as per ReLU function's definition. The ReLU function is f(x)=max(0,x). It means if x<=0 then f(x)=0, else f(x)=x. In the first case, when x<0, the derivative of f(x) with respect to x is f'(x)=0. So, we perform grad_input[input < 0] = 0. In the second case, it is f'(x)=1, so we simply pass the grad_output to grad_input (works like an open gate).
| https://stackoverflow.com/questions/60909934/ |
Install PyTorch from requirements.txt | Torch documentation says use
pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
to install the latest version of PyTorch. This works when I do it manually but when I add it to req.txt and do pip install -r req.txt, it fails and says ERROR: No matching distribution.
Edit: adding the whole line from req.txt and error here.
torch==1.4.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.htmltorch==1.4.0+cpu
ERROR: Could not find a version that satisfies the requirement torch==1.4.0+cpu (from -r requirements.txt (line 1)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2, 0.3.1, 0.4.0, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0, 1.2.0, 1.3.0, 1.3.1, 1.4.0)
ERROR: No matching distribution found for torch==1.4.0+cpu (from -r requirements.txt (line 1))
| Add --find-links in requirements.txt before torch
--find-links https://download.pytorch.org/whl/torch_stable.html
torch==1.2.0+cpu
Source: https://github.com/pytorch/pytorch/issues/29745#issuecomment-553588171
| https://stackoverflow.com/questions/60912744/ |
How to apply linear layer to 2D layer only in one dimension (by row or by column) - partially connected layers | I'm trying to apply a linear layer to a 2D matrix of tensors connecting it only by column as in the picture below.
The input shape is (batch_size, 3, 50). I first tried with 2D convolution, adding a 1 channel dimension, so input shape is (batch_size, 1, 3, 50)
import torch.nn as nn
import torch
class ColumnConv(nn.Module):
def __init__(self):
self.layers = nn.Sequential(
nn.Conv2d(
in_channels=1,
out_channels=1,
kernel_size=(3, 1),
stride=1,
), # shape is B, 1, 1, 50
nn.ReLU(),
nn.Flatten() #shape is B, 50
)
def forward(self, x):
return self.layers(x)
But it doesn't seem to work.
I'm planning to use a list of 50 nn.Linear layers and apply them to column slices of input, but it seems much more like a workaround not optimized for performance.
Is there a more "pytorchic" way of doing this?
| The PyTorch nn.Linear module can be applied to multidimensional input, the linear will be applied to the last dimension so to apply by column the solution is to swap rows and columns.
linear_3_to_1 = nn.Linear(3, 1)
x = torch.randn(1, 1, 3, 50)
x = x.transpose(2, 3) #swap 3 and 50
out = linear_3_to_1(x).flatten()
| https://stackoverflow.com/questions/60915372/ |
Get indices of elements in tensor a that are present in tensor b | For example, I want to get the indices of elements valued 0 and 2 in tensor a. These values, (0 and 2) are stored in tensor b. I have devised a pythonic way to do so (shown below), but I don't think list comprehensions are optimized to run on GPU, or maybe there is a more PyTorchy way to do it that I am unaware of.
import torch
a = torch.tensor([0, 1, 0, 1, 1, 0, 2])
b = torch.tensor([0, 2])
torch.tensor([x in b for x in a]).nonzero()
>>>> tensor([[0],
[2],
[5],
[6]])
Any other suggestions or is this an acceptable way?
| Here's a more efficient way to do it (as suggested in the link posted by jodag in comments...):
(a[..., None] == b).any(-1).nonzero()
| https://stackoverflow.com/questions/60918304/ |
How can I count the number of 1's and 0's in the second dimension of a PyTorch Tensor? | I have a tensor with size: torch.Size([64, 2941]), which is 64 batches of 2941 elements.
Across all 64 batches, I want to count the total number of 1s and 0s in the second dimension of the tensor, all the way to the 2941th so that I will have those counts as a tensor of size torch.Size([2941])
How do I do that?
| You can sum them:
import torch
torch.manual_seed(2020)
# x is a fake data, it should be your tensor with 64x2941
x = (torch.rand((3,4)) > 0.5).to(torch.int32)
print(x)
# tensor([[0, 0, 1, 0],
# [0, 0, 1, 1],
# [0, 1, 1, 1]], dtype=torch.int32)
ones = (x == 1.).sum(dim=0)
print(ones)
# tensor([0, 1, 3, 2])
And if x is binary, you can have the number of zeros by a simple subtraction:
zeros = x.shape[1] - ones
| https://stackoverflow.com/questions/60922782/ |
I fine tuned a pre-trained BERT for sentence classification, but i cant get it to predict for new sentences | below is the result of my fine-tuning.
Training Loss Valid. Loss Valid. Accur. Training Time Validation Time
epoch
1 0.16 0.11 0.96 0:02:11 0:00:05
2 0.07 0.13 0.96 0:02:19 0:00:05
3 0.03 0.14 0.97 0:02:22 0:00:05
4 0.02 0.16 0.96 0:02:21 0:00:05
next i tried to use the model to predict labels from a csv file. i created a label column, set the type to int64 and run the prediction.
print('Predicting labels for {:,} test sentences...'.format(len(input_ids)))
model.eval()
# Tracking variables
predictions , true_labels = [], []
# Predict
for batch in prediction_dataloader:
# Add batch to GPU
batch = tuple(t.to(device) for t in batch)
# Unpack the inputs from our dataloader
b_input_ids, b_input_mask, b_labels = batch
# Telling the model not to compute or store gradients, saving memory and
# speeding up prediction
with torch.no_grad():
# Forward pass, calculate logit predictions
outputs = model(b_input_ids, token_type_ids=None,
attention_mask=b_input_mask)
logits = outputs[0]
# Move logits and labels to CPU
logits = logits.detach().cpu().numpy()
label_ids = b_labels.to('cpu').numpy()
# Store predictions and true labels
predictions.append(logits)
true_labels.append(label_ids)
however, while i am able to print out the predictions[4.235, -4.805] etc, and the true_labels[NaN,NaN.....], i am unable to actually get the predicted labels{0 or 1}. Am i missing something here?
| The output of the models are logits, i.e., the probability distribution before normalization using softmax.
If you take your output: [4.235, -4.805] and run softmax over it
In [1]: import torch
In [2]: import torch.nn.functional as F
In [3]: F.softmax(torch.tensor([4.235, -4.805]))
Out[3]: tensor([9.9988e-01, 1.1856e-04])
You get get 99% probability score for label 0. When you have the logits as a 2D tensor, you can easily get the classes by calling
logits.argmax(0)
The NaNs values in your true_labels are probably a bug in how you load the data, it has nothing to do with the BERT model.
| https://stackoverflow.com/questions/60923314/ |
Why override Dataset instead of directly pass in input and labels, pytorch | Sorry if what I say here is wrong -- new to pytorch.
From what I can tell there are two main ways of getting training data and passing through a network. One is to override Dataset and the other is to just prepare your data correctly and then iterate over it, like shown in this example: pytorch classification example
which does something like
rnn(input, hidden, output)
for i in range(input.size()[0]):
output, hidden = rnn(input[i], hidden)
The other way would be to do something like
for epoch in range(epochs):
for data, target in trainloader:
computer model etc
where in this method, trainloader is from doing something like
trainloader = DataLoader(my_data)
after overriding getitem and len
My question here, is what are the differences between these methods, and why would you use one over the other? Also, it seems to me that overriding Dataset doesn't work for something that has lets say an input layer of size 100 nodes with an output of 10 nodes, since when you return getitem it needs a pair of (data, label). This seems like a case where I probably don't understand how to use Dataset very well, but that is why I'm asking in the first place. I think I read something about a collate function which might help in this scenario?
| Dataset class and the Dataloader class in PyTorch help us to feed our own training data into the network. Dataset class is used to provide an interface for accessing all the training or testing samples in your dataset. In order to achieve this, you have to implement at least two methods, __getitem__ and __len__ so that each training sample can be accessed by its index. In the initialization part of the class, we load the dataset (as float type) and convert them into Float torch tensors. __getitem__ will return the features and target value.
What are the differences between these methods?
In PyTorch either you can prepare your data such that the PyTorch DataLoader can consume it and you get an iterable object or you can overload the default DataLoader to perform some custom operations like if you want to do some preprocessing of text/images, stack frames from videos clips, etc.
Our DataLoader behaves like an iterator, so we can loop over it and fetch a different mini-batch every time.
Basic Sample
from torch.utils.data import DataLoader
train_loader = DataLoader(dataset=train_data, batch_size=16, shuffle=True)
valid_loader = DataLoader(dataset=valid_data, batch_size=16, shuffle=True)
# To retrieve a sample mini-batch, one can simply run the command below —
# it will return a list containing two tensors:
# one for the features, another one for the labels.
next(iter(train_loader))
next(iter(valid_loader))
Custom Sample
import torch
from torch.utils.data import Dataset, Dataloader
class SampleData(Dataset):
def __init__(self, data):
self.data = torch.FloatTensor(data.values.astype('float'))
def __len__(self):
return len(self.data)
def __getitem__(self, index):
target = self.data[index][-1]
data_val = self.data[index] [:-1]
return data_val,target
train_dataset = SampleData(train_data)
valid_dataset = SampleData(valid_data)
device = "cuda" if torch.cuda.is_available() else "cpu"
kwargs = {'num_workers': 1, 'pin_memory': True} if device=='cuda' else {}
train_loader = DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True, **kwargs)
test_loader = DataLoader(valid_dataset, batch_size=test_batch_size, shuffle=False, **kwargs)
Why would you use one over the other?
It solely depends on your use-case and the amount of control you want. PyTorch has given you all the power and it is you who is going to decide how much you want to. Suppose you are solving a simple image classification problem, then,
You can simply put all the images in a root folder with each subfolder containing the samples belonging to a particular class and label the folder with the class name. When training we just need to specify the path to the root folder and the PyTorch DataLoader will automatically pick images from each folder and training the model.
But on the other hand, if you have classifying video clips or video sequences generally known as video tagging in a large video file then you need to write your custom DataLoader to load the frames from the video, stack it and give input to the DataLoader.
Use can find some useful links below for further reference:
https://pytorch.org/docs/stable/data.html
https://stanford.edu/~shervine/blog/pytorch-how-to-generate-data-parallel
https://pytorch.org/tutorials/beginner/data_loading_tutorial.html
| https://stackoverflow.com/questions/60925070/ |
Extracting indexes from a max pool over uniform data | I'm trying to find max points in a 2D tensor for a given kernel size, but I'm having issues with a special case where all the values are uniform. For example, given the following example, I would like to mark each point as a max point:
+---+---+---+---+
| 5 | 5 | 5 | 5 |
+---+---+---+---+
| 5 | 5 | 5 | 5 |
+---+---+---+---+
| 5 | 5 | 5 | 5 |
+---+---+---+---+
| 5 | 5 | 5 | 5 |
+---+---+---+---+
If I run torch.nn.functional.max_pool2d with a kernel size=3, stride=1, and padding=1, I get the following indicies:
+---+---+---+----+
| 0 | 0 | 1 | 2 |
+---+---+---+----+
| 0 | 0 | 1 | 2 |
+---+---+---+----+
| 4 | 4 | 5 | 6 |
+---+---+---+----+
| 8 | 8 | 9 | 10 |
+---+---+---+----+
What changes do I need to account for to instead obtain the following indicies?
+----+----+----+----+
| 1 | 2 | 3 | 4 |
+----+----+----+----+
| 5 | 6 | 7 | 8 |
+----+----+----+----+
| 9 | 10 | 11 | 12 |
+----+----+----+----+
| 13 | 14 | 15 | 16 |
+----+----+----+----+
| You can do the following:
a = torch.ones(4,4)
indices = (a == torch.max(a).item()).nonzero()
What this does is return a [16,2] sized tensor with the 2D coordinates of the max value(s), i.e. [0,0], [0,1], .., [3,3]. The torch.max part should be easy to understand, nonzero() considers the boolean tensor given by (a == torch.max(a).item()), takes False to be 0, and returns the non-zero indices. Hope this helps!
| https://stackoverflow.com/questions/60925607/ |
torch assign not in place by tensor slicing in pytorch | I am trying to convert my current code, which assigns tensors in place, to an outer operation.
Meaning currently the code is
self.X[:, nc:] = D
Where D is in the same shape as self.X[:, nc:]
But I would like to convert it to
sliced_index = ~ somehow create an indexed tensor from self.X[:, nc:]
self.X = self.X.scatter(1,sliced_index,mm(S_, Z[:, :n - nc]))
And don't know how to create that index mask tensor that represents only the entries in the sliced tensor
Minimal example:
a = [[0,1,2],[3,4,5]]
D = [[6],[7]]
Not_in_place = [[0,1,6],[3,4,7]]
| A masked scatter is a little easier. The mask itself can be computed as an in-place operation after which you can use masked_scatter
mask = torch.zeros(self.X.shape, device=self.X.device, dtype=torch.bool)
mask[:, nc:] = True
self.X = self.X.masked_scatter(mask, D)
A more specialized version which relies on broadcasting but should be more efficient would be
mask = torch.zeros([1, self.X.size(1)], device=self.X.device, dtype=torch.bool)
mask[0, nc:] = True
self.X = self.X.masked_scatter(mask, D)
| https://stackoverflow.com/questions/60927234/ |
Create slice mask in pytorch? | Is there a way to specify a mask based on a slice operation?
For example
A = torch.arange(6).view((2,3))
# A = [[0,1,2], [3,4,5]]
mask_slice = torch.mask_slice(A[:,1:])
# mask_slice = [[0,1,1],[0,1,1]]
| You can do something like this (if I got your question right):
mask_slice = torch.zeros(A.shape, dtype=bool)
mask_slice[:, 1:] = 1
# tensor([[False, True, True],
# [False, True, True]])
| https://stackoverflow.com/questions/60928087/ |
Multi class classifcation with Pytorch | I'm new with Pytorch and I need a clarification on multiclass classification.
I'm fine-tuning the DenseNet neural network, so it can recognize 3 different classes.
Because it's a multiclass problem, I have to replace the classification layer in this way:
kernelCount = self.densenet121.classifier.in_features
self.densenet121.classifier = nn.Sequential(nn.Linear(kernelCount, 3), nn.Softmax(dim=1))
And use CrossEntropyLoss as the loss function:
loss = torch.nn.CrossEntropyLoss(reduction='mean')
By reading on Pytorch forum, I found that CrossEntropyLoss applys the softmax function on the output of the neural network. Is this true? Should I remove the Softmax activation function from the structure of the network?
And what about the test phase? If it's included, I have to call the softmax function on the output of the model?
Thanks in advance for your help.
| Yes, CrossEntropyLoss applies softmax implicitly. You should remove the softmax layer at the end of the network since softmax is not idempotent, therefore applying it twice would be a semantic error.
As far as evaluation/testing goes. Remember that softmax is a monotonically increasing operation (meaning the relative order of outputs doesn't change when you apply it). Therefore the result of argmax before and after softmax will give the same result.
The only time you may want to perform softmax explicitly during evaluation would be if you need the actual confidence value for some reason. If needed you can apply softmax explicitly using torch.softmax on the network output during evaluation.
| https://stackoverflow.com/questions/60938630/ |
RuntimeError: size mismatch, m1: [4 x 784], m2: [4 x 784] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:136 | I have executed the following code
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils import data as t_data
import torchvision.datasets as datasets
from torchvision import transforms
data_transforms = transforms.Compose([transforms.ToTensor()])
mnist_trainset = datasets.MNIST(root='./data', train=True,
download=True, transform=data_transforms)
batch_size=4
dataloader_mnist_train = t_data.DataLoader(mnist_trainset,
batch_size=batch_size,
shuffle=True
)
def make_some_noise():
return torch.rand(batch_size,100)
class generator(nn.Module):
def __init__(self, inp, out):
super(generator, self).__init__()
self.net = nn.Sequential(
nn.Linear(inp,784),
nn.ReLU(inplace=True),
nn.Linear(784,1000),
nn.ReLU(inplace=True),
nn.Linear(1000,800),
nn.ReLU(inplace=True),
nn.Linear(800,out)
)
def forward(self, x):
x = self.net(x)
return x
class discriminator(nn.Module):
def __init__(self, inp, out):
super(discriminator, self).__init__()
self.net = nn.Sequential(
nn.Linear(inp,784),
nn.ReLU(inplace=True),
nn.Linear(784,784),
nn.ReLU(inplace=True),
nn.Linear(784,200),
nn.ReLU(inplace=True),
nn.Linear(200,out),
nn.Sigmoid()
)
def forward(self, x):
x = self.net(x)
return x
def plot_img(array,number=None):
array = array.detach()
array = array.reshape(28,28)
plt.imshow(array,cmap='binary')
plt.xticks([])
plt.yticks([])
if number:
plt.xlabel(number,fontsize='x-large')
plt.show()
d_steps = 100
g_steps = 100
gen=generator(4,4)
dis=discriminator(4,4)
criteriond1 = nn.BCELoss()
optimizerd1 = optim.SGD(dis.parameters(), lr=0.001, momentum=0.9)
criteriond2 = nn.BCELoss()
optimizerd2 = optim.SGD(gen.parameters(), lr=0.001, momentum=0.9)
printing_steps = 20
epochs = 5
for epoch in range(epochs):
print (epoch)
# training discriminator
for d_step in range(d_steps):
dis.zero_grad()
# training discriminator on real data
for inp_real,_ in dataloader_mnist_train:
inp_real_x = inp_real
break
inp_real_x = inp_real_x.reshape(batch_size,784)
dis_real_out = dis(inp_real_x)
dis_real_loss = criteriond1(dis_real_out,
Variable(torch.ones(batch_size,1)))
dis_real_loss.backward()
# training discriminator on data produced by generator
inp_fake_x_gen = make_some_noise()
#output from generator is generated
dis_inp_fake_x = gen(inp_fake_x_gen).detach()
dis_fake_out = dis(dis_inp_fake_x)
dis_fake_loss = criteriond1(dis_fake_out,
Variable(torch.zeros(batch_size,1)))
dis_fake_loss.backward()
optimizerd1.step()
# training generator
for g_step in range(g_steps):
gen.zero_grad()
#generating data for input for generator
gen_inp = make_some_noise()
gen_out = gen(gen_inp)
dis_out_gen_training = dis(gen_out)
gen_loss = criteriond2(dis_out_gen_training,
Variable(torch.ones(batch_size,1)))
gen_loss.backward()
optimizerd2.step()
if epoch%printing_steps==0:
plot_img(gen_out[0])
plot_img(gen_out[1])
plot_img(gen_out[2])
plot_img(gen_out[3])
print("\n\n")
On running the code,following error is shown
File "mygan.py", line 105, in <module>
dis_real_out = dis(inp_real_x)
RuntimeError: size mismatch, m1: [4 x 784], m2: [4 x 784] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:136
How can I resolve this?
I got the code from https://blog.usejournal.com/train-your-first-gan-model-from-scratch-using-pytorch-9b72987fd2c0
| The error hints that the tensor you fed into the discriminator has incorrect shape. Now let's try to find out what the shape of the tensor is, and what shape is expected.
The tensor itself has a shape of [batch_size x 784] because of the reshape operation above. The discriminator network, on the other hand, expects a tensor with a last dimension of 4. This is because the first layer in the discriminator network is nn.Linear(inp, 784), where inp = 4.
A linear layer nn.Linear(input_size, output_size), expects the final dimension of the input tensor to be equal to input_size, and generates output with the final dimension projected to output_size. In this case, it expects an input tensor of shape [batch_size x 4], and outputs a tensor of shape [batch_size x 784].
And now to the real issue: the generator and discriminator that you defined has incorrect size. You seem to have changed the 300 dimension size from the blog post to 784, which I assume is the size of your image (28 x 28 for MNIST). However, the 300 is not the input size, but rather a "hidden state size" -- the model uses a 300-dimensional vector to encode your input image.
What you should do here is to set the input size to 784, and the output size to 1, because the discriminator makes a binary judgment of fake (0) or real (1). For the generator, the input size should be equal to the "input noise" that you randomly generate, in this case 100. The output size should also be 784, because its output is the generated image, which should be the same size as the real data.
So, you only need to make the following changes to your code, and it should run smoothly:
gen = generator(100, 784)
dis = discriminator(784, 1)
| https://stackoverflow.com/questions/60942205/ |
How to break PyTorch autograd with in-place ops | I'm trying to understand better the role of in-place operations in PyTorch autograd.
My understanding is that they are likely to cause problems since they may overwrite values needed during the backward step.
I'm trying to build an example where an in-place operation breaks the auto differentiation, my idea is to overwrite some value needed during the backpropagation after it has been used to compute some other tensor.
I'm using the assignment as the in-place operation (I tried += with the same result), I double-checked it is an in-place op in this way:
x = torch.arange(5, dtype=torch.float, requires_grad=True)
y = x
y[3] = -1
print(x)
prints:
tensor([ 0., 1., 2., -1., 4.], grad_fn=<CopySlices>)
This is my attempt to break autograd:
Without the in-place op:
x = torch.arange(5, dtype=torch.float, requires_grad=True)
out1 = x ** 2
out2 = out1 / 10
# out1[3] += 100
out2.sum().backward()
print(x.grad)
This prints
tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000])
With the in-place op:
x = torch.arange(5, dtype=torch.float, requires_grad=True)
out1 = x ** 2
out2 = out1 / 10
out1[3] = 0
out2.sum().backward()
print(x.grad)
This prints:
tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000])
I was expecting to obtain differents grads.
What is the item assignment doing? I don't get the grad_fn=<CopySlices>.
Why does it return the same grads?
Is there a working example of in-place operations that break autograd?
Is there a list of non-backwards compatible PyTorch ops?
| A working example of an in-place operations that breaks autograd:
x = torch.ones(5, requires_grad=True)
x2 = (x + 1).sqrt()
z = (x2 - 10)
x2[0] = -1
z.sum().backward()
Raises:
RuntimeError: one of the variables needed for gradient computation has been modified by an in-place operation: [torch.FloatTensor [5]], which is output 0 of SqrtBackward, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
| https://stackoverflow.com/questions/60949682/ |
Why bilinear scaling of images with PIL and pytorch produces different results? | In order to feed an image to the pytorch network I first need to downscale it to some fixed size. At first I've done it using PIL.Image.resize() method, with interpolation mode set to BILINEAR. Then I though it would be more convenient to first convert a batch of images to pytorch tensor and then use torch.nn.functional.interpolate() function to scale the whole tensor at once on a GPU ('bilinear' interpolation mode as well). This lead to a decrease of the model accuracy because now during inference a type of scaling (torch) was different from the one used during training (PIL). After that, I compared two methods of downscaling visually and found out that they produce different results. Pillow downscaling seems more smooth. Do these methods perform different operations under the hood though both being bilinear? If so, I am also curious if there is a way to achieve the same result as Pillow image scaling with torch tensor scaling?
Original image (the well-known Lenna image)
Pillow scaled image:
Torch scaled image:
Mean channel absolute difference map:
Demo code:
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
from torchvision import transforms
import matplotlib.pyplot as plt
pil_to_torch = transforms.ToTensor()
res_shape = (128, 128)
pil_img = Image.open('Lenna.png')
torch_img = pil_to_torch(pil_img)
pil_image_scaled = pil_img.resize(res_shape, Image.BILINEAR)
torch_img_scaled = F.interpolate(torch_img.unsqueeze(0), res_shape, mode='bilinear').squeeze(0)
pil_image_scaled_on_torch = pil_to_torch(pil_image_scaled)
relative_diff = torch.abs((pil_image_scaled_on_torch - torch_img_scaled) / pil_image_scaled_on_torch).mean().item()
print('relative pixel diff:', relative_diff)
pil_image_scaled_numpy = pil_image_scaled_on_torch.cpu().numpy().transpose([1, 2, 0])
torch_img_scaled_numpy = torch_img_scaled.cpu().numpy().transpose([1, 2, 0])
plt.imsave('pil_scaled.png', pil_image_scaled_numpy)
plt.imsave('torch_scaled.png', torch_img_scaled_numpy)
plt.imsave('mean_diff.png', np.abs(pil_image_scaled_numpy - torch_img_scaled_numpy).mean(-1))
Python 3.6.6, requirements:
cycler==0.10.0
kiwisolver==1.1.0
matplotlib==3.2.1
numpy==1.18.2
Pillow==7.0.0
pyparsing==2.4.6
python-dateutil==2.8.1
six==1.14.0
torch==1.4.0
torchvision==0.5.0
| "Bilinear interpolation" is an interpolation method.
But downscaling an image is not necessarily only accomplished using interpolation.
It is possible to simply resample the image as a lower sampling rate, using an interpolation method to compute new samples that don't coincide with old samples. But this leads to aliasing (which is what you get when higher frequency components in the image cannot be represented at the lower sampling density, "aliasing" the energy of these higher frequencies onto lower frequency components; that is, new low frequency components appear in the image after the resampling).
To avoid aliasing, some libraries apply a low-pass filter (remove high frequencies that cannot be represented at the lower sampling frequency) before resampling. The subsampling algorithm in these libraries do much more than just interpolating.
The difference you see is because these two libraries take different approaches, one tries to avoid aliasing by low-pass filtering, the other doesn't.
To obtain the same results in Torch as in Pillow, you need to explicitly low-pass filter the image yourself. To get identical results you will have to figure out exactly how Pillow filters the image, there are different methods and different possible parameter settings. Looking at the source code is the best way to find out exactly what they do.
| https://stackoverflow.com/questions/60949936/ |
Building a deep reinforcement learning with a cnn q - approximation | I'm new in DRL. Starting from this code https://github.com/jaromiru/cwcf, I would like to substitute the MLP used for the q function approximation with a CNN, but I don't know how to do. Can anybody help me? Thanks
| Try going through this it has a detailed explanation on how to build DQN to solve the CartPole problem. You can also have a look at this which has implementations of many DRL algorithms
Then you can replace the code in agent.py present in repo with DQN agent code
| https://stackoverflow.com/questions/60955922/ |
How can i convert an ndarray shape (32 by xxx) into a single column dataframe, while discarding the last ten objects of this array | After running a binary classification NLP model over a dataset with batch size of 32, i have an nparray of predictions of size 32 by 300 and the last batch is of size 24. i am trying to rearrange these values in a dataframe.
predictions.append(logits.argmax(1))
[array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0]), array([0, 1, 0, 0, 0, 0, 0, 0............
however, when i try to convert it to a dataframe,
df.labels = pd.DataFrame(predictions)
df.labels.head()
this is what i get
0 0.0
1 0.0
2 0.0
3 0.0
4 0.0
Name: labels, dtype: float64
i want to have the values as 1 or 0 integers, not floats
the final data batch of 32 has NaN from value 24 to 32, instead of being blank
| If your column contains NaN it will always be of float type. The presence of NaN values explains therefore why the column is float.
You must have a dimension problem, your predictions variable is two dimensional, 32 x 10, you should flatten it first and then add your 24 elements, see documentions here :
predictions = predictions.flatten()
to_append = logits.argmax(1) # this is your array with 24 elements
predictions = predictions.append(to_append)
What happens here is that whan you append a row of 24 elements to a DataFrame with 32 columns, the last columns from 23 to 32 will exist and will automatically be filled with NaN. See some examples here and here.
Why do you want to transform NaN to blank? If blank means an empty string, you shouldn't do that, as you will mix float and string in your column.
If you want Integer values. You should make an imputation of the NaN values with a constant Integer value (let us say 888):
df = df.fillna(888)
Then you can transform all to int using the function astype :
df = df.astype('int16')
| https://stackoverflow.com/questions/60956579/ |
weird problem with Pytorch's mse_loss function | Traceback (most recent call last):
File "c:/Users/levin/Desktop/programming/nn.py", line 208, in <module>
agent.train(BATCHSIZE)
File "c:/Users/levin/Desktop/programming/nn.py", line 147, in train
output = F.mse_loss(prediction, target)
File "C:\Users\levin\Anaconda3\lib\site-packages\torch\nn\functional.py", line 2203, in mse_loss
if not (target.size() == input.size()):
AttributeError: 'NoneType' object has no attribute 'size'
This above is the Error that I'm constantly getting and I really don't know how to fix it.
This some code that might be important
def train(self, BATCHSIZE):
trainsample = random.sample(self.memory, BATCHSIZE)
for state, action, reward, new_state, gameovertemp in trainsample:
if gameovertemp:
target = torch.tensor(reward).grad_fn
else:
target = reward + self.gamma * torch.max(self.dqn.forward(new_state))
self.dqn.zero_grad()
prediction = torch.max(self.dqn.forward(state))
#print(prediction, "prediction")
#print(target, "target")
output = F.mse_loss(prediction, target)
output.backward()
self.optimizer.step()
| As stated in a comment the error due to either target of input to be None and is not related to the size() attribute.
The problem is probably at this line:
target = torch.tensor(reward).grad_fn
Here you convert reward to a new Tensor. However, a Tensor created by the user always has a grad_fn equal to None (as explained in Pytorch Autograd).
To have a grad_fn a Tensor must be the result of some computation, not a static value.
The thing is that mse_loss does not expect target to be differentiable, as the name suggest it is just the value to be compared.
Try to remove the grad_fn from this line the raw Tensor should be sufficient.
| https://stackoverflow.com/questions/60958134/ |
PyTorch TensorBoard write frequency | I'm trying to write my training and validation losses to tensorboard using torch (torch.utils.tensorboard) and it looks like it only writes up to 1000 data points, no matter what the actual number of iterations are. For example, running the following code,
writer1 = SummaryWriter('runs/1')
writer2 = SummaryWriter('runs/2')
for i in range(2000):
writer1.add_scalar('tag', 1, i)
for i in range(20000):
writer2.add_scalar('tag', 1, i)
both yield 1000 points exactly when examining and downloaded csv, and even on the tensorboard dashboard, the first points start at steps 5 and 18 and increment such that the total number of steps are 1000, rather than 2,000 and 20,000.
I don't know if this is tensorboard's default behaviour or if its PyTorch's decision, but either way, is there a way to write every single step?
| Actually I found the answer here. So the SummaryWriter is saving at every epoch, but to load everything, tensorboard has to be started with the flag --samples_per_plugin scalars=0. 0 tells tensorboard to load all points, while 100 would mean a total of 100 points for example
To sum up, I started tensorboard with the command tensorboard --logdir=logs --samples_per_plugin scalars=0
| https://stackoverflow.com/questions/60962281/ |
kth-value per row in pytorch? | Given
import torch
A = torch.rand(9).view((3,3)) # tensor([[0.7455, 0.7736, 0.1772],\n[0.6646, 0.4191, 0.6602],\n[0.0818, 0.8079, 0.6424]])
k = torch.tensor([0,1,0])
A.kthvalue_vectoriezed(k) -> [0.1772,0.6602,0.0818]
Meaning I would like to operate on each column with a different k.
Not kthvalue nor topk offers such API.
Is there a vectorized way around that?
Remark - kth value is not the value in the kth index, but the kth smallest element. Pytorch docs
torch.kthvalue(input, k, dim=None, keepdim=False, out=None) -> (Tensor, LongTensor)
Returns a namedtuple (values, indices) where values is the k th smallest element of each row of the input tensor in the given dimension dim. And indices is the index location of each element found.
| Assuming you don't need indices into original matrix (if you do, just use fancy indexing for the second return value as well) you could simply sort the values (by last index by default) and return appropriate values like so:
def kth_smallest(tensor, indices):
tensor_sorted, _ = torch.sort(tensor)
return tensor_sorted[torch.arange(len(indices)), indices]
And this test case gives you your desired values:
tensor = torch.tensor(
[[0.7455, 0.7736, 0.1772], [0.6646, 0.4191, 0.6602], [0.0818, 0.8079, 0.6424]]
)
print(kth_smallest(tensor, [0, 1, 0])) # -> [0.1772,0.6602,0.0818]
| https://stackoverflow.com/questions/60964950/ |
Create a torch::Tensor in C++ to change the shape | I have a tensor array, and I want to change the shape of tensor. I tried to use torch.view, but it raise an exception that "shape[1] is invalid for input of size 10000". Anyone can give me a tips for the error information?
int shape[] = {1,1,100,100};
torch::Tensor img = torch::zeros((100,100),torch::KF32);
torch::Tensor tmg = img.view(*shape);
| C++ is not python so constructs like unpacking with * obviously will not work. Same goes for (, ), you should use object which can be "auto-casted" to IntArrayRef.
Creating objects basics
ArrayRef is a template class which means it can hold different C++ types and IntArrayRef is an alias for ArrayRef<int>. This class has a few constructors (e.g. from standard C-style array, std::vector, std::array or std::initializer_list).
Both torch::zeros and view method of torch::Tensor require this exact object.
What you can do is:
/* auto to feel more "Pythonic" */
auto img = torch::zeros({100, 100}, torch::kF32);
auto tmg = img.view({1, 1, 100, 100});
{1, 1, 100, 100} is std::initializer_list<int> type so ArrayRef<int> (a.k.a. IntArrayRef) can be constructed from it (probably moved as this object is an rvalue).
Same thing happens for torch::zeros.
Easier way for this case
What you have here could be accomplished easier though with unsqueeze like this:
auto img = torch::zeros({100, 100}, torch::kF32);
auto unsqueezed = img.unsqueeze(0).unsqueeze(0);
Where 0 in the dimension.
About libtorch
All in all read the reference and check types at least if you want to work with C++. I agree docs could use some work but if you know something about C++ it shouldn't be too hard to follow even into source code which might be needed sometimes.
| https://stackoverflow.com/questions/60966721/ |
Reset Random Initialization on Pytorch | I want to do some experiments on feedforward neural networks. To make a fair comparison, I need them to have the exact same random initialisation. How can I do it?
Is there a way to save the same initial weights such that I can train a network and then reinitialize it exactly as it was before?
I have been trying to save the initial parameters on a list, called 'init' , and then reassign the parameters but it did not work:
i = 0
for name, param in model.named_parameters():
param = init[i]
i += 1
Any suggestion?
| You can try seeding random via:
torch.manual_seed(seed)
torch.manual_seed_all(seed)
Note you have to seed random before each model initialisation. If this doesn't work, try the following:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
| https://stackoverflow.com/questions/60975415/ |
How can I get the MSE of a tensor across a specific dimension? | I have 2 tensors with .size of torch.Size([2272, 161]). I want to get mean-squared-error between them. However, I want it along each of the 161 channels, so that my error tensor has a .size of torch.Size([161]). How can I accomplish this?
It seems that torch.nn.MSELoss doesn't let me specify a dimension.
| For the nn.MSELoss you can specify the option reduction='none'. This then gives you back the squared error for each entry position of both of your tensors. Then you can apply torch.sum/torch.mean.
a = torch.randn(2272,161)
b = torch.randn(2272,161)
loss = nn.MSELoss(reduction='none')
loss_result = torch.sum(loss(a,b),dim=0)
I don't think there is a direct way to specify at the initialisation of the loss to which dimension to apply mean/sum. Hope that helps!
| https://stackoverflow.com/questions/60976758/ |
Modifying validation function for single image instead of Tencrop | I have a PublicTest function that runs every epoch for validation and there is a transform test variable that transforms the validation data as above:
transform_test = transforms.Compose([
transforms.TenCrop(cut_size),
transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),
])
def PublicTest(epoch):
global PublicTest_acc
global best_PublicTest_acc
global best_PublicTest_acc_epoch
net.eval()
PublicTest_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(PublicTestloader):
bs, ncrops, c, h, w = np.shape(inputs)
inputs = inputs.view(-1, c, h, w)
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs, volatile=True), Variable(targets)
outputs = net(inputs)
outputs_avg = outputs.view(bs, ncrops, -1).mean(1) # avg over crops
loss = criterion(outputs_avg, targets)
PublicTest_loss += loss.item()
_, predicted = torch.max(outputs_avg.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum()
utils.progress_bar(batch_idx, len(PublicTestloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (PublicTest_loss / (batch_idx + 1), 100. * correct / total, correct, total))
I'd like to modify the code so instead of Tencrop each image would be validated once. I changed the transform_test like this
transform_test = transforms.Compose([transforms.ToTensor()])
I run the code but had the realized that PublicTest have ncrops as a parameter and received the error:
File "mainpro_FER.py", line 147, in PublicTest
bs, ncrops, c, h, w = np.shape(inputs)
ValueError: not enough values to unpack (expected 5, got 4)
removed ncrops parameter in the function, tried again had this error:
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
So I need a way to make this function work for single image for every images in batch unlike TenCrop.
Thanks.
| Nevermind guys, I figured out just like this:
def PublicTest(epoch):
global PublicTest_acc
global best_PublicTest_acc
global best_PublicTest_acc_epoch
net.eval()
PublicTest_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(PublicTestloader):
bs, c, h, w = np.shape(inputs)
inputs = inputs.view(-1, c, h, w)
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs, volatile=True), Variable(targets)
outputs = net(inputs)
# outputs_avg = outputs.view(bs, ncrops, -1).mean(1) # avg over crops
loss = criterion(outputs, targets)
PublicTest_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum()
utils.progress_bar(batch_idx, len(PublicTestloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (PublicTest_loss / (batch_idx + 1), 100. * correct / total, correct, total))
| https://stackoverflow.com/questions/60977205/ |
How can I get one array to return only the masked values define by another array with Numpy / PyTorch? | I have a mask, which has a shape of: [64, 2895] and an array pred which has a shape of [64, 2895, 161].
mask is binary with only 0s and 1s. What I want to do is reduce pred so that it maintains 64 batches, and along the 2895, wherever there is a 1 in the mask for each batch, return the related pred.
So as a simplified example, if:
mask = [[1, 0, 0],
[1, 1, 0],
[0, 0, 1]]
pred = [[[0.12, 0.23, 0.45, 0.56, 0.57],
[0.91, 0.98, 0.97, 0.96, 0.95],
[0.24, 0.46, 0.68, 0.80, 0.15]],
[[1.12, 1.23, 1.45, 1.56, 1.57],
[1.91, 1.98, 1.97, 1.96, 1.95],
[1.24, 1.46, 1.68, 1.80, 1.15]],
[[2.12, 2.23, 2.45, 2.56, 2.57],
[2.91, 2.98, 2.97, 2.96, 2.95],
[2.24, 2.46, 2.68, 2.80, 2.15]]]
What I want is:
[[[0.12, 0.23, 0.45, 0.56, 0.57]],
[[1.12, 1.23, 1.45, 1.56, 1.57],
[1.91, 1.98, 1.97, 1.96, 1.95]],
[[2.24, 2.46, 2.68, 2.80, 2.15]]]
I realize that there are different dimensions, I hope that that's possible. If not, then fill in the missing dimensions with 0. Either numpy or pytorch would be helpful. Thank you.
| If you want a vectorized computation then different dimension seems not possible, but this would give you the one with masked entry filled with 0:
# pred: torch.size([64, 2895, 161])
# mask: torch.size([64, 2895])
result = pred * mask[:, :, None]
# extend mask with another dimension so now it can do entry-wise multiplication
and result is exactly what you want
| https://stackoverflow.com/questions/60980181/ |
What does "*" operator do before the tensor size in PyTorch? | I am now learning building neural networks in PyTorch. Here are the codes cut from the .py file:
x = torch.unsqueeze(torch.linspace(-1, 1, 1000), dim=1)
y = x.pow(2) + 0.1*torch.normal(torch.zeros(*x.size()))
I am quite comfused about the utility of the * operator before x.size(). I tried to delete it and plot the scatter graph, which was proved the same as the one with * not removed.
I also checked the official documentation of size in https://pytorch.org/docs/stable/tensors.html but I couldn't figure it out.
Image of torch.size item in documentation
I'd appreciate it very much if you may help me.
| the reason that * makes no difference in the results here is because torch.zero except both a variable number of arguments and a collection like a list or tuple as mentioned here. It does not mean * itself is useless.
Then, since torch.Size() class is a subclass of python tuple, one can unpack it using *. (x.size() will return a torch.Size() object)
So to wrap up, x.size() would give you (1000, 1) and *x.size() in the argument would give you 1000, 1 and both are accepted by torch.zeros()
| https://stackoverflow.com/questions/60981102/ |
how target[y == l] = label work is labeling make_blobs dataset in pytorch tutorial? | I am learning PyTorch with this blog: [PyTorch Introduction to Neural Network] (https://medium.com/biaslyai/pytorch-introduction-to-neural-network-feedforward-neural-network-model-e7231cff47cb)
I found this piece of code confusing:
from sklearn.datasets import make_blobs
def blob_label(y, label, loc): # assign labels
target = numpy.copy(y)
for l in loc:
target[y == l] = label
return target
x_train, y_train = make_blobs(n_samples=40, n_features=2, cluster_std=1.5, shuffle=True)
x_train = torch.FloatTensor(x_train)
y_train = torch.FloatTensor(blob_label(y_train, 0, [0]))
y_train = torch.FloatTensor(blob_label(y_train, 1, [1,2,3]))
x_test, y_test = make_blobs(n_samples=10, n_features=2, cluster_std=1.5, shuffle=True)
x_test = torch.FloatTensor(x_test)
y_test = torch.FloatTensor(blob_label(y_test, 0, [0]))
y_test = torch.FloatTensor(blob_label(y_test, 1, [1,2,3]))
how exactly is target[y == l] = label working in here?
how this line of code assigns 1s and 0s to the data?
Thanks!
| It's Boolean or “mask” index arrays see doc for more
>>> y = torch.arange(9).reshape(3,3)
>>> y
tensor([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> target = np.copy(y)
so, target[y == l] = label
y == l give us boolean array like (if l = 0)
>>> y == 0
tensor([[ True, False, False],
[False, False, False],
[False, False, False]])
and we can access and assign value using boolean array y == 0
>>> target[y == 0]
array([0], dtype=int64)
>>> target[y == 0] = 999
>>> target
array([[999, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]], dtype=int64)
| https://stackoverflow.com/questions/60981135/ |
Why the backpropagation process can still work when I included 'loss.backward()' in 'with torch.no_grad():'? | I'm working with a linear regression example in PyTorch. I know I did wrong including 'loss.backward()' in 'with torch.no_grad():', but why it worked well with my code?
According to pytorch docs, torch.autograd.no_grad is a context-manager that disabled gradient calculation. So I'm really confused.
Code here:
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Toy dataset
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
[9.779], [6.182], [7.59], [2.167], [7.042],
[10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
[3.366], [2.596], [2.53], [1.221], [2.827],
[3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
input_size = 1
output_size = 1
epochs = 100
learning_rate = 0.05
model = nn.Linear(input_size, output_size)
criterion = nn.MSELoss(reduction='sum')
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# training
for epoch in range(epochs):
# convert numpy to tensor
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
# forward
out = model(inputs)
loss = criterion(out, targets)
# backward
with torch.no_grad():
model.zero_grad()
loss.backward()
optimizer.step()
print('inputs grad : ', inputs.requires_grad)
if epoch % 5 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
predicted = model(torch.from_numpy(x_train)).detach().numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predicted, label='Fitted line')
plt.legend()
plt.show()
# Save the model checkpoint
torch.save(model.state_dict(), 'model\linear_model.ckpt')
Thanks in advance for answering my question.
| This worked because the loss calculation has happened before the no_grad and you keep calculating the gradients according to that loss calculation (which calculation had gradient enabled).
Basically, you continue update the weights of your layers using the gradients calculated outside of the no_grad.
When you actually use the no_grad:
for epoch in range(epochs):
# convert numpy to tensor
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
with torch.no_grad(): # no_grad used here
# forward
out = model(inputs)
loss = criterion(out, targets)
model.zero_grad()
loss.backward()
optimizer.step()
print('inputs grad : ', inputs.requires_grad)
if epoch % 5 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
Then you will get the proper error, saying:
element 0 of tensors does not require grad and does not have a grad_fn.
That is, you use no_grad where is not appropriate to use it.
If you print the .requires_grad of loss, then you will see that loss has requires_grad.
That is, when you do this:
for epoch in range(epochs):
# convert numpy to tensor
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
# forward
out = model(inputs)
loss = criterion(out, targets)
# backward
with torch.no_grad():
model.zero_grad()
loss.backward()
optimizer.step()
print('inputs grad : ', inputs.requires_grad)
print('loss grad : ', loss.requires_grad) # Prints loss.require_rgad
if epoch % 5 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
You will see:
inputs grad : False
loss grad : True
Additionally, the
print('inputs grad : ', inputs.requires_grad)
Will always print False. That is, if you do
for epoch in range(epochs):
# convert numpy to tensor
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
print('inputs grad : ', inputs.requires_grad). # Print the inputs.requires_grad
# forward
out = model(inputs)
loss = criterion(out, targets)
# backward
with torch.no_grad():
model.zero_grad()
loss.backward()
optimizer.step()
print('inputs grad : ', inputs.requires_grad)
print('loss grad : ', loss.requires_grad)
if epoch % 5 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
You will get:
inputs grad : False
inputs grad : False
loss grad : True
That is, you are using wrong things to check what you did wrong. The best thing that you can do is to read again the docs of PyTorch on gradient mechanics.
| https://stackoverflow.com/questions/60984003/ |
Why `torch.cuda.is_available()` returns False even after installing pytorch with cuda? | On a Windows 10 PC with an NVidia GeForce 820M
I installed CUDA 9.2 and cudnn 7.1 successfully,
and then installed PyTorch using the instructions at pytorch.org:
pip install torch==1.4.0+cu92 torchvision==0.5.0+cu92 -f https://download.pytorch.org/whl/torch_stable.html
But I get:
>>> import torch
>>> torch.cuda.is_available()
False
| Your graphics card does not support CUDA 9.0.
Since I've seen a lot of questions that refer to issues like this I'm writing a broad answer on how to check if your system is compatible with CUDA, specifically targeted at using PyTorch with CUDA support. Various circumstance-dependent options for resolving issues are described in the last section of this answer.
The system requirements to use PyTorch with CUDA are as follows:
Your graphics card must support the required version of CUDA
Your graphics card driver must support the required version of CUDA
The PyTorch binaries must be built with support for the compute capability of your graphics card
Note: If you install pre-built binaries (using either pip or conda) then you do not need to install the CUDA toolkit or runtime on your system before installing PyTorch with CUDA support. This is because PyTorch, unless compiled from source, is always delivered with a copy of the CUDA library.
1. How to check if your GPU/graphics card supports a particular CUDA version
First, identify the model of your graphics card.
Before moving forward ensure that you've got an NVIDIA graphics card. AMD and Intel graphics cards do not support CUDA.
NVIDIA doesn't do a great job of providing CUDA compatibility information in a single location. The best resource is probably this section on the CUDA Wikipedia page. To determine which versions of CUDA are supported
Locate your graphics card model in the big table and take note of the compute capability version. For example, the GeForce 820M compute capability is 2.1.
In the bullet list preceding the table check to see if the required CUDA version is supported by the compute capability of your graphics card. For example, CUDA 9.2 is not supported for compute compatibility 2.1.
If your card doesn't support the required CUDA version then see the options in section 4 of this answer.
Note: Compute capability refers to the computational features supported by your graphics card. Newer versions of the CUDA library rely on newer hardware features, which is why we need to determine the compute capability in order to determine the supported versions of CUDA.
2. How to check if your GPU/graphics driver supports a particular CUDA version
The graphics driver is the software that allows your operating system to communicate with your graphics card. Since CUDA relies on low-level communication with the graphics card you need to have an up-to-date driver in order use the latest versions of CUDA.
First, make sure you have an NVIDIA graphics driver installed on your system. You can acquire the newest driver for your system from NVIDIA's website.
If you've installed the latest driver version then your graphics driver probably supports every CUDA version compatible with your graphics card (see section 1). To verify, you can check Table 3 in the CUDA release notes. In rare cases I've heard of the latest recommended graphics drivers not supporting the latest CUDA releases. You should be able to get around this by installing the CUDA toolkit for the required CUDA version and selecting the option to install compatible drivers, though this usually isn't required.
If you can't, or don't want to upgrade the graphics driver then you can check to see if your current driver supports the specific CUDA version as follows:
On Windows
Determine your current graphics driver version (Source https://www.nvidia.com/en-gb/drivers/drivers-faq/)
Right-click on your desktop and select NVIDIA Control Panel. From the
NVIDIA Control Panel menu, select Help > System Information. The
driver version is listed at the top of the Details window. For more
advanced users, you can also get the driver version number from the
Windows Device Manager. Right-click on your graphics device under
display adapters and then select Properties. Select the Driver tab and
read the Driver version. The last 5 digits are the NVIDIA driver
version number.
Visit the CUDA release notes and scroll down to Table 3. Use this table to verify your graphics driver is new enough to support the required version of CUDA.
On Linux/OS X
Run the following command in a terminal window
nvidia-smi
This should result in something like the following
Sat Apr 4 15:31:57 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 435.21 Driver Version: 435.21 CUDA Version: 10.1 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce RTX 206... Off | 00000000:01:00.0 On | N/A |
| 0% 35C P8 16W / 175W | 502MiB / 7974MiB | 1% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 1138 G /usr/lib/xorg/Xorg 300MiB |
| 0 2550 G /usr/bin/compiz 189MiB |
| 0 5735 G /usr/lib/firefox/firefox 5MiB |
| 0 7073 G /usr/lib/firefox/firefox 5MiB |
+-----------------------------------------------------------------------------+
Driver Version: ###.## is your graphic driver version. In the example above the driver version is 435.21.
CUDA Version: ##.# is the latest version of CUDA supported by your graphics driver. In the example above the graphics driver supports CUDA 10.1 as well as all compatible CUDA versions before 10.1.
Note: The CUDA Version displayed in this table does not indicate that the CUDA toolkit or runtime are actually installed on your system. This just indicates the latest version of CUDA your graphics driver is compatible with.
To be extra sure that your driver supports the desired CUDA version you can visit Table 3 on the CUDA release notes page.
3. How to check if a particular version of PyTorch is compatible with your GPU/graphics card compute capability
Even if your graphics card supports the required version of CUDA then it's possible that the pre-compiled PyTorch binaries were not compiled with support for your compute capability. For example, in PyTorch 0.3.1 support for compute capability <= 5.0 was dropped.
First, verify that your graphics card and driver both support the required CUDA version (see Sections 1 and 2 above), the information in this section assumes that this is the case.
The easiest way to check if PyTorch supports your compute capability is to install the desired version of PyTorch with CUDA support and run the following from a python interpreter
>>> import torch
>>> torch.zeros(1).cuda()
If you get an error message that reads
Found GPU0 XXXXX which is of cuda capability #.#.
PyTorch no longer supports this GPU because it is too old.
then that means PyTorch was not compiled with support for your compute capability. If this runs without issue then you should be good to go.
Update If you're installing an old version of PyTorch on a system with a newer GPU then it's possible that the old PyTorch release wasn't compiled with support for your compute capability. Assuming your GPU supports the version of CUDA used by PyTorch, then you should be able to rebuild PyTorch from source with the desired CUDA version or upgrade to a more recent version of PyTorch that was compiled with support for the newer compute capabilities.
4. Conclusion
If your graphics card and driver support the required version of CUDA (section 1 and 2) but the PyTorch binaries don't support your compute capability (section 3) then your options are
Compile PyTorch from source with support for your compute capability (see here)
Install PyTorch without CUDA support (CPU-only)
Install an older version of the PyTorch binaries that support your compute capability (not recommended as PyTorch 0.3.1 is very outdated at this point). AFAIK compute capability older than 3.X has never been supported in the pre-built binaries
Upgrade your graphics card
If your graphics card doesn't support the required version of CUDA (section 1) then your options are
Install PyTorch without CUDA support (CPU-only)
Install an older version of PyTorch that supports a CUDA version supported by your graphics card (still may require compiling from source if the binaries don't support your compute capability)
Upgrade your graphics card
| https://stackoverflow.com/questions/60987997/ |
How can I save PyTorch's DataLoader instance? | I want to save PyTorch's torch.utils.data.dataloader.DataLoader instance, so that I can continue training where I left off (keeping shuffle seed, states and everything).
| It's quite simple. One should design their own Sampler which takes the starting index and shuffles the data by itself:
import random
from torch.utils.data.dataloader import Sampler
random.seed(224) # use a fixed number
class MySampler(Sampler):
def __init__(self, data, i=0):
random.shuffle(data)
self.seq = list(range(len(data)))[i * batch_size:]
def __iter__(self):
return iter(self.seq)
def __len__(self):
return len(self.seq)
Now save the last index i somewhere and the next time instantiate the DataLoader using it:
train_dataset = MyDataset(train_data)
train_sampler = MySampler(train_dataset, last_i)
train_data_loader = DataLoader(dataset=train_dataset,
batch_size=batch_size,
sampler=train_sampler,
shuffle=False) # don't forget to set DataLoader's shuffle to False
It's quite useful when training on Colab.
| https://stackoverflow.com/questions/60993677/ |
How do I assign a numpy.int64 to a torch.cuda.FloatTensor? | Im not able to assign int64 to torch tensor. I have got the following tensor
tempScale = torch.zeros((total, len(scale))).cuda() if useGpu else torch.zeros((nbPatchTotal, len(scale)))
In my code, when I'm using the following line, it's throwing an error message
tmpScale[:, j] = scale
The error message is
TypeError: can't assign a numpy.int64 to a torch.cuda.FloatTensor
what am I missing?
| You have to convert scale to a torch tensor of the same type and device as tmpScale before assignment.
tmpScale[:, j] = torch.from_numpy(scale).to(tmpScale)
Note that this is casting scale from an int64 to a float32 which will likely result in a loss of precision if values in scale have magnitude larger than 224 (about 16 million).
| https://stackoverflow.com/questions/60996756/ |
Empty state_dict with vector or tuple of layers in nn.Module | I switched to using a Version with a parametrized number of layers of torch.nn.Module like Net_par below, only to find out all the saved state_dicts were empty after quite some optimizing.^^
This method is the recommended saving operation (https://pytorch.org/docs/stable/notes/serialization.html#recommend-saving-models), still layers stored in a vector (or tuple, for that matter) are discarded when constructing the state_dict.
torch.save works properly in contrast, but adds to data and limits robustness. This feels a little like a bug, can anybody help with a workaround?
Minimal example for comparison between parametrized and fixed layer count:
import torch
import torch.nn as nn
class Net_par(nn.Module):
def __init__(self,layer_dofs):
super(Net_par, self).__init__()
self.layers=[]
for i in range(len(layer_dofs)-1):
self.layers.append(nn.Linear(layer_dofs[i],layer_dofs[i+1]))
def forward(self, x):
for i in range(len(self.layers)-1):
x = torch.tanh(self.layers[i](x))
return torch.tanh(self.layers[len(self.layers)-1](x))
class Net_sta(nn.Module):
def __init__(self,dof1,dof2):
super(Net_sta, self).__init__()
self.layer=nn.Linear(dof1,dof2)
def forward(self, x):
return torch.tanh(self.layer1(x))
if __name__=="__main__":
net_par=Net_par((3,4))
net_sta=Net_sta(3,4)
print(str(net_par.state_dict()))
#OrderedDict() <------Why?!
print(str(net_sta.state_dict()))
#OrderedDict([('layer.weight', tensor([[...
# ...]])), ('layer.bias', tensor([... ...]))])
| You need to use nn.ModuleList() instead of simple python list.
class Net_par(nn.Module):
...
self.layers = nn.ModuleList([])
| https://stackoverflow.com/questions/60997648/ |
How to change DataLoader in PyTorch to read one image for prediction? | Currently, I have a pre-trained model that uses a DataLoader for reading a batch of images for training the model.
self.data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False,
num_workers=1, pin_memory=True)
...
model.eval()
for step, inputs in enumerate(test_loader.data_loader):
outputs = model(torch.cat([inputs], 1))
...
I want to process (make predictions) on images, as they arrive from a queue. It should be similar to a code that reads a single image and runs the model to make predictions on it. Something along the following lines:
from PIL import Image
new_input = Image.open(image_path)
model.eval()
outputs = model(torch.cat([new_input ], 1))
I was wondering if you could guide me how to do this and apply the same transformations in the DataLoader.
| You can use do it with IterableDataset :
from torch.utils.data import IterableDataset
class MyDataset(IterableDataset):
def __init__(self, image_queue):
self.queue = image_queue
def read_next_image(self):
while self.queue.qsize() > 0:
# you can add transform here
yield self.queue.get()
return None
def __iter__(self):
return self.read_next_image()
and batch_size = 1 :
import queue
import torchvision.transforms.functional as TF
buffer = queue.Queue()
new_input = Image.open(image_path)
buffer.put(TF.to_tensor(new_input))
# ... Populate queue here
dataset = MyDataset(buffer)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1)
for data in dataloader:
model(data) # data is one-image batch of size [1,3,H,W] where 3 - number of color channels
| https://stackoverflow.com/questions/61001855/ |
How to convert a list of different-sized tensors to a single tensor? | I want to convert a list of tensors with different sizes to a single tensor.
I tried torch.stack, but it shows an error.
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-237-76c3ff6f157f> in <module>
----> 1 torch.stack(t)
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 5 and 6 in dimension 1 at C:\w\1\s\tmp_conda_3.7_105232\conda\conda-bld\pytorch_1579085620499\work\aten\src\TH/generic/THTensor.cpp:612
My list of tensors:
[tensor([-0.1873, -0.6180, -0.3918, -0.5849, -0.3607]),
tensor([-0.6873, -0.3918, -0.5849, -0.9768, -0.7590, -0.6707]),
tensor([-0.6686, -0.7022, -0.7436, -0.8231, -0.6348, -0.4040, -0.6074, -0.6921])]
I have also tried this in a different way, instead of tensors, I used a lists of these individual tensors and tried to make a tensor out of it. That also showed an error.
list: [[-0.18729999661445618, -0.6179999709129333, -0.3917999863624573, -0.5849000215530396, -0.36070001125335693], [-0.6873000264167786, -0.3917999863624573, -0.5849000215530396, -0.9768000245094299, -0.7590000033378601, -0.6707000136375427], [-0.6686000227928162, -0.7021999955177307, -0.7436000108718872, -0.8230999708175659, -0.6348000168800354, -0.40400001406669617, -0.6074000000953674, -0.6920999884605408]]
The error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-245-489aea87f307> in <module>
----> 1 torch.FloatTensor(t)
ValueError: expected sequence of length 5 at dim 1 (got 6)
Apparently, it says, it is expecting the same length of lists if I am not wrong.
Can anyone help here?
| I agree with @helloswift123, you cannot stack tensors of different lengths.
Also, @helloswift123's answer will work only when the total number of elements is divisible by the shape that you want. In this case, the total number of elements is 19 and in no case, it can be reshaped into something useful since it is a prime number.
torch.cat() as suggested,
data = [torch.tensor([-0.1873, -0.6180, -0.3918, -0.5849, -0.3607]),
torch.tensor([-0.6873, -0.3918, -0.5849, -0.9768, -0.7590, -0.6707]),
torch.tensor([-0.6686, -0.7022, -0.7436, -0.8231, -0.6348, -0.4040, -0.6074, -0.6921])]
dataTensor = torch.cat(data)
dataTensor.numel()
Output:
tensor([-0.1873, -0.6180, -0.3918, -0.5849, -0.3607, -0.6873, -0.3918, -0.5849,
-0.9768, -0.7590, -0.6707, -0.6686, -0.7022, -0.7436, -0.8231, -0.6348,
-0.4040, -0.6074, -0.6921])
19
Possible solution:
This is also not a perfect solution but might solve this problem.
# Have a list of tensors (which can be of different lengths)
data = [torch.tensor([-0.1873, -0.6180, -0.3918, -0.5849, -0.3607]),
torch.tensor([-0.6873, -0.3918, -0.5849, -0.9768, -0.7590, -0.6707]),
torch.tensor([-0.6686, -0.7022, -0.7436, -0.8231, -0.6348, -0.4040, -0.6074, -0.6921])]
# Determine maximum length
max_len = max([x.squeeze().numel() for x in data])
# pad all tensors to have same length
data = [torch.nn.functional.pad(x, pad=(0, max_len - x.numel()), mode='constant', value=0) for x in data]
# stack them
data = torch.stack(data)
print(data)
print(data.shape)
Output:
tensor([[-0.1873, -0.6180, -0.3918, -0.5849, -0.3607, 0.0000, 0.0000, 0.0000],
[-0.6873, -0.3918, -0.5849, -0.9768, -0.7590, -0.6707, 0.0000, 0.0000],
[-0.6686, -0.7022, -0.7436, -0.8231, -0.6348, -0.4040, -0.6074, -0.6921]])
torch.Size([3, 8])
This will append zeros to the end of any tensor which is having fewer elements and in this case you can use torch.stack() as usual.
I hope this helps!
| https://stackoverflow.com/questions/61003467/ |
Python, Pytorch, having trouble using cuda | OS: Windows 10
Python 3.7.4 (Conda)
GPU: GTX 980
So I installed CUDA toolkit v.10.1, got the matching cuDNN files, installed the cuda 10.1 enabled pytorch version and in addition to that i updated my gpu drivers. but if i now try to check wether my gpu is available with torch.cuda.is_available() it still get a False. Any Ideas??
| You need to make sure that your python is running on GPU instead of CPU.
You can do this by starting your IDE on GPU by selecting from right-click options. Just right click on your IDE and select Run with graphics processer. Like Shown in picture below.
Alternatively, you can go to Nvidia Control Panel > Manage 3D Settings > Program Settings and customize the default Graphics Processor of Python and your IDE to NVIDIA GPU. The control panel can be seen below.
| https://stackoverflow.com/questions/61008209/ |
Sum over indices with value (1) | I have a tensor with a shape (2, 2, 3) like:
a= tensor ([[[2, 0, 2],[1, 0, 0]],[[1, 0, 1],[0, 1, 0]]])
I want to find the indices of the values (1), then make 2 to the power of those indices and finally add the results for the last dimension, so the final result should be like:
tensor ([[[],[2^0]],[[2^0+2^2],[2^1]]])
My actual tensor is much bigger than this example, so I don’t want to use "for" loop, and I have to use broadcasting…
I was thinking of something like torch.pow(2,(a == 1).nonzero()).sum(), but it doesn’t work. I have to find a way to apply (a== 1).nonzero() only for the last dimension, any suggestion? Thanks.
| Change it to NumPy and apply this:
a_n = a.numpy()
a_n = np.apply_along_axis(func1d=lambda x: np.sum(np.power(2,np.where(x==1))[0]), axis=2, arr=a_n)
a = torch.Tensor(a_n)
Basically, it applies the function you want in axis=2, I'm supposing your larger array is something like (2,2,n)
| https://stackoverflow.com/questions/61011962/ |
How to properly run my project using GPU? | I am really new to torch and machine learning. I am trying to run my project using GPU. I tried to have such modification to my code:
model = Challenge()
model = model.to(torch.device('cuda'))
However, I am still having following error:
Traceback (most recent call last):
File "C:/Users/ruidong/Desktop/YZR temp/Project2/train_challenge.py", line 112, in <module>
main()
File "C:/Users/ruidong/Desktop/YZR temp/Project2/train_challenge.py", line 91, in main
stats)
File "C:/Users/ruidong/Desktop/YZR temp/Project2/train_challenge.py", line 40, in _evaluate_epoch
output = model(X)
File "C:\Users\ruidong\Anaconda3\envs\EECS445\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\ruidong\Desktop\YZR temp\Project2\model\challenge.py", line 48, in forward
z = F.relu(self.conv1(x))
File "C:\Users\ruidong\Anaconda3\envs\EECS445\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\ruidong\Anaconda3\envs\EECS445\lib\site-packages\torch\nn\modules\conv.py", line 345, in forward
return self.conv2d_forward(input, self.weight)
File "C:\Users\ruidong\Anaconda3\envs\EECS445\lib\site-packages\torch\nn\modules\conv.py", line 342, in conv2d_forward
self.padding, self.dilation, self.groups)
RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _thnn_conv2d_forward
Any suggestions? really appreciate.
| The model is correctly moved to GPU. However, for a model that is placed in GPU, you need to pass the tensors that are in GPU too. The error is because you are passing tensor that is placed in CPU in a model that is in GPU. Just do the same for inputs before passing them to model
| https://stackoverflow.com/questions/61014484/ |
RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True | I'm a student and a beginner in Python and PyTorch both. I have a very basic Neural Network for which I am encountering the mentioned RunTimeError. The code to reproduce the error is this:
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
# Ensure Reproducibility
torch.manual_seed(0)
# Data Generation
x = torch.randn((100,1), requires_grad = True)
y = 1 + 2 * x + 0.3 * torch.randn(100,1)
# Shuffles the indices
idx = np.arange(100)
np.random.shuffle(idx)
# Uses first 80 random indices for train
train_idx = idx[:70]
# Uses the remaining indices for validation
val_idx = idx[70:]
# Generates train and validation sets
x_train, y_train = x[train_idx], y[train_idx]
x_val, y_val = x[val_idx], y[val_idx]
class OurFirstNeuralNetwork(nn.Module):
def __init__(self):
super(OurFirstNeuralNetwork, self).__init__()
# Here we "define" our Neural Network Architecture
self.fc1 = nn.Linear(1, 5)
self.non_linearity_fc1 = nn.ReLU()
self.fc2 = nn.Linear(5,1)
#self.non_linearity_fc2 = nn.ReLU()
def forward(self, x):
# The forward pass
# Here we define how activations "flow" between neurons. We've already discussed the "Sum" and "Transformation" steps of the forward pass.
sum_fc1 = self.fc1(x)
transformation_fc1 = self.non_linearity_fc1(sum_fc1)
sum_fc2 = self.fc2(transformation_fc1)
#transformation_fc2 = self.non_linearity_fc2(sum_fc2)
# The transformation_fc2 is also the output of our model which symbolises the end of our forward pass.
return sum_fc2
# Instantiate the model and train
model = OurFirstNeuralNetwork()
print(model)
print(model.state_dict())
n_epochs = 1000
loss_fn = nn.MSELoss(reduction='mean')
optimizer = optim.Adam(model.parameters())
for epoch in range(n_epochs):
model.train()
optimizer.zero_grad()
prediction = model(x_train)
loss = loss_fn(y_train, prediction)
print(epoch, loss)
loss.backward(retain_graph=True)
optimizer.step()
print(model.state_dict())
Everything is basic and standard and this works fine.
However, when I take out the "retain_graph=True" argument, it throws the RunTimeError. From reading various forums, I understand that this is to do with the graph getting thrown away after the first iteration but I have seen many tutorials and blogs where loss.backward() is the way to go especially since it conserves memory. But I am not able to conceptually grasp why the same does not work for me.
Any help is appreciated and my apologies if the way in which I have asked my question is not in the expected format. I am open to feedback and will oblige to include more details or rephrase the question so that it is easier for everyone. Thank you in advance!
| You need to add optimizer.zero_grad() after optimizer.step() to zero out the gradients.
Why you need to do this?
When you do loss.backward() torch will compute gradients for parameters and update the parameter's .grad property. When you do optimizer.step(), the parameters are updated using the .grad property as i.e `parameter = parameter - lr*parameter.grad.
Since you do not clear the gradients and call backward the second time, it will compute dl/d(updated param) which will require to backpropagate through paramter.grad of the first pass. When doing backward, the computation graph of this gradients is not stored and hence you have to pass retain_graph= True to get rid of error. However, we don't want to do that for updating params. Rather we want to clear gradients, and restart with a new computation graph therefore, you need to zero the gradients with a .zero_grad call.
Also see Why do we need to call zero_grad() in PyTorch?
| https://stackoverflow.com/questions/61015728/ |
torch.nn.conv2d does not give the same result as torch.nn.functional.conv2d | This is my code:
l1 = nn.Conv2d(3, 2, kernel_size=3, stride=2).double() #Layer
l1wt = l1.weight.data #filter
inputs = np.random.rand(3, 3, 5, 5) #input
it = torch.from_numpy(inputs) #input tensor
output1 = l1(it) #output
output2 = torch.nn.functional.conv2d(it, l1wt, stride=2) #output
print(output1)
print(output2)
I would expect to get the same result for output1 and output2, but they are not.
Am I doing something wrong are do nn and nn.functional work different?
| I think you forgot the bias.
inp = torch.rand(3,3,5,5)
a = nn.Conv2d(3,2,3,stride=2)
a(inp)
nn.functional.conv2d(inp, a.weight.data, bias=a.bias.data)
Looks the same to me
| https://stackoverflow.com/questions/61018705/ |
Pytorch cross entropy input dimensions | I'm trying to develop a binary classifier with Huggingface's BertModel and Pytorch.
The classifier module is something like this:
class SSTClassifierModel(nn.Module):
def __init__(self, num_classes = 2, hidden_size = 768):
super(SSTClassifierModel, self).__init__()
self.number_of_classes = num_classes
self.dropout = nn.Dropout(0.01)
self.hidden_size = hidden_size
self.bert = BertModel.from_pretrained('bert-base-uncased')
self.classifier = nn.Linear(hidden_size, num_classes)
def forward(self, input_ids, att_masks,token_type_ids, labels):
_, embedding = self.bert(input_ids, token_type_ids, att_masks)
output = self.classifier(self.dropout(embedding))
return output
The way I train the model is as follows:
loss_function = BCELoss()
model.train()
for epoch in range(NO_OF_EPOCHS):
for step, batch in enumerate(train_dataloader):
input_ids = batch[0].to(device)
input_mask = batch[1].to(device)
token_type_ids = batch[2].to(device)
labels = batch[3].to(device)
# assuming batch size = 3, labels is something like:
# tensor([[0],[1],[1]])
model.zero_grad()
model_output = model(input_ids,
input_mask,
token_type_ids,
labels)
# model output is something like: (with batch size = 3)
# tensor([[ 0.3566, -0.0333],
#[ 0.1154, 0.2842],
#[-0.0016, 0.3767]], grad_fn=<AddmmBackward>)
loss = loss_function(model_output.view(-1,2) , labels.view(-1))
I'm doing the .view()s because of the Huggingface's source code for BertForSequenceClassification here which uses the exact same way to compute the loss. But I get this error:
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in binary_cross_entropy(input, target, weight, size_average, reduce, reduction)
2068 if input.numel() != target.numel():
2069 raise ValueError("Target and input must have the same number of elements. target nelement ({}) "
-> 2070 "!= input nelement ({})".format(target.numel(), input.numel()))
2071
2072 if weight is not None:
ValueError: Target and input must have the same number of elements. target nelement (3) != input nelement (6)
Is there something wrong with my labels? or my model's output? I'm really stuck here. The documentation for Pytorch's BCELoss says:
Input: (N,∗) where ∗ means, any number of additional dimensions
Target: (N,∗), same shape as the input
How should I make my labels the same shape as the model output? I feel like there's something huge that I'm missing but I can't find it.
| Few observations:
The code that you refer to uses CrossEntropyLoss but you are using BCELoss.
CrossEntropyLoss takes prediction logits (size: (N,D)) and target labels (size: (N,)) whereas BCELoss takes p(y=1|x) (size: (N,)) and target labels (size: (N,)) as p(y=0|x) can be computed from p(y=1|x)
CrossEntropyLoss expects logits i.e whereas BCELoss expects probability value
Solution:
Since you pass an (N,2) tensor, it gives an error. You only need to pass p(y=1|x), therefore you can do
loss = loss_function(model_output.view(-1,2)[:,1] , labels.view(-1))
above I assumed that the second value is p(y=1|x).
A cleaner way would be to make model output only one value i.e p(y=1|x) and pass it to the loss function. It seems from the code that you are passing logit values and not probability values, so you may also need to compute sigmoid (model_output) if you want to use BCELoss or alternatively you can use BCEWithLogitsLoss.
Another alternative is to change the loss to CrossEntropyLoss that should work too as it can work for binary labels too.
| https://stackoverflow.com/questions/61019485/ |
Get local world size in torch distributed training | Suppose I have 2 machines with 4 GPUs each. Suppose that each instance of the training algorithm requires 2 GPUs.
I would like to run 4 processes, 2 for each machine, each process using 2 GPUs.
How can I make each process retrieve the number of local processes running on the same machine?
I can detect the world size with
torch.distributed.get_world_size()
and the global rank with
torch.distributed.get_rank()
But, given that I would like not to hard code parameters, is there a way to recover that on each node are running 2 processes? This will be usefull to me to assign GPUs to each process equally.
Example: Suppose I know that a machine has 4 GPUs and that there are 2 processes on it, I will assign GPUs [0, 1] to process with local rank 0 and GPUs [2, 3] to process with local rank 1. I know total number of processes but I cannot understand if they are on the same machine, so I cannot decide how many GPUs they are allowed to use.
I need a function that would be called torch.distributed.get_local_world_size()
| torch.cuda.device_count() is essentially the local world size and could be useful in determining how many GPUs you have available on each device. If you can't do that for some reason, using plain MPI might help
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank() # device rank - [0,1]
torch.cuda.device(i)
ngpus = torch.cuda.device_count()
print(ngpus, " gpus on machine", i) # here's local world size for each process
but I think it would work just to call torch.cuda.device_count() in any case without adding this dependency. I am pretty new here so if you can, please let me know how this answer can be improved.
| https://stackoverflow.com/questions/61021029/ |
Pytorch Dataloader shuffle with multiple dataset | I'm trying to make custom Dataloader with multiple datasets.
My question is that if I use (shuffle = True) in the Dataloader option, is it possible to shuffle the same order in multiple Dataloader?
For example:
dataloader1: label = [5 , 4, 15, 16]
dataloader2: label = [5 , 4, 15, 16]
| Edit: Pytorch's dataloaders have an implemented solution for that already.
See here: https://pytorch.org/docs/stable/data.html#torch.utils.data.Sampler you can specify the sampler yourself. So you can create a generator and give it to all dataloaders.
Old (and a bit more hacky) answer:
If keeping the order is really important, instead of making a custom dataloader, it may be better to make a custom dataset.
Note that is only possible if all datasets have the same number of examples. Or not use part of the data of the larger datasets.
Something in those lines should work:
class ManyDatasetsInOne(Dataset):
def __init__(self, **parameters):
self.dataset1 = dataset1(**parameters_1)
self.dataset2 = dataset2(**parameters_2)
def __len__(self):
return len(self.dataset1)
def __getitem__(self, index):
data1 = load_item(idx, self.dataset1)
data2 = load_item(idx, self.dataset1)
return data1, data2
| https://stackoverflow.com/questions/61025759/ |
Pytorch Concatenate rows in alternate order | I am trying to code up the positional encoding in the transformers paper. In order to do so I need to do an operation similar to the following:
a = torch.arange(20).reshape(4,5)
b = a * 2
c = torch.cat([torch.stack([a_row,b_row]) for a_row, b_row in zip(a,b)])
I feel like there might be a faster way to do the above? perhaps by adding a dimension on to a and b?
| So turns out simple concatenation and reshaping does the trick:
c = torch.cat([a, b], dim=-1).view(-1, a.shape[-1])
When I timed it with the following it was about 2.3x faster than @dennlinger's answer:
improved2 = timeit.timeit("c = torch.cat([a, b], dim=-1).view(-1, a.shape[-1])",
setup="import torch; from __main__ import a, b",
number=10000)
print(improved2/10000)
# 7.253780400003507e-06
print(improved / improved2)
# 2.3988091506044955
| https://stackoverflow.com/questions/61026393/ |
Libtorch operator/syntax errors in Visual Studio | Hi recently I’ve installed Libtorch and I was able to use it in my new Visual Studio project without a problem. Currently I am trying to use Libtorch in an existing CUDA project. But I am having these strange errors when I include torch header and I couldn’t find any solution in the internet regarding to my problem. Does anyone have any idea what might be the cause of these errors?
Severity Code Description Project File Line Suppression State
Error C2833 'operator {' is not a recognized operator or type DepthSensing e:\research\libtorch\include\c10\util\flat_hash_map.h 1433
Error C2059 syntax error: 'newline' DepthSensing e:\research\libtorch\include\c10\util\flat_hash_map.h 1433
Error C2238 unexpected token(s) preceding ';' DepthSensing e:\research\libtorch\include\c10\util\flat_hash_map.h 1433
Error C2143 syntax error: missing ';' before 'const' DepthSensing e:\research\libtorch\include\c10\util\flat_hash_map.h 1433
Error C2833 'operator {' is not a recognized operator or type DepthSensing e:\research\libtorch\include\c10\util\order_preserving_flat_hash_map.h 1552
Error C2059 syntax error: 'newline' DepthSensing e:\research\libtorch\include\c10\util\order_preserving_flat_hash_map.h 1552
Error C2238 unexpected token(s) preceding ';' DepthSensing e:\research\libtorch\include\c10\util\order_preserving_flat_hash_map.h 1552
Error C2143 syntax error: missing ';' before 'const' DepthSensing e:\research\libtorch\include\c10\util\order_preserving_flat_hash_map.h 1552
Environment
Windows 10
CUDA 10.1
Visual Studio 2017
C++14
| Thanks to @john I have realized that there was a macro in another library which has the same name as a typename in Libtorch library(which was a macro called V in my case), that’s why it was confused in compilation. I am sticking to this solution for now.
warning C4003: not enough actual parameters for macro 'max' - Visual Studio 2010 C++
| https://stackoverflow.com/questions/61029916/ |
PyTorch transferring index to 1-0 | How to quickly set the elements in the given index list to 1 and others to 0?
For example,I have an ID pool like:
torch.arange(10),
for a given input index tensor([1,5,7,9,2]) wanna return tensor([0,1,1,0,0,1,0,1,0,1])
| Easiest is to start with zeros and fill with ones using fancy indexing like this:
import torch
tensor = torch.zeros(10)
tensor[[1, 5, 7, 9, 2]] = 1
If your IDs are predefined (e.g. torch.arange(10)) and you want to get only those elements which are not zero you can do this:
import torch
ids = torch.arange(10)
mask = torch.zeros_like(ids).bool() # it has to be bool
mask[[1, 5, 7, 9, 2]] = True
torch.masked_select(ids, mask)
Which would give you:
tensor([1, 2, 5, 7, 9])
| https://stackoverflow.com/questions/61032062/ |
Should I set model.eval for getting the current training loss in Pytorch? | We set model.train() during training, but during my training iterations, I also want to do a forward pass of the training dataset to see what my new loss is. When doing this, should I temporarily set model.eval()?
| If your network has layers which act different during inference (torch.nn.BatchNormNd and torch.nn.DropoutNd could be an example, for the second case all neurons will be used but scaled by inverted probability of keeping neurons, see here or here for example) and you want to test how your network performs currently (which is usually called a validation step) then it is mandatory to use module.eval().
It is a common (and very good!) practice to always switch to eval mode when doing inference-like things no matter if this changes your actual model.
EDIT:
You should also use with torch.no_grad(): block during inference, see official tutorial code as gradients are not needed during this phase and it's wasteful to compute them.
| https://stackoverflow.com/questions/61032272/ |
Applying a 1D Convolution on a Tensor in Pytorch | I have a Tensor that represents a set of 1D signals, that are concatenated along the column axis. So say I have 300 1D signals that are of size 64. So [64x300]
I want to apply a smooth convolution / moving average kernel on it [0.2 0.2 0.2 0.2 0.2] on the GPU, but I am not sure exactly what is the API to do it. Can I be provided an example?
| You can use regular torch.nn.Conv1d to do this.
Inputs
In your case you have 1 channel (1D) with 300 timesteps (please refer to documentation those values will be appropriately C_in and L_in).
So, for your input it would be (you need 1 there, it cannot be squeezed!):
import torch
inputs = torch.randn(64, 1, 300)
Convolution
You need torch.nn.Conv1d with kernel_size equal to 5 (as indicated by your elements: [0.2 0.2 0.2 0.2 0.2]) and no bias. I assume your output has to be of the same size (300) so 2 elements have to be padded at the beginning and end. All of this gives us this module:
module = torch.nn.Conv1d(
in_channels=1, out_channels=1, kernel_size=5, padding=2, bias=False
)
Weights of this module (0.2 values) can be specified like this:
module.weight.data = torch.full_like(module.weight.data, 0.2)
torch.full_like will work for kernel of any size in case you want other size than 5.
Finally run it to average steps and you're done:
out = module(inputs)
GPU
If you want to use GPU just cast your module and inputs like this:
inputs = inputs.cuda()
module = module.cuda()
See CUDA documentation for more information.
| https://stackoverflow.com/questions/61032581/ |
ValueError: sampler option is mutually exclusive with shuffle pytorch | i'm working on face recognition project using pytorch and mtcnn and after trained my training dataset , now i want to make prediction on test data set
this my trained code
optimizer = optim.Adam(resnet.parameters(), lr=0.001)
scheduler = MultiStepLR(optimizer, [5, 10])
trans = transforms.Compose([
np.float32,
transforms.ToTensor(),
fixed_image_standardization
])
dataset = datasets.ImageFolder(data_dir, transform=trans)
img_inds = np.arange(len(dataset))
np.random.shuffle(img_inds)
train_inds = img_inds[:int(0.8 * len(img_inds))]
val_inds = img_inds[int(0.8 * len(img_inds)):]
train_loader = DataLoader(
dataset,
num_workers=workers,
batch_size=batch_size,
sampler=SubsetRandomSampler(train_inds)
)
val_loader = DataLoader(
dataset,
shuffle=True,
num_workers=workers,
batch_size=batch_size,
sampler=SubsetRandomSampler(val_inds)
)
and if remove sampler=SubsetRandomSampler(val_inds) and put val_inds instead it will rise this error
val_inds
^
SyntaxError: positional argument follows keyword argument
i want to make prediction (select randomly from test data set) in pytorch?thats why i should use shuffle=True
i followed this repo facenet-pytorch
| TLDR; Remove shuffle=True in this case as SubsetRandomSampler shuffles data already.
What torch.utils.data.SubsetRandomSampler does (please consult documentation when in doubt) is it will take a list of indices and return their permutation.
In your case you have indices corresponding to training (those are indices of elements in training Dataset) and validation.
Let's assume those look like that:
train_indices = [0, 2, 3, 4, 5, 6, 9, 10, 12, 13, 15]
val_indices = [1, 7, 8, 11, 14]
During each pass SubsetRandomSampler will return one number from those lists at random and those will be randomized again after all of them were returned (__iter__ will be called again).
So SubsetRandomSampler might return something like this for val_indices (analogously for train_indices):
val_indices = [1, 8, 11, 7, 14] # Epoch 1
val_indices = [11, 7, 8, 14, 1] # Epoch 2
val_indices = [7, 1, 14, 8, 11] # Epoch 3
Now each of those numbers are an index to your original dataset. Please note validation is shuffled this way and so is train without using shuffle=True. Those indices do not overlap so data is splitted correctly.
Additional info
shuffle uses torch.utils.data.RandomSampler under the hood if shuffle=True is specified, see source code. This in turn is equivalent to using torch.utils.data.SubsetRandomSampler with all indices (np.arange(len(datatest))) specified.
you don't have to pre-shuffle np.random.shuffle(img_inds) as indices will be shuffled during each pass anyway
don't use numpy if torch provides the same functionality. There is torch.arange, mixing both libraries is almost never necessary.
Inference
Single image
Just pass it through your network an get output, e.g.:
module.eval()
with torch.no_grad():
output = module(dataset[5380])
First line puts model in evaluation mode (changes behaviour of some layer), context manager turns off gradient (as it's not needed for predictions). Those are almost always used when "checking neural network output".
Checking validation dataset
Something along those lines, notice the same ideas applied as for single image:
module.eval()
total_batches = 0
batch_accuracy = 0
for images, labels in val_loader:
total_batches += 1
with torch.no_grad():
output = module(images)
# In case it outputs logits without activation
# If it outputs activation you may have to use argmax or > 0.5 for binary case
# Item gets float from torch.tensor
batch_accuracy += torch.mean(labels == (output > 0.0)).item()
print("Overall accuracy: {}".format(batch_accuracy / total_batches))
Other cases
Please see some beginners guides or tutorials and understand those concepts as StackOverflow is not a place to re-do this work (rather concrete and small questions), thanks.
| https://stackoverflow.com/questions/61033726/ |
Either too little or too many arguments for a nn.Sequential | I am new to PyTorch, so please excuse my silly question.
I define a nn.Sequential in init of my Encoder object like this:
self.list_of_blocks = [EncoderBlock(n_features, n_heads, n_hidden, dropout) for _ in range(n_blocks)]
self.blocks = nn.Sequential(*self.list_of_blocks)
The forward of EncoderBlock looks like this
def forward(self, x, mask):
In the forward() of my Encoder, I try to do:
z0 = self.blocks(z0, mask)
I expect the nn.Sequential to pass these two arguments to individual blocks.
However, I get
TypeError: forward() takes 2 positional arguments but 3 were given
When I try:
z0 = self.blocks(z0)
I get (understandably):
TypeError: forward() takes 2 positional arguments but only 1 was given
When I do not use nn.Sequential and just execute one EncoderBlock after another, it works:
for i in range(self.n_blocks):
z0 = self.list_of_blocks[i](z0, mask)
Question: What am I doing wrong and how do I use nn.Sequential correctly in this case?
| Sequential in general does not work with multiple inputs and outputs.
It is an often discussed topic, see PyTorch forum and GitHub issues #1908 or #9979.
You can define your own version of sequential. Assuming the mask is the same for all your encoder block (e.g., like in the Transformer networks), you can do:
class MaskedSequential(nn.Sequential):
def forward(self, x, mask):
for module in self._modules.values():
x = module(x, mask)
return inputs
Or if your EncoderBlocks return tuples, you can use a more general solution suggested in one of the GitHub issues:
class MySequential(nn.Sequential):
def forward(self, *inputs):
for module in self._modules.values():
if type(inputs) == tuple:
inputs = module(*inputs)
else:
inputs = module(inputs)
return inputs
| https://stackoverflow.com/questions/61036671/ |
pytorch - How to Save and load model from DistributedDataParallel learning | I'm new to the Pytorch DstributedDataParallel(), but I found that most of the tutorials save the local rank 0 model during training. Which means if I get 3 machine with 4 GPU on each of them, at the final I'll get 3 model that save from each machine.
For example in pytorch ImageNet tutorial on line 252:
if not args.multiprocessing_distributed or (args.multiprocessing_distributed
and args.rank % ngpus_per_node == 0):
save_checkpoint({...})
They save the model if rank % ngpus_per_node == 0.
To the best of my knowledge, DistributedDataParallel() will automatic do all reduce to the loss on the backend, without doing any further job, every process can sync the loss automatically base on that.
All the model on each process will only have slightly different at the end of the process. That mean we only need to save one model is enough.
So why don't we just save model on rank == 0, but rank % ngpus_per_node == 0 ?
And which model should I used for if I get multiple model?
If this is the right way for saving model in distribute learning, should I merge them, used one of them, or inference the result base on all three models?
Please let me know if I'm wrong.
| What is going on
Please correct me if I'm wrong in any place
The changes you are referring to were introduced in 2018 via this commit and described as:
in multiprocessing mode, only one process will write the checkpoint
Previously, those were saved without any if block so each node on each GPU would save a model which is indeed wasteful and would most probably overwrite saved model multiple times on each node.
Now, we are talking about multiprocessing distributed (possibly many workers each with possibly multiple GPUs).
args.rank for each process is thus modified inside the script by this line:
args.rank = args.rank * ngpus_per_node + gpu
which has the following comment:
For multiprocessing distributed training, rank needs to be the
global rank among all the processes
Hence args.rank is unique ID amongst all GPUs amongst all nodes (or so it seems).
If so, and each node has ngpus_per_node (in this training code it is assumed each has the same amount of GPUs from what I've gathered), then the model is saved only for one (last) GPU on each node. In your example with 3 machines and 4 GPUs you would get 3 saved models (hopefully I understand this code correctly as it's pretty convoluted tbh).
If you used rank==0 only one model per world (where world would be defined as n_gpus * n_nodes) would be saved.
Questions
First question
So why don't we just save model on rank == 0, but rank %
ngpus_per_node == 0 ?
I will start with your assumption, namely:
To the best of my knowledge, DistributedDataParallel() will automatic
do all reduce to the loss on the backend, without doing any further
job, every process can sync the loss automatically base on that.
Precisely, it has nothing to do with loss but rather gradient accumulation and applied corrections to weights, as per documentation (emphasis mine):
This container parallelizes the application of the given module by
splitting the input across the specified devices by chunking in the batch dimension. The module is replicated on each machine and
each device, and each such replica handles a portion of the input.
During the backwards pass, gradients from each node are averaged.
So, when the model is created with some weights it is replicated on all devices (each GPU for each node). Now each GPU gets a part of input (say, for total batch size equal to 1024, 4 nodes each with 4 GPUs, each GPU would get 64 elements), calculates forward pass, loss, performs backprop via .backward() tensor method. Now all gradients are averaged by all-gather, parameters are optimized on root machine and parameters are distributed to all nodes so module's state is always the same across all machines.
Note: I'm not sure how this averaging exactly takes place (and I don't see it explicitly said in docs), though I assume those are first averaged across GPUs and later across all nodes as it would be the most efficient I think.
Now, why would you save model for each node in such case? In principle you could only save one (as all modules will be exactly the same), but it has some downsides:
Say your node where your model was saved crashes and the file is lost. You have to redo all the stuff. Saving each model is not too costly operation (done once per epoch or less) so it can be easily done for each node/worker
You have to restart training. This means model would have to be copied to each worker (and some necessary metadata, though I don't think it's the case here)
Nodes will have to wait for every forward pass to finish anyway (so the gradients can be averaged), if the model saving takes a lot of time it would waste GPU/CPU being idle (or some other synchronization scheme would have to be applied, I don't think there is one in PyTorch). This makes it somewhat "no-cost" if you look at the overall picture.
Question 2 (and 3)
And which model should I used for if I get multiple model?
It doesn't matter as all of them will be exactly the same as the same corrections via optimizer are applied to the model with the same initial weights.
You could use something along those lines to load your saved .pth model:
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
parallel_model = torch.nn.DataParallel(MyModelGoesHere())
parallel_model.load_state_dict(
torch.load("my_saved_model_state_dict.pth", map_location=str(device))
)
# DataParallel has model as an attribute
usable_model = parallel_model.model
| https://stackoverflow.com/questions/61037819/ |
Using flatten in pytorch v1.0 Sequential module | Due to my CUDA version being 8, I am using torch 1.0.0
I need to use the Flatten layer for Sequential model. Here's my code :
import torch
import torch.nn as nn
import torch.nn.functional as F
print(torch.__version__)
# 1.0.0
from collections import OrderedDict
layers = OrderedDict()
layers['conv1'] = nn.Conv2d(1, 5, 3)
layers['relu1'] = nn.ReLU()
layers['conv2'] = nn.Conv2d(5, 1, 3)
layers['relu2'] = nn.ReLU()
layers['flatten'] = nn.Flatten()
layers['linear1'] = nn.Linear(3600, 1)
model = nn.Sequential(
layers
).cuda()
It gives me the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-38-080f7c5f5037> in <module>
6 layers['conv2'] = nn.Conv2d(5, 1, 3)
7 layers['relu2'] = nn.ReLU()
----> 8 layers['flatten'] = nn.Flatten()
9 layers['linear1'] = nn.Linear(3600, 1)
10 model = nn.Sequential(
AttributeError: module 'torch.nn' has no attribute 'Flatten'
How can I flatten my conv layer output in pytorch 1.0.0?
| Just make a new Flatten layer.
from collections import OrderedDict
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
layers = OrderedDict()
layers['conv1'] = nn.Conv2d(1, 5, 3)
layers['relu1'] = nn.ReLU()
layers['conv2'] = nn.Conv2d(5, 1, 3)
layers['relu2'] = nn.ReLU()
layers['flatten'] = Flatten()
layers['linear1'] = nn.Linear(3600, 1)
model = nn.Sequential(
layers
).cuda()
| https://stackoverflow.com/questions/61039700/ |
RuntimeError: _th_normal not supported on CPUType for Long | I am trying to generate a number from the normal distribution using:
from torch.distributions import Normal
noise = Normal(th.tensor([0]), th.tensor(3.20))
noise = noise.sample()
But I am getting this error: RuntimeError: _th_normal not supported on CPUType for Long
| Your first tensor th.tensor([0]) is of torch.Long type due to automatic type inference from passed value while float or FloatTensor is required by function.
You can solve it by passing 0.0 explicitly like this:
import torch
noise = torch.distributions.Normal(torch.tensor([0.0]), torch.tensor(3.20))
noise = noise.sample()
Better yet, drop torch.tensor altogether, in this case Python types will be automatically casted to float if possible, so this is valid as well:
import torch
noise = torch.distributions.Normal(0, 3.20)
noise = noise.sample()
And please, do not alias torch as th, it is not official, use fully qualified name as this only confuses everyone.
| https://stackoverflow.com/questions/61041458/ |
Obtaining the shape (4, 1, 84, 84) with pytorch | Suppose I have four pytorch tensors (tensor1, tensor2, tensor3, tensor4). Each tensor is of shape (1, 1, 84, 84). The first dimension is the number of tensors, the second dimension is the number of colors (e.g. grayscale in our example) and the last two dimensions represent the height and the width of the image.
I want to stack them so that I get the shape (4, 1, 84, 84).
I tried torch.stack((tensor1, tensor2, tensor3, tensor4), dim=0), but I got a shape (4, 1, 1, 84, 84).
How can I stack those tensors so that the shape will be (4, 1, 84, 84)
| You can use the concatenate function:
a = torch.ones(1,1,84,84)
b = torch.ones(1,1,84,84)
c = torch.cat((a,b), 0) # size[2,1,84,84]
| https://stackoverflow.com/questions/61044652/ |
Pytorch 'Tensor' object is not callable | I am trying to apply sobel filter to my network. I am getting this error : "'Tensor' object is not callable"
Here is my code:
class SobelFilter(nn.Module):
def __init__(self):
super(SobelFilter, self).__init__()
kernel1=torch.Tensor([[1, 0, -1],[2,0,-2],[1,0,-1]])
kernela=kernel1.expand((1,1,3,3))
kernel2=torch.Tensor([[1, 2, 1],[0,0,0],[-1,-2,-1]])
kernelb=kernel2.expand((1,1,3,3))
inputs = torch.randn(1,1,64,128)
self.conv1 = F.conv2d(inputs,kernela,stride=1,padding=1)
self.conv2 = F.conv2d(inputs,kernelb,stride=1,padding=1)
def forward(self, x ):
print(x.shape)
G_x = self.conv1(x) %GIVES ERROR AT THIS LINE
G_y = self.conv2(x)
out = torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2))
return out
class EXP(nn.Module):
def __init__(self, maxdisp):
super(EXP, self).__init__()
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.SobelFilter = SobelFilter()
def forward(self, im):
% just think "im" to be [1,32,64,128]
for i in range(im.shape[1]):
out1= im[:,i,:,:].unsqueeze(1)
im[:,i,:,:] = self.SobelFilter(out1)
what can cause the problem?
Thank you!
| I think your issue is that you are using torch.nn.functional instead of just torch.
The purpose of the functional API is to perform the operations (in this case the conv2d) directly, without creating a class instance and then calling its forward method.
Therefore, the statement self.conv1 = F.conv2d(inputs,kernela,stride=1,padding=1) is already doing the convolution between the input and kernela and what you have in self.conv1is the result of such convolution.
There are two approaches here to fix the problem. Use torch.Conv2d inside __init__, where inputs is the channel of the input and not a tensor with the same shape as your real input.
And the second approach is to stick with the functional API but move it to the forward() method. What you want to achieve can be done by changing the forward to:
def forward(self, x ):
print(x.shape)
G_x = F.conv2d(x,self.kernela,stride=1,padding=1)
G_y = F.conv2d(x,self.kernelb,stride=1,padding=1)
out = torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2))
return out
Note that I made kernela and kernelb class attributes. Thus you should also change the __init__() to
def __init__(self):
super(SobelFilter, self).__init__()
kernel1=torch.Tensor([[1, 0, -1],[2,0,-2],[1,0,-1]])
self.kernela=kernel1.expand((1,1,3,3))
kernel2=torch.Tensor([[1, 2, 1],[0,0,0],[-1,-2,-1]])
self.kernelb=kernel2.expand((1,1,3,3))
| https://stackoverflow.com/questions/61044667/ |
Error implementing torch.optim.lr_scheduler.LambdaLR in Pytorch | I'm working on an Image classifier and trying to implement Cyclical Learning Rates to have a better results. I'm using lr_scheduler.LambdaLR to adjust the learning rate during training, but I'm having an error that I'm not sure what is the cause of it.
this is my code:
lr_find_epochs = 2
start_lr = 1e-7
end_lr = 0.1
# Set up the model, optimizer and loss function for the experiment
optimizer = torch.optim.SGD(model.parameters(), start_lr)
criterion = nn.NLLLoss()
# LR function lambda
lr_lambda = lambda x: math.exp(x * math.log(end_lr / start_lr) / (lr_find_epochs * len( train_loader)))
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda)
and this is the error I'm having:
The error in lr_scheduler.py.
| The issue is caused by this line here
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lr_lambda)
As the error suggests you are trying to reference value before it has been assigned,i.e. the lambda function is called with itself as the argument which is currently not assigned to anything. As a result of this, an error is raised in lr_scheduler.py
Maybe you want to pass something else to the lambda function.
| https://stackoverflow.com/questions/61045293/ |
* (tuple of Tensors tensors, name dim, Tensor out) | Suppose I have the memory list list_of_tensors = [tensor1, tensor2, tensor3, tensor4]. Each element is a pytorch tensor of shape (1, 1, 84, 84).
I want to concatenate that list of tensors to get a tensor of shape (4, 1, 84, 84). torch.cat(TT, dim=0) might surely allow me to do that. TT must be a tuple of tensor, so torch.cat(*list_of_tensors, dim=0) or torch.cat((*list_of_tensors), dim=0) won't work.
How can I use list_of_tensors and torch.cat(???, dim=0) to create a new tensor of shape (4, 1, 84, 84)
| You can use stack, and remove surplus dimension with squeeze
c = (torch.stack(list_of_tensors,dim=1)).squeeze(0)
now c.shape is (4, 1, 84, 84)
You can find explanation here: https://discuss.pytorch.org/t/how-to-turn-a-list-of-tensor-to-tensor/8868/6
| https://stackoverflow.com/questions/61045362/ |
How can I element-wise 2 Tensors with different dimensions with Broadcasting? | I have a tensor called inputs with a size of torch.Size([20, 1, 161, 199]) and another mask with a size of torch.Size([20, 1, 199]). I want to multiply them together.
I tried:
masked_inputs = inputs * mask[..., None]
but get an error:
RuntimeError: The size of tensor a (161) must match the size of tensor b (199) at non-singleton dimension 2
I'm not quite sure what to do?
| This did it:
masked_inputs = inputs * mask.unsqueeze(2)
| https://stackoverflow.com/questions/61046262/ |
How do I do masking in PyTorch / Numpy with different dimensions? | I have a mask with a size of torch.Size([20, 1, 199]) and a tensor, reconstruct_output and inputs both with a size of torch.Size([20, 1, 161, 199]).
I want to set reconstruct_output to inputs where the mask is 0. I tried:
reconstruct_output[mask == 0] = inputs[mask == 0]
But I get an error:
IndexError: The shape of the mask [20, 1, 199] at index 2 does not match the shape of the indexed tensor [20, 1, 161, 199] at index 2
| We can use advanced indexing here. To obtain the indexing arrays which we want to use to index both reconstruct_output and inputs, we need the indices along its axes where m==0. For that we can use np.where, and use the resulting indices to update reconstruct_output as:
m = mask == 0
i, _, l = np.where(m)
reconstruct_output[i, ..., l] = inputs[i, ..., l]
Here's a small example which I've checked with:
mask = np.random.randint(0,3, (2, 1, 4))
reconstruct_output = np.random.randint(0,10, (2, 1, 3, 4))
inputs = np.random.randint(0,10, (2, 1, 3, 4))
Giving for instance:
print(reconstruct_output)
array([[[[8, 9, 7, 2],
[5, 4, 6, 1],
[1, 4, 0, 3]]],
[[[4, 3, 3, 4],
[0, 9, 9, 7],
[3, 4, 9, 3]]]])
print(inputs)
array([[[[7, 3, 9, 8],
[3, 1, 0, 8],
[0, 5, 4, 8]]],
[[[3, 7, 5, 8],
[2, 5, 3, 8],
[3, 6, 7, 5]]]])
And the mask:
print(mask)
array([[[0, 1, 2, 1]],
[[1, 0, 1, 0]]])
By using np.where to find the indices where there are zeroes in mask we get:
m = mask == 0
i, _, l = np.where(m)
i
# array([0, 1, 1])
l
# array([0, 1, 3])
Hence we'll be replacing the 0th column from the first 2D array and the 1st and 3rd from the second 2D array.
We can now use these arrays to replace along the corresponding axes indexing as:
reconstruct_output[i, ..., l] = inputs[i, ..., l]
Getting:
reconstruct_output
array([[[[7, 9, 7, 2],
[3, 4, 6, 1],
[0, 4, 0, 3]]],
[[[4, 7, 3, 8],
[0, 5, 9, 8],
[3, 6, 9, 5]]]])
| https://stackoverflow.com/questions/61046471/ |
How have the number of dimensions after LSTM been decided in Pointer Generator Model in PyTorch? | I don't understand why is the number of input and output dimensions 2 * config.hidden_dim while applying a fully connected layer in the encode class (mentioned in the last line)?
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.embedding = nn.Embedding(config.vocab_size, config.emb_dim)
init_wt_normal(self.embedding.weight)
self.lstm = nn.LSTM(
config.emb_dim, config.hidden_dim, num_layers=1,
batch_first=True, bidirectional=True)
init_lstm_wt(self.lstm)
self.W_h = nn.Linear(
config.hidden_dim * 2, config.hidden_dim * 2, bias=False)
The code has been taken from https://github.com/atulkum/pointer_summarizer/blob/master/training_ptr_gen/model.py
Please Explain
| The reason is that the LSTM layer bidirectional, i.e., there are in fact two LSTMs each of them processing the input from each direction. They both return vectors of dimension config.hidden_dim which get concatenated into vectors of 2 * config.hidden_dim.
| https://stackoverflow.com/questions/61047446/ |
size mismatch, m1: [288 x 9], m2: [2592 x 256] at /tmp/pip-req-build-4baxydiv/aten/src/TH/generic/THTensorMath.cpp:197 | Here is the error I got
*** RuntimeError: size mismatch, m1: [288 x 9], m2: [2592 x 256] at /tmp/pip-req-build-4baxydiv/aten/src/TH/generic/THTensorMath.cpp:197
Here my model :
class DQN(nn.Module):
def __init__(self, num_actions, lr):
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(
in_channels=4, out_channels=16, kernel_size=8, stride=4)
self.conv2 = nn.Conv2d(
in_channels=16, out_channels=32, kernel_size=4, stride=2)
# You have to respect the formula ((W-K+2P/S)+1)
self.fc = nn.Linear(in_features=32*9*9, out_features=256)
self.out = nn.Linear(in_features=256, out_features=num_actions)
def forward(self, state):
import ipdb; ipdb.set_trace()
# (1) Hidden Conv. Layer
self.layer1 = F.relu(self.conv1(state))
# (2) Hidden Conv. Layer
self.layer2 = F.relu(self.conv2(self.layer1))
# (3) Hidden Linear Layer
self.layer3 = self.fc(self.layer2)
# (4) Output
actions = self.out(self.layer3)
return actions
The error is triggered at line self.layer3 = self.fc(self.layer2). state is a pytorch tensor of shape (1, 4, 84, 84).
The full traceback is
Traceback (most recent call last):
File "/home/infinity/Projects/Exercice_Project/AI_Exercices/Atari_2600_Breakout.py", line 228, in <module>
action = agent.choose_action(state, policy_network)
File "/home/infinity/Projects/Exercice_Project/AI_Exercices/Atari_2600_Breakout.py", line 166, in choose_action
return policy_net(state).argmax(dim=1).to(self.device)
File "/home/infinity/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 541, in __call__
result = self.forward(*input, **kwargs)
File "/home/infinity/Projects/Exercice_Project/AI_Exercices/Atari_2600_Breakout.py", line 101, in forward
self.layer3 = self.fc(self.layer2)
File "/home/infinity/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 541, in __call__
result = self.forward(*input, **kwargs)
File "/home/infinity/anaconda3/lib/python3.7/site-packages/torch/nn/modules/linear.py", line 87, in forward
return F.linear(input, self.weight, self.bias)
File "/home/infinity/anaconda3/lib/python3.7/site-packages/torch/nn/functional.py", line 1372, in linear
output = input.matmul(weight.t())
RuntimeError: size mismatch, m1: [288 x 9], m2: [2592 x 256] at /tmp/pip-req-build-4baxydiv/aten/src/TH/generic/THTensorMath.cpp:197
| Just before self.layer3 = self.fc(self.layer2), I had to add the line input_layer3 = self.layer2.reshape(-1, 32*9*9).
| https://stackoverflow.com/questions/61049416/ |
How to generate accurate masks for an image from Mask R-CNN prediction in PyTorch? | I have trained a Mask RCNN network for instance segmentation of apples. I am able to load the weights and generate predictions for my test images. The masks being generated seem to be in the correct location, but the mask itself has no real form.. it just looks like a bunch of pixels
Training is done based on the dataset from this paper, and here is the github link to code being used to train and generate weights
code for prediction is as follows. (i have omitted the parts where i create path variables and assign the paths)
import os
import glob
import numpy as np
import pandas as pd
import cv2 as cv
import fileinput
import torch
import torch.utils.data
import torchvision
from data.apple_dataset import AppleDataset
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
import utility.utils as utils
import utility.transforms as T
from PIL import Image
from matplotlib import pyplot as plt
%matplotlib inline
def get_transform(train):
transforms = []
transforms.append(T.ToTensor())
if train:
transforms.append(T.RandomHorizontalFlip(0.5))
return T.Compose(transforms)
def get_maskrcnn_model_instance(num_classes):
# load an instance segmentation model pre-trained pre-trained on COCO
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=False)
# get number of input features for the classifier
in_features = model.roi_heads.box_predictor.cls_score.in_features
# replace the pre-trained head with a new one
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
# now get the number of input features for the mask classifier
in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
hidden_layer = 256
# and replace the mask predictor with a new one
model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes)
return model
num_classes = 2
device = torch.device('cpu')
model = get_maskrcnn_model_instance(num_classes)
checkpoint = torch.load('model_49.pth', map_location=device)
model.load_state_dict(checkpoint['model'], strict=False)
dataset_test = AppleDataset(test_image_files_path, get_transform(train=False))
img, _ = dataset_test[1]
model.eval()
with torch.no_grad():
prediction = model([img.to(device)])
prediction
Image.fromarray(img.mul(255).permute(1, 2, 0).byte().numpy())
(unable to load image here since its over 2MB.
Image.fromarray(prediction[0]['masks'][0, 0].mul(255).byte().cpu().numpy())
Here is an Imgur link to the original image.. below is the predicted mask for one of the instances
Also, could you please help me understand the data structure of the generated prediction matrix shown below.. How do i access the masks so as to generate a single image with all masks displayed???
[{'boxes': tensor([[ 966.8143, 1633.7491, 1106.7389, 1787.6367],
[1418.7872, 1467.0619, 1732.0828, 1796.1527],
[1608.0396, 2064.6482, 1710.7534, 2206.5535],
[2326.3750, 1690.3418, 2542.2112, 1883.2626],
[2213.2024, 1864.3657, 2299.8933, 1963.0178],
[1112.9083, 1732.5953, 1236.7600, 1823.0170],
[1150.8256, 614.0334, 1218.8584, 711.4094],
[ 942.7086, 794.6043, 1138.2318, 1008.0430],
[1065.4371, 723.0493, 1192.7570, 870.3763],
[1002.3103, 883.4616, 1146.9994, 1006.6841],
[1315.2816, 1680.8625, 1531.3210, 1989.3317],
[1244.5769, 1925.0903, 1459.5417, 2175.3252],
[1725.2191, 2082.6187, 1934.0227, 2274.2952],
[ 936.3065, 1554.3765, 1014.2722, 1659.4229],
[ 934.8851, 1541.3331, 1090.4736, 1657.3751],
[2486.0120, 776.4577, 2547.2329, 847.9725],
[2336.1675, 698.6327, 2508.6492, 921.4550],
[2368.4077, 1954.1102, 2448.4004, 2049.5796],
[1899.1403, 1775.2371, 2035.7561, 1962.6923],
[2176.0664, 1075.1553, 2398.6084, 1267.2555],
[2274.8899, 641.6769, 2395.9634, 791.3353],
[2535.1580, 874.4780, 2642.8213, 966.4614],
[2183.4236, 619.9688, 2288.5676, 758.6825],
[2183.9832, 1122.9382, 2334.9583, 1263.3226],
[1135.7822, 779.0529, 1225.9871, 890.0135],
[ 317.3954, 1328.6995, 397.3900, 1467.7740],
[ 945.4811, 1833.3708, 997.2318, 1878.8607],
[1992.4447, 679.4969, 2134.6667, 835.8701],
[1098.5416, 1452.7799, 1429.1808, 1771.4460],
[1657.3193, 1405.5405, 1781.6273, 1574.6780],
[1443.8911, 1747.1544, 1739.0361, 2076.9724],
[1092.6003, 1165.3340, 1206.0881, 1383.8314],
[2466.4170, 1945.5931, 2555.1931, 2039.8368],
[2561.8508, 1616.2659, 2672.1033, 1742.2332],
[1894.4806, 907.9214, 2097.1875, 1182.6473],
[2321.5005, 1701.3344, 2368.3699, 1865.3914],
[2180.0781, 567.5969, 2344.6357, 763.4360],
[1845.7612, 668.6808, 2045.2688, 899.8501],
[1858.9216, 2145.7097, 1961.8870, 2273.5088],
[ 261.4607, 1314.0154, 396.9288, 1486.9498],
[2488.1682, 1585.2357, 2669.0178, 1794.9926],
[2696.9548, 936.0087, 2802.7961, 1025.2294],
[1593.6837, 1489.8641, 1720.3124, 1627.8135],
[2517.9468, 857.1713, 2567.1125, 929.4335],
[1943.2167, 636.3422, 2151.4419, 853.8924],
[2143.5664, 1100.0521, 2308.1570, 1290.7125],
[2140.9231, 1947.9692, 2238.6956, 2000.6249],
[1461.6316, 2105.2593, 1559.7675, 2189.0264],
[2114.0781, 374.8153, 2222.8838, 559.9851],
[2350.5320, 726.5779, 2466.8140, 878.2617]]),
'labels': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1]),
'scores': tensor([0.9916, 0.9841, 0.9669, 0.9337, 0.9118, 0.7729, 0.7202, 0.7193, 0.6928,
0.6872, 0.6690, 0.5913, 0.4877, 0.4683, 0.3781, 0.3327, 0.3164, 0.2364,
0.1696, 0.1692, 0.1502, 0.1365, 0.1316, 0.1171, 0.1119, 0.1094, 0.1041,
0.0865, 0.0853, 0.0835, 0.0822, 0.0816, 0.0797, 0.0796, 0.0788, 0.0780,
0.0757, 0.0736, 0.0736, 0.0689, 0.0681, 0.0644, 0.0642, 0.0630, 0.0612,
0.0598, 0.0563, 0.0531, 0.0525, 0.0522]),
'masks': tensor([[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]],
[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]],
[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]],
...,
[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]],
[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]],
[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]]])}]
| The prediction from the Mask R-CNN has the following structure:
During inference, the model requires only the input tensors, and returns the post-processed predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as follows:
boxes (FloatTensor[N, 4]): the predicted boxes in [x1, y1, x2, y2] format, with values between 0 and H and 0 and W
labels (Int64Tensor[N]): the predicted labels for each image
scores (Tensor[N]): the scores or each prediction
masks (UInt8Tensor[N, 1, H, W]): the predicted masks for each instance, in 0-1 range.
You can use OpenCV's findContours and drawContours functions to draw masks as follows:
img_cv = cv2.imread('input.jpg', cv2.COLOR_BGR2RGB)
for i in range(len(prediction[0]['masks'])):
# iterate over masks
mask = prediction[0]['masks'][i, 0]
mask = mask.mul(255).byte().cpu().numpy()
contours, _ = cv2.findContours(
mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img_cv, contours, -1, (255, 0, 0), 2, cv2.LINE_AA)
cv2.imshow('img output', img_cv)
Sample output:
| https://stackoverflow.com/questions/61051335/ |
Torch sum each row excluding an index | Given a Tensor A of shape (N,C) and an indices Tensor Idx of shape (N,), i'd like to sum all the elements of each row in A excluding the corresponding column index in I. For example:
A = torch.tensor([[1,2,3],
[4,5,6]])
Idx = torch.tensor([0,2])
#result:
torch.tensor([[5],
[9]])
A solution using loops is known.
| You can set excluded elements to zero:
A[range(A.shape[0]),Idx] = 0
and sum tensor along rows:
b = A.sum(dim = 1,keepdim = True ) # b = torch.tensor([[5], [9]])
| https://stackoverflow.com/questions/61067750/ |
"No such file" when loading csv data stored in G drive to torchtext format using torchtext.data.TabularDataset, | I have stored a csv file in G drive and try to load it to torchtext data.TabularDataset. The error message is "FileNotFoundError: [Errno 2] No such file or directory: 'https://.....'"
Is it impossible to load csv file from g drive directly to torchtext TabularDataset?
Here is the code. I have also made a public colab notebook with data publicly available.
import torch
from torchtext import data, datasets
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
TEXT = data.Field(tokenize = 'spacy', batch_first = True, lower=False)
LABEL = data.LabelField(sequential=False, dtype = torch.float)
train = data.TabularDataset(path = 'https://drive.google.com/open?id=1eWMjusU3H34m0uml5SdJvYX6gQuB8zta',
format = 'csv',
fields = [('Insult', LABEL), (None, None), ('Comment', TEXT)],
skip_header=False)
| Let's assume you can afford to download this CSV file. I would suggest you to use a functionally built-in on torchtext: download_from_url.
import os
import torch
from torchtext import data, datasets
from torchtext.utils import download_from_url
# download the file
CSV_FILENAME = 'data.csv'
CSV_GDRIVE_URL = 'https://drive.google.com/uc?export=download&id=1eWMjusU3H34m0uml5SdJvYX6gQuB8zta'
download_from_url(CSV_GDRIVE_URL, CSV_FILENAME)
TEXT = data.Field(tokenize = 'spacy', batch_first = True, lower=False) #from torchtext import data
LABEL = data.LabelField(sequential=False, dtype = torch.float)
# if you're on Colab, you'll need this /content
train = data.TabularDataset(path=os.path.join('/content', CSV_FILENAME),
format='csv',
fields = [('Insult', LABEL), (None, None), ('Comment', TEXT)],
skip_header=False )
Notice that the Google Drive link should not be the one with open?id, but change it to uc?export=download&id.
| https://stackoverflow.com/questions/61068047/ |
Anaconda, update Pytorch to the latest version 1.5 | How could I update PyTorch from 1.4 -> 1.5 using Anaconda either through terminal or navigator?
Updating Anaconda with conda update --all updated some of the packages, not all, PyTorch included.
Initially, I installed PyTorch by running conda install -c pytorch pytorch
From PyTorch Github page there's the command
conda install -c pytorch magma-cuda90 # or [magma-cuda92 | magma-cuda100 | magma-cuda101 ] depending on your cuda version
but I wonder if there's going to be any kind of conflict between the already installed version and this one.
Thanks
| PyTorch latest stable release (as of April 06, 2020) is still 1.4, as you can see here.
Therefore, if you want to install the nightly build (which is on track to the 1.5) using conda, you can follow the official instructions:
Cuda 10.1:
conda install pytorch torchvision cudatoolkit=10.1 -c pytorch-nightly -c defaults -c conda-forge
Cuda 9.2:
conda install pytorch torchvision cudatoolkit=9.2 -c pytorch-nightly -c defaults -c conda-forge -c numba/label/dev
or the CPU-only version:
conda install pytorch torchvision cpuonly -c pytorch-nightly -c defaults -c conda-forge
Or, you can just wait 1.5 to be an stable release (currently, we are in the release candidate 2) and update the pytorch package as you'd have done otherwise.
Be aware that:
PyTorch 1.4 is the last release that supports Python 2
So, if you're moving to PyTorch 1.5, say goodbye to Python 2 (Yay!!).
| https://stackoverflow.com/questions/61068181/ |
Reduce the number of hidden units in hugging face transformers (BERT) | I have been given a large csv each line of which is a set of BERT tokens made with hugging face BertTokenizer (https://huggingface.co/transformers/main_classes/tokenizer.html).
1 line of this file looks as follows:
101, 108, 31278, 90939, 70325, 196, 199, 71436, 10107, 29190, 10107, 106, 16680, 68314, 10153, 17015, 15934, 10104, 108, 10233, 12396, 14945, 10107, 10858, 11405, 13600, 13597, 169, 57343, 64482, 119, 119, 119, 100, 11741, 16381, 10109, 68830, 10110, 20886, 108, 10233, 11127, 21768, 100, 14120, 131, 120, 120, 188, 119, 11170, 120, 12132, 10884, 10157, 11490, 12022, 10113, 10731, 10729, 11565, 14120, 131, 120, 120, 188, 119, 11170, 120, 162, 11211, 11703, 12022, 11211, 10240, 44466, 100886, 102
and there are 9 million lines like this
Now, I am trying to get embeddings from these tokens like this:
def embedding:
tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', do_lower_case=False)
model = BertModel.from_pretrained('bert-base-multilingual-cased')
input_ids = torch.tensor([101, 108, 31278, 90939, 70325, 196, 199, 71436, 10107, 29190, 10107, 106, 16680, 68314, 10153, 17015, 15934, 10104, 108, 10233, 12396, 14945, 10107, 10858, 11405, 13600, 13597, 169, 57343, 64482, 119, 119, 119, 100, 11741, 16381, 10109, 68830, 10110, 20886, 108, 10233, 11127, 21768, 100, 14120, 131, 120, 120, 188, 119, 11170, 120, 12132, 10884, 10157, 11490, 12022, 10113, 10731, 10729, 11565, 14120, 131, 120, 120, 188, 119, 11170, 120, 162, 11211, 11703, 12022, 11211, 10240, 44466, 100886, 102]).unsqueeze(0) # Batch size 1
outputs = model(input_ids)
last_hidden_states = outputs[0][0][0] # The last hidden-state is the first element of the output tuple
Output of this is embedding correspending to the line. The size is 768*1 tensor. Semantically, everything is ok. But, when I do this for the full file the output is 768 * 9,0000,000 torch tensors. So I get a memory error even with large machine with a 768 GB of RAM.
Here is how I call this function:
tokens['embeddings'] = tokens['text_tokens'].apply(lambda x: embedding(x))
tokens is the pandas data frame with 9 million lines each of which contains BERT tokens.
Is it possible to reduce the default size of the hidden units, which is 768 here: https://huggingface.co/transformers/main_classes/model.html
Thank you for your help.
| Changing the dimensionality would mean changing all the model parameters, i.e., retraining the model. This could be achievable by knowledge distillation, but it will be probably still quite computationally demanding.
You can also use some dimensionality reduction techniques on the BERT outputs, like PCA (available e.g., in scikit-learn). In that case, I would suggest taking several thousand BERT vectors, fit the PCA and then apply the PCA on all the remaining vectors.
| https://stackoverflow.com/questions/61072673/ |
Understanding when to call zero_grad() in pytorch, when training with multiple losses | I am going through an open-source implementation of a domain-adversarial model (GAN-like). The implementation uses pytorch and I am not sure they use zero_grad() correctly. They call zero_grad() for the encoder optimizer (aka the generator) before updating the discriminator loss. However zero_grad() is hardly documented, and I couldn't find information about it.
Here is a psuedo code comparing a standard GAN training (option 1), with their implementation (option 2). I think the second option is wrong, because it may accumulate the D_loss gradients with the E_opt. Can someone tell if these two pieces of code are equivalent?
Option 1 (a standard GAN implementation):
X, y = get_D_batch()
D_opt.zero_grad()
pred = model(X)
D_loss = loss(pred, y)
D_opt.step()
X, y = get_E_batch()
E_opt.zero_grad()
pred = model(X)
E_loss = loss(pred, y)
E_opt.step()
Option 2 (calling zero_grad() for both optimizers at the beginning):
E_opt.zero_grad()
D_opt.zero_grad()
X, y = get_D_batch()
pred = model(X)
D_loss = loss(pred, y)
D_opt.step()
X, y = get_E_batch()
pred = model(X)
E_loss = loss(pred, y)
E_opt.step()
| It depends on params argument of torch.optim.Optimizer subclasses (e.g. torch.optim.SGD) and exact structure of the model.
Assuming E_opt and D_opt have different set of parameters (model.encoder and model.decoder do not share weights), something like this:
E_opt = torch.optim.Adam(model.encoder.parameters())
D_opt = torch.optim.Adam(model.decoder.parameters())
both options MIGHT indeed be equivalent (see commentary for your source code, additionally I have added backward() which is really important here and also changed model to discriminator and generator appropriately as I assume that's the case):
# Starting with zero gradient
E_opt.zero_grad()
D_opt.zero_grad()
# See comment below for possible cases
X, y = get_D_batch()
pred = discriminator(x)
D_loss = loss(pred, y)
# This will accumulate gradients in discriminator only
# OR in discriminator and generator, depends on other parts of code
# See below for commentary
D_loss.backward()
# Correct weights of discriminator
D_opt.step()
# This only relies on random noise input so discriminator
# Is not part of this equation
X, y = get_E_batch()
pred = generator(x)
E_loss = loss(pred, y)
E_loss.backward()
# So only parameters of generator are updated always
E_opt.step()
Now it's all about get_D_Batch feeding data to discriminator.
Case 1 - real samples
This is not a problem as it does not involve generator, you pass real samples and only discriminator takes part in this operation.
Case 2 - generated samples
Naive case
Here indeed gradient accumulation may occur. It would occur if get_D_batch would simply call X = generator(noise) and passed this data to discriminator.
In such case both discriminator and generator have their gradients accumulated during backward() as both are used.
Correct case
We should take generator out of the equation. Taken from PyTorch DCGan example there is a little line like this:
# Generate fake image batch with G
fake = generator(noise)
label.fill_(fake_label)
# DETACH HERE
output = discriminator(fake.detach()).view(-1)
What detach does is it "stops" the gradient by detaching it from the computational graph. So gradients will not be backpropagated along this variable. This effectively does not impact gradients of generator so it has no more gradients so no accumulation happens.
Another way (IMO better) would be to use with.torch.no_grad(): block like this:
# Generate fake image batch with G
with torch.no_grad():
fake = generator(noise)
label.fill_(fake_label)
# NO DETACH NEEDED
output = discriminator(fake).view(-1)
This way generator operations will not build part of the graph so we get better performance (it would in the first case but would be detached afterwards).
Finally
Yeah, all in all first option is better for standard GANs as one doesn't have to think about such stuff (people implementing it should, but readers should not). Though there are also other approaches like single optimizer for both generator and discriminator (one cannot zero_grad() only for subset of parameters (e.g. encoder) in this case), weight sharing and others which further clutter the picture.
with torch.no_grad() should alleviate the problem in all/most cases as far as I can tell and imagine ATM.
| https://stackoverflow.com/questions/61078289/ |
AttributeError: 'Example' object has no attribute 'Insult' when build vocab using build_vocab() from torchtext | I tried to build vocabulary using .build_vocab() from torchtext in colab. It returns the error message: AttributeError: 'Example' object has no attribute 'Insult'
My question is similar to @szymix12 s question. His answer is to make sure the order of the fields passed is the same as the csv headers. I confirm that the order I assign is correct. The csv data got two columns:"Insult" (LABEL) and "Comment"(TEXT). "Insult" is a binary label indicator (0 or 1).
The code is as below, I have also made a colab notebook. Feel free to run.
import os
import torch
from torchtext import data, datasets
from torchtext.utils import download_from_url
CSV_FILENAME = 'data.csv'
CSV_GDRIVE_URL = 'https://drive.google.com/open?id=1ctPKO-_sJbmc8RodpBZ5-3EyYBWlUy5Pbtjio5pyq00'
download_from_url(CSV_GDRIVE_URL, CSV_FILENAME)
TEXT = data.Field(tokenize = 'spacy', batch_first = True, lower=True) #from torchtext import data
LABEL = data.LabelField(sequential=False, dtype = torch.float)
train = data.TabularDataset(path=os.path.join('/content', CSV_FILENAME),
format='csv',
fields = [('Insult', LABEL), ('Comment', TEXT)],
skip_header=True)
print(vars(train[0]),vars(train[1]),vars(train[2]))
TEXT.build_vocab(train)
| You don't need to manually download&upload the file as suggested by @knoop. As I provided in my previous answer to your question, you should not use the link with open. You should change to uc?export=download instead. In this way, the correct CSV_GDRIVE_URL should be:
CSV_GDRIVE_URL = 'https://drive.google.com/uc?export=download&id=1eWMjusU3H34m0uml5SdJvYX6gQuB8zta'
Then, if you cat it, you'll get:
,Insult,Date,Comment
11,0,20120530044519Z,"""Be careful,Jimbo.OG has a fork with your name on it."""
1478,0,,"""@dale0987654321 @\\'Micah Carter So you\\'re saying those claims are all false...? I don\\'t know... just from my understanding these are in his book.... but I can be wrong... I\\'m just saying if they are true....should I just assume he\\'s racist?\\n\\nFrom \\'Dreams of My Father\\',""I CEASED TO ADVERISE MY MOTHER\\'S RACE AT THE AGE OF12 OR 13, when I began to suspect that by doing so I was ingratiating myself to whites""From Dreams of My Father, "" I FOUND A SOLACE IN NURSING A PERVASIVE SENSE OF GRIEVANCE AND ANIMOSITY AGAINST MY MOTHER\\'S RACE"".From \\'Dreams of my Father\\', ""The emotion between the races could never be pure..... the THE OTHER RACE (WHITE) WOULD ALWAYS REMAIN JUST THAT: MENACING, ALIEN AND APART""From Dreams Of My Father, ""never emulate white men and brown men whose fates didn\\'t speak to my own. IT WAS INTO MY FATHER\\'S IMAGE , THE BLACK MAN, THE SON OF AFRICA, THAT I\\'D PACKED ALL THE ATTRIBUTES I SOUGHT IN MYSELF.From Dreams Of My Father:""THAT HATE HADN\\'T GONE AWAY,"" he wrote, BLAMING WHITE PEOPLE,- SOME CRUEL, SOME IGNORANT, sometimes a single face, sometimes just a faceless image of a system claiming power over our lives."""""
1983,0,20120610152024Z,"""Only fucking with number 2... that's prolly the only pair i can pull off \xa0out these."""
3201,1,,"""S T F U and pay your dues"""
3549,0,20120530024115Z,"""Worry about your current opponent...."""
3402,1,20120618222736Z,"""And while you're at it, please prove how your ""point"" related to past draconian laws that banned inter-racial marriage?\xa0 That intent was to ""ban"" mixed races.\xa0 Just stop it please! You are insulting intelligence."""
2233,0,20120620034735Z,"""I'd rather have an old, straight white guy than the stupid fcking zebra we have now....everything he touches turns toshit............"""
3219,1,20120619020631Z,"""Only a black racists idiot would claim that the NAACP is not racist in todays world, especially since you're a member.\n\nAnd I don't give a 'bo' whether you take that personally or not."""
3148,0,,"""Fight for money !!! go ahead ,kill yourselfs, all for greed,common, take decision that is not in accordance with what the supreme court says, find some connection by the INEC ,and say to yourself ,HO IS MY TURN TO LOOT NOT YOURS,OR I KILL U.bounch of shameless idiots."""
386,0,,"""The cleverest comment that I have seen for a long time, I think that it was in the Mail\\n\\n \\n\\n\\'Arshavin is the worst Russian Sub since the Kursk"""""
And TEXT.build_vocab(train) will run successfully.
| https://stackoverflow.com/questions/61085648/ |
Pytorch sending inputs/targets to device | Currently using the pycocotools 2.0 library.
My train_loader is:
train_loader, test_loader = get_train_test_loader('dataset', batch_size=16, num_workers=4)
However the training lines of code:
for i, data in enumerate(train_loader, 0):
images, targets = data
images = images.to(device)
targets = targets.to(device)
Results in error. Variables data, images, and targets are all of class tuple
Traceback (most recent call last):
File "train.py", line 40, in <module>
images = images.to(device)
AttributeError: 'tuple' object has no attribute 'to'
How can I properly send these to cuda device?'
Edit:
I can send images[0].to(device) no problem. How can I send the rest?
| You should open the for loop with as many items as your dataset returns at each iteration.
Here is an example to illustrate my point:
Consider the following dataset:
class CustomDataset:
def __getitem__(self, index):
...
return a, b, c
Notice that it returns 3 items at each iteration.
Now let us make a dataloader out of this:
from torch.utils.data import DataLoader
train_dataset = CustomDataset()
train_loader = DataLoader(train_dataset, batch_size=50, shuffle=True)
Now when we use train_loader we should open the for loop with 3 items:
for i, (a_tensor, b_tensor, c_tensor) in enumerate(train_loader):
...
Inside the for loop's context, a_tensor, b_tensor, c_tensor will be tensors with 1st dimension 50 (batch_size).
So, based on the example that you have given, it seems that whatever dataset class your get_train_test_loader function is using has some problem. It is always better to seprately instantiate the dataset and then create the dataloader rather than use a blanket function like the one you have.
| https://stackoverflow.com/questions/61087597/ |
How can I parallelize a for loop for use in PyTorch? | I realize that for loops are slow with Python in general. I have some code that messes around with some tensors:
for batch_index, mask_batch in enumerate(mask):
mask_len = torch.sum(mask_batch).int()
if mask_len == 0:
side_input = torch.zeros((max_inp_len, side_input.shape[1])).to(mask.device)
else:
m_nonzero = mask_batch.nonzero().flatten()
first_nonzero = m_nonzero[0]
last_nonzero = m_nonzero[-1]
if side == 'left':
end_index = first_nonzero - 1
start_index = 0
elif side == 'right':
start_index = last_nonzero + 1
end_index = inputs[batch_index].size(1)
side_input = inputs[batch_index][start_index:end_index]
if end_index - start_index < max_inp_len:
pad_zeros = torch.zeros(
(max_inp_len - side_input.shape[0], side_input.shape[1])).to(mask.device)
if side == 'left':
side_input = torch.cat((pad_zeros, side_input), 0)
elif side == 'right':
side_input = torch.cat((side_input, pad_zeros), 0)
side_inputs.append(side_input)
return torch.stack(side_inputs)
I feel like this loop is REALLY slowing things down. Is there some way for me to do it without the loop?
| Python does not have true parallelism within any given process. You would have to spawn a ProcessPool and make the inside of your loop a function taking batch_index, mask_batch, then map that function over the mask object in your current for loop. Thing is, I don't know if PyTorch will play nicely with this.
Like so
def f(batch_index, mask_batch):
mask_len = torch.sum(mask_batch).int()
if mask_len == 0:
side_input = torch.zeros((max_inp_len, side_input.shape[1])).to(mask.device)
else:
m_nonzero = mask_batch.nonzero().flatten()
first_nonzero = m_nonzero[0]
last_nonzero = m_nonzero[-1]
if side == 'left':
end_index = first_nonzero - 1
start_index = 0
elif side == 'right':
start_index = last_nonzero + 1
end_index = inputs[batch_index].size(1)
side_input = inputs[batch_index][start_index:end_index]
if end_index - start_index < max_inp_len:
pad_zeros = torch.zeros((max_inp_len - side_input.shape[0], side_input.shape[1])).to(mask.device)
if side == 'left':
side_input = torch.cat((pad_zeros, side_input), 0)
elif side == 'right':
side_input = torch.cat((side_input, pad_zeros), 0)
return side_input
The other things you can look at are further vectorizing the code. Most things in PyTorch and Numpy can be vectorized away by using builtin functions and adding another dimension onto your tensors that represents the "loop" dimension. This will allow PyTorch to handle the parallelism for you.
PyTorch may have a concept of devices that you can put different iterations of the loop on, again this will require you to make a function for this loop and maybe take the device it goes on as an input.
Lastly you can look into just in time compliation like Numba or torch.jit to perform auto-vectorization for you.
None of this will work (most likely) if the mask is of an unknown length. If it is of a known length, I think vectorization, as hard as it is, is likely your best choice.
| https://stackoverflow.com/questions/61088837/ |
What is running loss in PyTorch and how is it calculated | I had a look at this tutorial in the PyTorch docs for understanding Transfer Learning. There was one line that I failed to understand.
After the loss is calculated using loss = criterion(outputs, labels), the running loss is calculated using running_loss += loss.item() * inputs.size(0) and finally, the epoch loss is calculated using running_loss / dataset_sizes[phase].
Isn't loss.item() supposed to be for an entire mini-batch (please correct me if I am wrong). i.e, if the batch_size is 4, loss.item() would give the loss for the entire set of 4 images. If this is true, why is loss.item() being multiplied with inputs.size(0) while calculating running_loss? Isn't this step like an extra multiplication in this case?
Any help would be appreciated. Thanks!
| It's because the loss given by CrossEntropy or other loss functions is divided by the number of elements i.e. the reduction parameter is mean by default.
torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
Hence, loss.item() contains the loss of entire mini-batch, but divided by the batch size. That's why loss.item() is multiplied with batch size, given by inputs.size(0), while calculating running_loss.
| https://stackoverflow.com/questions/61092523/ |
NCCL Connection Failed Using PyTorch Distributed | I am trying to send a PyTorch tensor from one machine to another with torch.distributed. The dist.init_process_group function works properly. However, there is a connection failure in the dist.broadcast function. Here is my code on node 0:
import torch
from torch import distributed as dist
import numpy as np
import os
master_addr = '47.xxx.xxx.xx'
master_port = 10000
world_size = 2
rank = 0
backend = 'nccl'
os.environ['MASTER_ADDR'] = master_addr
os.environ['MASTER_PORT'] = str(master_port)
os.environ['WORLD_SIZE'] = str(world_size)
os.environ['RANK'] = str(rank)
dist.init_process_group(backend, init_method='tcp://47.xxx.xxx.xx:10000', timeout=datetime.timedelta(0, 10), rank=rank, world_size=world_size)
print("Finished initializing process group; backend: %s, rank: %d, "
"world_size: %d" % (backend, rank, world_size))
a = torch.from_numpy(np.random.rand(3, 3)).cuda()
dist.broadcast(tensor=a, src=0)
Here is my code on node 1:
import torch
from torch import distributed as dist
import numpy as np
import os
master_addr = '47.xxx.xxx.xx'
master_port = 10000
world_size = 2
rank = 1
backend = 'nccl'
os.environ['MASTER_ADDR'] = master_addr
os.environ['MASTER_PORT'] = str(master_port)
os.environ['WORLD_SIZE'] = str(world_size)
os.environ['RANK'] = str(rank)
dist.init_process_group(backend, init_method='tcp://47.xxx.xxx.xx:10000', timeout=datetime.timedelta(0, 10), rank=rank, world_size=world_size)
print("Finished initializing process group; backend: %s, rank: %d, "
"world_size: %d" % (backend, rank, world_size))
a = torch.zeros((3,3)).cuda()
dist.broadcast(tensor=a, src=0)
I set NCCL_DEBUG=INFO before running the code. Here is the information I got on Node 1:
iZbp11ufz31riqnssil53cZ:13530:13530 [0] NCCL INFO Bootstrap : Using [0]eth0:192.168.0.181<0>
iZbp11ufz31riqnssil53cZ:13530:13530 [0] NCCL INFO NET/Plugin : No plugin found (libnccl-net.so).
iZbp11ufz31riqnssil53cZ:13530:13530 [0] NCCL INFO NET/IB : No device found.
iZbp11ufz31riqnssil53cZ:13530:13530 [0] NCCL INFO NET/Socket : Using [0]eth0:192.168.0.181<0>
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO Setting affinity for GPU 0 to ffff
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO Call to connect returned Connection timed out, retrying
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO Call to connect returned Connection timed out, retrying
iZbp11ufz31riqnssil53cZ:13530:13553 [0] include/socket.h:395 NCCL WARN Connect to 192.168.0.143<59811> failed : Connection timed out
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO bootstrap.cc:100 -> 2
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO bootstrap.cc:326 -> 2
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO init.cc:695 -> 2
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO init.cc:951 -> 2
iZbp11ufz31riqnssil53cZ:13530:13553 [0] NCCL INFO misc/group.cc:69 -> 2 [Async thread]
Traceback (most recent call last):
File "test_dist_1.py", line 25, in <module>
dist.broadcast(tensor=a, src=0)
File "/root/anaconda3/lib/python3.7/site-packages/torch/distributed/distributed_c10d.py", line 806, in broadcast
work = _default_pg.broadcast([tensor], opts)
RuntimeError: NCCL error in: /tmp/pip-req-build-58y_cjjl/torch/lib/c10d/ProcessGroupNCCL.cpp:290, unhandled system error
And Node 0 seems to stuck in function dist.broadcast:
iZuf6cu11ru7evq9ybagdjZ:13530:13530 [0] NCCL INFO Bootstrap : Using [0]eth0:192.168.0.143<0>
iZuf6cu11ru7evq9ybagdjZ:13530:13530 [0] NCCL INFO NET/Plugin : No plugin found (libnccl-net.so).
iZuf6cu11ru7evq9ybagdjZ:13530:13530 [0] NCCL INFO NET/IB : No device found.
iZuf6cu11ru7evq9ybagdjZ:13530:13530 [0] NCCL INFO NET/Socket : Using [0]eth0:192.168.0.143<0>
iZuf6cu11ru7evq9ybagdjZ:13530:13553 [0] NCCL INFO Setting affinity for GPU 0 to ffff
Can anyone help me with this? How can I send the tensor from node 0 to node 1? I would really appreciate any help!
| I found that the two servers that I used were not under the same VPC. Therefore, they can never communicate. So I used other servers under the same VPC and it worked.
| https://stackoverflow.com/questions/61094394/ |
PyTorch tensor advanced indexing | Say i have one matrix and one vector as follows:
x = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
y = torch.tensor([0, 2, 1])
is there a way to slice it x[y] so the result is:
res = [1, 6, 8]
so basically i take the first element of y and take the element in x that corresponds to the first row and the elements' column.
Cheers
| You can specify the corresponding row index as:
import torch
x = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
y = torch.tensor([0, 2, 1])
x[range(x.shape[0]), y]
tensor([1, 6, 8])
| https://stackoverflow.com/questions/61096522/ |
How can I add an element to a PyTorch tensor along a certain dimension? | I have a tensor inps, which has a size of [64, 161, 1] and I have some new data d which has a size of [64, 161]. How can I add d to inps such that the new size is [64, 161, 2]?
| There is a cleaner way by using .unsqueeze() and torch.cat(), which makes direct use of the PyTorch interface:
import torch
# create two sample vectors
inps = torch.randn([64, 161, 1])
d = torch.randn([64, 161])
# bring d into the same format, and then concatenate tensors
new_inps = torch.cat((inps, d.unsqueeze(2)), dim=-1)
print(new_inps.shape) # [64, 161, 2]
Essentially, unsqueezing the second dimension already brings the two tensors into the same shape; you just have to be careful to unsqueeze along the right dimension.
Similarly, the concatenation is unfortunately named differently from the otherwise similarly named NumPy function, but behave the same. Note that instead of letting torch.cat figure out the dimension by providing dim=-1, you can also explicitly provide the dimension to concatenate along, in this case by replacing it with dim=2.
Keep in mind the difference between concatenation and stacking, which is helpful for similar problems with tensor dimensions.
| https://stackoverflow.com/questions/61101919/ |
What is the difference between tensor[:] and tensor in pytorch? | import numpy as np
import time
features, labels = d2l.get_data_ch7()
def init_adam_states():
v_w, v_b = torch.zeros((features.shape[1], 1),dtype=torch.float32), torch.zeros(1, dtype=torch.float32)
s_w, s_b = torch.zeros((features.shape[1], 1),dtype=torch.float32), torch.zeros(1, dtype=torch.float32)
return ((v_w, s_w), (v_b, s_b))
def adam(params, states, hyperparams):
beta1, beta2, eps = 0.9, 0.999, 1e-6
for p, (v, s) in zip(params, states):
v[:] = beta1 * v + (1 - beta1) * p.grad.data
s = beta2 * s + (1 - beta2) * p.grad.data**2
v_bias_corr = v / (1 - beta1 ** hyperparams['t'])
s_bias_corr = s / (1 - beta2 ** hyperparams['t'])
p.data -= hyperparams['lr'] * v_bias_corr / (torch.sqrt(s_bias_corr) + eps)
hyperparams['t'] += 1
def train_ch7(optimizer_fn, states, hyperparams, features, labels, batch_size=10, num_epochs=2):
# 初始化模型
net, loss = d2l.linreg, d2l.squared_loss
w = torch.nn.Parameter(torch.tensor(np.random.normal(0, 0.01, size=(features.shape[1], 1)), dtype=torch.float32),
requires_grad=True)
b = torch.nn.Parameter(torch.zeros(1, dtype=torch.float32), requires_grad=True)
def eval_loss():
return loss(net(features, w, b), labels).mean().item()
ls = [eval_loss()]
data_iter = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(features, labels), batch_size, shuffle=True)
for _ in range(num_epochs):
start = time.time()
print(w)
print(b)
for batch_i, (X, y) in enumerate(data_iter):
l = loss(net(X, w, b), y).mean() # 使⽤平均损失
# 梯度清零
if w.grad is not None:
w.grad.data.zero_()
b.grad.data.zero_()
l.backward()
optimizer_fn([w, b], states, hyperparams) # 迭代模型参数
if (batch_i + 1) * batch_size % 100 == 0:
ls.append(eval_loss()) # 每100个样本记录下当前训练误差
# 打印结果和作图
print('loss: %f, %f sec per epoch' % (ls[-1], time.time() - start))
d2l.set_figsize()
d2l.plt.plot(np.linspace(0, num_epochs, len(ls)), ls)
d2l.plt.xlabel('epoch')
d2l.plt.ylabel('loss')
train_ch7(adam, init_adam_states(), {'lr': 0.01, 't': 1}, features, labels)
I want to implement the Adam algorithm in the follow code and I feel confused in the function named adam.
v = beta1 * v + (1 - beta1) * p.grad.data
s = beta2 * s + (1 - beta2) * p.grad.data**2
when I use the follow code, the loss function curve is figure 1.
figure 1
v[:] = beta1 * v + (1 - beta1) * p.grad.data
s = beta2 * s + (1 - beta2) * p.grad.data**2
or
v = beta1 * v + (1 - beta1) * p.grad.data
s[:] = beta2 * s + (1 - beta2) * p.grad.data**2
when I use the follow code, the loss function curve is figure 2.
figure 2
v[:] = beta1 * v + (1 - beta1) * p.grad.data
s[:] = beta2 * s + (1 - beta2) * p.grad.data**2
when I use the follow code, the loss function curve is figure 3.
figure 3
The loss function curve in case 3 has always been smoother than that in case 1.
The loss function curve in case 2 sometimes can't converge.
Why is different?
| To answer the first question,
v = beta1 * v + (1 - beta1) * p.grad.data
is an out-of-place operation. Remember that python variables are references to objects. By assigning a new value to variable v, the underlying object which v referred to before this assignment will not be changed. Instead the expression beta1 * v + (1 - beta1) * p.grad.data results in a new tensor which is then referred to by v.
On the other hand
v[:] = beta1 * v + (1 - beta1) * p.grad.data
is an in-place operation. After this operation v still refers to the same underlying object, and the elements of that tensor are modified and replaced with the values of the new tensor beta1 * v + (1 - beta1) * p.grad.data.
Take a look at the following 3 lines to see why this matters
for p, (v, s) in zip(params, states):
v[:] = beta1 * v + (1 - beta1) * p.grad.data
s[:] = beta2 * s + (1 - beta2) * p.grad.data**2
v and s are actually referring to tensors which are stored in states. If we do in-place operations then the values in states are changed to reflect the value assigned to v[:] and s[:].
If out-of-place operations are used then the values in states remain unchanged.
| https://stackoverflow.com/questions/61103275/ |
How I can swap 3 dimensions with each other in Pytorch? | I have a a= torch.randn(28, 28, 8) and I want to swap the dimensions of the tensor and move the third dimension to the first place, first one to the second place and the second one to the third place. I used b = a.transpose(2, 0, 1) , but I received this error:
TypeError: transpose() received an invalid combination of arguments - got (int, int, int), but expected one of:
* (name dim0, name dim1)
* (int dim0, int dim1)
Should I use transpose several times, each time only to swap two dimensions? Is there any way that I can swap all at once?
Thanks.
| You can use Pytorch's permute() function to swap all at once,
>>>a = torch.randn(28, 28, 8)
>>>b = a.permute(2, 0, 1)
>>>b.shape
torch.Size([8, 28, 28])
| https://stackoverflow.com/questions/61104138/ |
How do I remove elements from a 3D tensor with PyTorch? | I have a tensor with shape torch.Size([4, 161, 325]). How do I remove the first element along dim=2 so that the resulting tensor has a shape of torch.Size([4, 161, 324])?
| You can use simple slicing,
>>>a = torch.randn(4, 161, 325)
>>>b = a[:, :, 1:]
>>>b.shape
torch.Size([4, 161, 324])
| https://stackoverflow.com/questions/61105070/ |
Transformer Pipeline for NER returns partial words with ##s | How should I interpret the partial words with '##'s in them returned by the Transformer NER pipelines? Other tools like Flair and SpaCy return the word and their tag. I have worked with the CONLL dataset before and never noticed anything like this. Moreover, why are words being divided like this?
Example from the HuggingFace:
from transformers import pipeline
nlp = pipeline("ner")
sequence = "Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very" \
"close to the Manhattan Bridge which is visible from the window."
print(nlp(sequence))
Output:
[
{'word': 'Hu', 'score': 0.9995632767677307, 'entity': 'I-ORG'},
{'word': '##gging', 'score': 0.9915938973426819, 'entity': 'I-ORG'},
{'word': 'Face', 'score': 0.9982671737670898, 'entity': 'I-ORG'},
{'word': 'Inc', 'score': 0.9994403719902039, 'entity': 'I-ORG'},
{'word': 'New', 'score': 0.9994346499443054, 'entity': 'I-LOC'},
{'word': 'York', 'score': 0.9993270635604858, 'entity': 'I-LOC'},
{'word': 'City', 'score': 0.9993864893913269, 'entity': 'I-LOC'},
{'word': 'D', 'score': 0.9825621843338013, 'entity': 'I-LOC'},
{'word': '##UM', 'score': 0.936983048915863, 'entity': 'I-LOC'},
{'word': '##BO', 'score': 0.8987102508544922, 'entity': 'I-LOC'},
{'word': 'Manhattan', 'score': 0.9758241176605225, 'entity': 'I-LOC'},
{'word': 'Bridge', 'score': 0.990249514579773, 'entity': 'I-LOC'}
]
| Pytorch transformers and BERT make 2 tokens, the regular words as tokens and words + sub-words as tokens; which divide words by their base meaning + their complement, addin "##" at the start.
Let's say you have the phrease: I like hugging animals
The first set of tokens would be:
["I", "like", "hugging", "animals"]
And the second list with the sub-words would be:
["I", "like", "hug", "##gging", "animal", "##s"]
You can learn more here:
https://www.kaggle.com/funtowiczmo/hugging-face-tutorials-training-tokenizer
| https://stackoverflow.com/questions/61107371/ |
PyTorch broadcast multiplication of 4D and 2D matrix? | How do I broadcast to multiply these two matrices together?
x: torch.Size([10, 120, 180, 30]) # (N, H, W, C)
W: torch.Size([64, 30]) # (Y, C)
The output should be:
(10, 120, 180, 64) == (N, H, W, Y)
| I assume x is some kind of example with batches and w matrix is the corresponding weight. In this case you could simply do:
out = x @ w.T
which is a tensor multiplication, not an element-wise one. You can't do element-wise multiplication to get such shape and this operation would not make sense. All you could do is to unsqueeze both of the matrics in some way to have their shape broadcastable and apply some operation over dimension you don't want for some reason like this:
x : torch.Size([10, 120, 180, 30, 1])
W: torch.Size([1, 1, 1, 30, 64]) # transposition would be needed as well
After such unsqueezing you could do x*w and sum or mean along the third dim to get desired shape.
For clarity, both ways are not equivalent.
| https://stackoverflow.com/questions/61113563/ |
PyTorch DataLoader shuffle | I did an experiment and I did not get the result I was expecting.
For the first part, I am using
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,
shuffle=False, num_workers=0)
I save trainloader.dataset.targets to the variable a, and trainloader.dataset.data to the variable b before training my model. Then, I train the model using trainloader. After the training is finished, I save trainloader.dataset.targets to the variable c, and trainloader.dataset.data to the variable d. Finally, I check a == c and b == d and they both give True, which was expected because the shuffle parameter of the DataLoader is False.
For the second part, I am using
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,
shuffle=True, num_workers=0)
I save trainloader.dataset.targets to the variable e, and trainloader.dataset.data to the variable f before training my model. Then, I train the model using trainloader. After the training is finished, I save trainloader.dataset.targets to the variable g, and trainloader.dataset.data to the variable h. I expect e == g and f == h to be both False since shuffle=True, but they give True again. What am I missing from the definition of DataLoader class?
| I believe that the data that is stored directly in the trainloader.dataset.data or .target will not be shuffled, the data is only shuffled when the DataLoader is called as a generator or as iterator
You can check it by doing next(iter(trainloader)) a few times without shuffling and with shuffling and they should give different results
import torch
import torchvision
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
])
MNIST_dataset = torchvision.datasets.MNIST('~/Desktop/intern/',download = True, train = False,
transform = transform)
dataLoader = torch.utils.data.DataLoader(MNIST_dataset,
batch_size = 128,
shuffle = False,
num_workers = 10)
target = dataLoader.dataset.targets
MNIST_dataset = torchvision.datasets.MNIST('~/Desktop/intern/',download = True, train = False,
transform = transform)
dataLoader_shuffled= torch.utils.data.DataLoader(MNIST_dataset,
batch_size = 128,
shuffle = True,
num_workers = 10)
target_shuffled = dataLoader_shuffled.dataset.targets
print(target == target_shuffled)
_, target = next(iter(dataLoader));
_, target_shuffled = next(iter(dataLoader_shuffled))
print(target == target_shuffled)
This will give :
tensor([True, True, True, ..., True, True, True])
tensor([False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, True,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, True, False, False, False, False, False,
False, True, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, True, True, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, True, False, False, True, False,
False, False, False, False, False, False, False, False])
However the data and label stored in data and target is a fixed list and since you are trying to access it directly, they will not be shuffled.
| https://stackoverflow.com/questions/61115032/ |
Append feature maps to intermediate layers of network in PyTorch | I have the following PyTorch network architecture shown below. It takes in the input of size 16x8x2048, and gives an output of size 256x128x3. I have a feature map that I want to append along the channel dimension after every upsampling layer in the below architecture. I would be scaling the feature maps to the appropriate resolution before appending. How can I append these feature maps in the intermediate layers of the network?
model = []
model += [Conv2dBlock(2048, 256, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)]
model += [nn.Upsample(scale_factor=2, mode='bilinear')]
model += [Conv2dBlock(256, 128, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)]
model += [nn.Upsample(scale_factor=2, mode='bilinear')]
model += [Conv2dBlock(128, 64, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)]
model += [nn.Upsample(scale_factor=2, mode='bilinear')]
model += [Conv2dBlock(64, 32, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)]
model += [nn.Upsample(scale_factor=2, mode='bilinear')]
model += [Conv2dBlock(32, 32, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)]
model += [Conv2dBlock(32, 3, 3, 1, 1, norm='none', activation=activ, pad_type=pad_type)]
model = nn.Sequential(*model)
| So the solution was just changing the way in which the network is written as pointed out by https://stackoverflow.com/users/10229754/mercury. The following change shows a way in which the network can be written so that is possible to append additional input. In the forward() function, the input can be directly appended using torch.cat()-
conv1 = Conv2dBlock(2063, 256, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)
up1 = nn.Upsample(scale_factor=2, mode='bilinear')
conv2 = Conv2dBlock(256, 128, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)
up2 = nn.Upsample(scale_factor=2, mode='bilinear')
conv3 = Conv2dBlock(128, 64, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)
up3 = nn.Upsample(scale_factor=2, mode='bilinear')
conv4 = Conv2dBlock(64, 32, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)
up4 = nn.Upsample(scale_factor=2, mode='bilinear')
conv5 = Conv2dBlock(32, 32, 3, 1, 1, norm='bn', activation=activ, pad_type=pad_type)
conv6 = Conv2dBlock(32, 3, 3, 1, 1, norm='none', activation=activ, pad_type=pad_type)
| https://stackoverflow.com/questions/61115480/ |
Interpretation of in_channels and out_channels in Conv2D in Pytorch Convolution Neural Networks (CNN) | Let us suppose I have a CNN with starting 2 layers as:
inp_conv = Conv2D(in_channels=1,out_channels=6,kernel_size=(3,3))
Please correct me if I am wrong but I think what this line if code can be thought as that
There is a single grayscale image coming as input where we have to use 6 different kernals of same size (3,3) to make 6 different feature maps from a single image.
And if I have a second Conv2D layer just after first one as
second_conv_connected_to_inp_conv = Conv2D(in_channels=6,out_channels=12,kernel_size=(3,3))
What does this mean in terms of out_channels? Is there going to be 12 new feature maps for each of the 6 feature maps coming as output from first layer OR are there going to be a total of 12 feature maps from 6 incoming features?
| For each out_channel, you have a set of kernels for each in_channel.
Equivalently, each out_channel has an in_channel x height x width kernel:
for i in nn.Conv2d(in_channels=2, out_channels=3, kernel_size=(4, 5)).parameters():
print(i)
Output:
Parameter containing:
tensor([[[[-0.0012, 0.0848, -0.1301, -0.1164, -0.0609],
[ 0.0424, -0.0031, 0.1254, -0.0140, 0.0418],
[-0.0478, -0.0311, -0.1511, -0.1047, -0.0652],
[ 0.0059, 0.0625, 0.0949, -0.1072, -0.0689]],
[[ 0.0574, 0.1313, -0.0325, 0.1183, -0.0255],
[ 0.0167, 0.1432, -0.1467, -0.0995, -0.0400],
[-0.0616, 0.1366, -0.1025, -0.0728, -0.1105],
[-0.1481, -0.0923, 0.1359, 0.0706, 0.0766]]],
[[[ 0.0083, -0.0811, 0.0268, -0.1476, -0.1142],
[-0.0815, 0.0998, 0.0927, -0.0701, -0.0057],
[ 0.1011, 0.1572, 0.0628, 0.0214, 0.1060],
[-0.0931, 0.0295, -0.1226, -0.1096, -0.0817]],
[[ 0.0715, 0.0636, -0.0937, 0.0478, 0.0868],
[-0.0200, 0.0060, 0.0366, 0.0981, 0.1518],
[-0.1218, -0.0579, 0.0621, 0.1310, 0.1376],
[ 0.1395, 0.0315, -0.1375, 0.0145, -0.0989]]],
[[[-0.1474, 0.1405, 0.1202, -0.1577, 0.0296],
[-0.0266, -0.0260, -0.0724, 0.0608, -0.0937],
[ 0.0580, 0.0800, 0.1132, 0.0591, -0.1565],
[-0.1026, 0.0789, 0.0331, -0.1233, -0.0910]],
[[ 0.1487, 0.1065, -0.0689, -0.0398, -0.1506],
[-0.0028, -0.1191, -0.1220, -0.0087, 0.0237],
[-0.0648, 0.0938, -0.0962, 0.1435, 0.1084],
[-0.1333, -0.0394, 0.0071, 0.0231, 0.0375]]]], requires_grad=True)
Parameter containing:
tensor([ 0.0620, 0.0095, -0.0771], requires_grad=True)
A more detailed example going from 1 channel input, through 2 and 4 channel convolutions:
import torch
torch.manual_seed(0)
input0 = torch.randint(-1, 1, (1, 1, 8, 8)).type(torch.FloatTensor)
print('input0:', input0.size())
print(input0.data)
layer0 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=2, stride=2, padding=0, bias=False)
print('\nlayer1:')
for i in layer0.parameters():
print(i.size())
i.data = torch.randint(-1, 1, i.size()).type(torch.FloatTensor)
print(i.data)
output0 = layer0(input0)
print('\noutput0:', output0.size())
print(output0.data)
print('\nlayer1:')
layer1 = nn.Conv2d(in_channels=2, out_channels=4, kernel_size=2, stride=2, padding=0, bias=False)
for i in layer1.parameters():
print(i.size())
i.data = torch.randint(-1, 1, i.size()).type(torch.FloatTensor)
print(i.data)
output1 = layer1(output0)
print('\noutput1:', output1.size())
print(output1.data)
output:
input0: torch.Size([1, 1, 8, 8])
tensor([[[[-1., 0., 0., -1., 0., 0., 0., 0.],
[ 0., 0., 0., -1., -1., 0., -1., -1.],
[-1., -1., -1., 0., -1., 0., 0., -1.],
[-1., 0., 0., 0., 0., -1., 0., -1.],
[ 0., -1., 0., 0., -1., 0., 0., -1.],
[-1., 0., -1., 0., 0., 0., 0., 0.],
[-1., 0., -1., 0., 0., 0., 0., -1.],
[ 0., -1., -1., 0., 0., -1., 0., -1.]]]])
layer1:
torch.Size([2, 1, 2, 2])
tensor([[[[-1., -1.],
[-1., 0.]]],
[[[ 0., -1.],
[ 0., -1.]]]])
output0: torch.Size([1, 2, 4, 4])
tensor([[[[1., 1., 1., 1.],
[3., 1., 1., 1.],
[2., 1., 1., 1.],
[1., 2., 0., 1.]],
[[0., 2., 0., 1.],
[1., 0., 1., 2.],
[1., 0., 0., 1.],
[1., 0., 1., 2.]]]])
layer1:
torch.Size([4, 2, 2, 2])
tensor([[[[-1., -1.],
[-1., -1.]],
[[ 0., -1.],
[ 0., -1.]]],
[[[ 0., 0.],
[ 0., 0.]],
[[ 0., -1.],
[ 0., 0.]]],
[[[ 0., 0.],
[-1., 0.]],
[[ 0., -1.],
[-1., 0.]]],
[[[-1., -1.],
[-1., -1.]],
[[ 0., 0.],
[-1., -1.]]]])
output1: torch.Size([1, 4, 2, 2])
tensor([[[[-8., -7.],
[-6., -6.]],
[[-2., -1.],
[ 0., -1.]],
[[-6., -3.],
[-2., -2.]],
[[-7., -7.],
[-7., -6.]]]])
Breaking down the linear algebra:
np.sum(
# kernel for layer1, in_channel 0, out_channel 0
# multiplied by output0, channel 0, top left corner
(np.array([[-1., -1.],
[-1., -1.]]) * \
np.array([[1., 1.],
[3., 1.]])) + \
# kernel for layer1, in_channel 1, out_channel 0
# multiplied by output0, channel 1, top left corner
(np.array([[ 0., -1.],
[ 0., -1.]]) * \
np.array([[0., 2.],
[1., 0.]]))
)
This will be equal to output1, channel 0, top left corner:
-8.0
| https://stackoverflow.com/questions/61116355/ |
How to use custom torch.autograd.Function in nn.Sequential model | Is there any way that I can use custom torch.autograd.Function in a nn.Sequential object or should I use explicitly an nn.Module object with forward function. Specifically I am trying to implement a sparse autoencoder and I need to add L1 distance of the code(hidden representation) to the loss.
I have defined custom torch.autograd.Function L1Penalty below then tried to use it inside a nn.Sequential object as below. However when I run I got the error TypeError: __main__.L1Penalty is not a Module subclass How can I solve this issue?
class L1Penalty(torch.autograd.Function):
@staticmethod
def forward(ctx, input, l1weight = 0.1):
ctx.save_for_backward(input)
ctx.l1weight = l1weight
return input, None
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_variables
grad_input = input.clone().sign().mul(ctx.l1weight)
grad_input+=grad_output
return grad_input
model = nn.Sequential(
nn.Linear(10, 10),
nn.ReLU(),
nn.Linear(10, 6),
nn.ReLU(),
# sparsity
L1Penalty(),
nn.Linear(6, 10),
nn.ReLU(),
nn.Linear(10, 10),
nn.ReLU()
).to(device)
| The right way to do that would be this
import torch, torch.nn as nn
class L1Penalty(torch.autograd.Function):
@staticmethod
def forward(ctx, input, l1weight = 0.1):
ctx.save_for_backward(input)
ctx.l1weight = l1weight
return input
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_variables
grad_input = input.clone().sign().mul(ctx.l1weight)
grad_input+=grad_output
return grad_input
Creating a Lambda class that acts as a wrapper
class Lambda(nn.Module):
"""
Input: A Function
Returns : A Module that can be used
inside nn.Sequential
"""
def __init__(self, func):
super().__init__()
self.func = func
def forward(self, x): return self.func(x)
TA-DA!
model = nn.Sequential(
nn.Linear(10, 10),
nn.ReLU(),
nn.Linear(10, 6),
nn.ReLU(),
# sparsity
Lambda(L1Penalty.apply),
nn.Linear(6, 10),
nn.ReLU(),
nn.Linear(10, 10),
nn.ReLU())
a = torch.rand(50,10)
b = model(a)
print(b.shape)
| https://stackoverflow.com/questions/61117361/ |
How to change the values of a 2d tensor in certain rows and columns | Suppose I have an all-zero mask tensor like this:
mask = torch.zeros(5,3, dtype=torch.bool)
Now I want to set the value of mask at the intersection of the following rows and cols indices to True:
rows = torch.tensor([0,2,4])
cols = torch.tensor([1,2])
I would like to produce the following result:
tensor([[False, True, True ],
[False, False, False],
[False, True, True ],
[False, False, False],
[False, True, True ]])
When I try the following code, I receive an error:
mask[rows, cols] = True
IndexError: shape mismatch: indexing tensors could not be broadcast together with shapes [3], [2]
How can I do that efficiently in PyTorch?
| You need proper shape for that you can use torch.unsqueeze
mask = torch.zeros(5,3, dtype=torch.bool)
mask[rows, cols.unsqueeze(1)] = True
mask
tensor([[False, True, True],
[False, False, False],
[False, True, True],
[False, False, False],
[False, True, True]])
or torch.reshape
mask[rows, cols.reshape(-1,1)] = True
mask
tensor([[False, True, True],
[False, False, False],
[False, True, True],
[False, False, False],
[False, True, True]])
| https://stackoverflow.com/questions/61117634/ |
Pytorch Error: Optimizer got an Empty Parameter List on Linux server | I am running FasterRCNN code and was experimenting with various backbones (resnet18...101). I have created FasterRCNN class with init function. While training on my linux server I am facing the "Empty Parameter" error (can be seen in the attached image 1)
While the same code is running without any error on my local machine.
I am using Anaconda distribution 4.0.1 and Python 3.7 with pytorch 1.2
Below you can refer my code (model and train) -
class Faster_RCNN(nn.Module):
def __init__(self, num_classes=2, backbone = 'mobilenet_v2', test= False):
super(Faster_RCNN, self).__init__()
self.classes = num_classes # replace the classifier with a new one, that has num_classes 2 for our use.
# 1 class (bar) + background
self.test = test
self.backbone = backbone
print('....Initializing Model....\n')
print(f'....This model uses {self.backbone} as backbone....\n')
if self.backbone == 'mobilenet_v2':
backbone = torchvision.models.mobilenet_v2(pretrained=True).features
backbone.out_channels = 1280
anchor_generator = AnchorGenerator(sizes=((32, 64, 128),),
aspect_ratios=((1.0),))
roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0],
output_size=7,
sampling_ratio=2)
self.model = FasterRCNN(backbone,
num_classes=2,
rpn_anchor_generator=anchor_generator,
box_roi_pool=roi_pooler)
if self.backbone == 'resnet18':
bb = torchvision.models.resnet18(pretrained=True)
backbone = nn.Sequential(*list(bb.children())[:-2])
backbone.out_channels = 512
anchor_generator = AnchorGenerator(sizes=((32, 64, 128),),
aspect_ratios=((1.0),))
roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0],
output_size=7,
sampling_ratio=2)
self.model = FasterRCNN(backbone,
num_classes=2,
rpn_anchor_generator=anchor_generator,
box_roi_pool=roi_pooler)
if self.backbone == 'resnet34':
bb = torchvision.models.resnet34(pretrained=True)
backbone = nn.Sequential(*list(bb.children())[:-2])
backbone.out_channels = 512
anchor_generator = AnchorGenerator(sizes=((32, 64, 128),),
aspect_ratios=((1.0),))
roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0],
output_size=7,
sampling_ratio=2)
self.model = FasterRCNN(backbone,
num_classes=2,
rpn_anchor_generator=anchor_generator,
box_roi_pool=roi_pooler)
if self.backbone == 'resnet50':
bb = torchvision.models.resnet50(pretrained=True)
backbone = nn.Sequential(*list(bb.children())[:-2])
backbone.out_channels = 2048
anchor_generator = AnchorGenerator(sizes=((32, 64, 128),),
aspect_ratios=((1.0),))
roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0],
output_size=7,
sampling_ratio=2)
self.model = FasterRCNN(backbone,
num_classes=2,
rpn_anchor_generator=anchor_generator,
box_roi_pool=roi_pooler)
if self.backbone == 'resnet101':
bb = torchvision.models.resnet50(pretrained=True)
backbone = nn.Sequential(*list(bb.children())[:-2])
backbone.out_channels = 2048
anchor_generator = AnchorGenerator(sizes=((32, 64, 128),),
aspect_ratios=((1.0),))
roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0],
output_size=7,
sampling_ratio=2)
self.model = FasterRCNN(backbone,
num_classes=2,
rpn_anchor_generator=anchor_generator,
box_roi_pool=roi_pooler)
def forward(self, x,y):
if self.test:
pred = self.model(x)
else:
pred = self.model(x,y)
return pred
Here is the train code:
import dataloader
import model as md
import numpy as np
#import matplotlib.pyplot as plt
import torch
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
import argparse
writer = SummaryWriter()
bkbone = ['resnet18','resenet34','resenet50','resnet101']
for bbone in bkbone:
ap = argparse.ArgumentParser()
ap.add_argument("-b", "--backbone", required = False, default = bbone, help = "resenet18, resnet34, resnet50, resenet101 and mobilenet_v2 can be given")
args = vars(ap.parse_args())
epochs = 1000
batch_size = 10
lr = 0.005
path = 'D:\\beantech_Data\\objtect_detection'
# path = '/media/TBDataStudent/pankaj/beantech/object_detection'
data= dataloader.Bar(root=path, batch_size=batch_size)
model = md.Faster_RCNN(backbone=args['backbone']).cuda()
model.train()
optimizer = Adam(model.parameters(), lr = lr, weight_decay=0.0005)
lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer,step_size=3,gamma=0.1)
### Train ###
for epoch in range(epochs):
loss_classifier=[]
loss_box_reg =[]
loss_objectness = []
loss_rpn_box_reg = []
Tloss = []
for _, (img, label) in enumerate(data.train_loader):
images = [image.cuda() for image in img ]
for i in range(len(label)):
label[i]['boxes']=label[i]['boxes'].cuda()
label[i]['labels']=label[i]['labels'].cuda()
optimizer.zero_grad()
output = model(images, label)
l1, l2, l3, l4 = output
loss_classifier.append(output[l1].item())
loss_box_reg.append(output[l2].item())
loss_objectness.append(output[l3].item())
loss_rpn_box_reg.append(output[l4].item())
loss = sum(list(output.values()))
loss.backward()
optimizer.step()
Tloss.append(loss.item())
writer.add_scalar(l1, np.mean(loss_classifier), epoch)
writer.add_scalar(l2, np.mean(loss_box_reg), epoch)
writer.add_scalar(l3, np.mean(loss_objectness), epoch)
writer.add_scalar(l4, np.mean(loss_rpn_box_reg), epoch)
writer.add_scalar('Total Loss', np.mean(Tloss), epoch)
print(f'\n\n --{l1}: {np.mean(loss_classifier)}\n --{l2}: {np.mean(loss_box_reg)}\n --{l3}: {np.mean(loss_objectness)}\n --{l4}: {np.mean(loss_rpn_box_reg)}')
print(f'Total loss of epoch {epoch}is: {np.mean(Tloss)}')
writer.close()
torch.save(model.state_dict(), f'FasterRCNN_{args["backbone"]}'+'.pt')
| There was pytorch version mismatch. I updated the server with latest pytorch and everything is running smooth.
thanks everyone for the help.
| https://stackoverflow.com/questions/61119756/ |
Asking gpt-2 to finish sentence with huggingface transformers | I am currently generating text from left context using the example script run_generation.py of the huggingface transformers library with gpt-2:
$ python transformers/examples/run_generation.py \
--model_type gpt2 \
--model_name_or_path gpt2 \
--prompt "Hi, " --length 5
=== GENERATED SEQUENCE 1 ===
Hi, could anyone please inform me
I would like to generate short complete sentences. Is there any way to tell the model to finish a sentence before length words?
Note: I don't mind changing model, but would prefer an auto-regressive one.
| Unfortunately there is no way to do so. You can set the length parameter to a greater value and then just discard the incomplete part at the end.
Even GPT3 doesn't support completing a sentence before a specific length. GPT3 support "sequences" though. Sequences force the model to stop when certain condition is fulfilled. You can find more information about in thi article
| https://stackoverflow.com/questions/61121982/ |
training by batches leads to more over-fitting | I'm training a sequence to sequence (seq2seq) model and I have different values to train on for the input_sequence_length.
For values 10 and 15, I get acceptable results but when I try to train with 20, I get memory errors so I switched the training to train by batches but the model over-fit and the validation loss explodes, and even with the accumulated gradient I get the same behavior, so I'm looking for hints and leads to more accurate ways to do the update.
Here is my training function (only with batch section) :
if batch_size is not None:
k=len(list(np.arange(0,(X_train_tensor_1.size()[0]//batch_size-1), batch_size )))
for epoch in range(num_epochs):
optimizer.zero_grad()
epoch_loss=0
for i in list(np.arange(0,(X_train_tensor_1.size()[0]//batch_size-1), batch_size )): # by using equidistant batch till the last one it becomes much faster than using the X.size()[0] directly
sequence = X_train_tensor[i:i+batch_size,:,:].reshape(-1, sequence_length, input_size).to(device)
labels = y_train_tensor[i:i+batch_size,:,:].reshape(-1, sequence_length, output_size).to(device)
# Forward pass
outputs = model(sequence)
loss = criterion(outputs, labels)
epoch_loss+=loss.item()
# Backward and optimize
loss.backward()
optimizer.step()
epoch_loss=epoch_loss/k
model.eval
validation_loss,_= evaluate(model,X_test_hard_tensor_1,y_test_hard_tensor_1)
model.train()
training_loss_log.append(epoch_loss)
print ('Epoch [{}/{}], Train MSELoss: {}, Validation : {} {}'.format(epoch+1, num_epochs,epoch_loss,validation_loss))
EDIT:
here are the parameters that I'm training with :
batch_size = 1024
num_epochs = 25000
learning_rate = 10e-04
optimizer=torch.optim.Adam(model.parameters(), lr=learning_rate)
criterion = nn.MSELoss(reduction='mean')
| Batch size affects regularization. Training on a single example at a time is quite noisy, which makes it harder to overfit. Training on batches smoothes everything out, which makes it easier to overfit. Translating back to regularization:
Smaller batches add regularization.
Larger batches reduce regularization.
I am also curious about your learning rate. Every call to loss.backward() will accumulate the gradient. If you have set your learning rate to expect a single example at a time, and not reduced it to account for batch accumulation, then one of two things will happen.
The learning rate will be too high for the now-accumulated gradient, training will diverge, and both training and validation errors will explode.
The learning rate won't be too high, and nothing will diverge. The model will just train more quickly and effectively. If the model is too large for the data being fit, then training error will go to 0 but validation error will explode due to overfitting.
Update
Here is a bit more detail regarding the gradient accumulation.
Every call to loss.backward() will accumulate gradient, until you reset it with optimizer.zero_grad(). It will be acted on when you call optimizer.step(), based on whatever it has accumulated.
The way your code is written, you call loss.backward() for every pass through the inner loop, then you call optimizer.step() in the outer loop before resetting. So the gradient has been accumulated, that is summed, over all examples in the batch and not just one example at a time.
Under most assumptions, that will make the batch-accumulated gradient larger than the gradient for a single example. If the gradients are all aligned, for B batches, it will be larger by B times. If the gradients are i.i.d. then it will be more like sqrt(B) times larger.
If you do not account for this, then you have effectively increased your learning rate by that factor. Some of that will be mitigated by the smoothing effect of larger batches, which can then tolerate a higher learning rate. Larger batches reduce regularization, larger learning rates add it back. But that will not be a perfect match to compensate, so you will still want to adjust accordingly.
In general, whenever you change your batch size you will also want to re-tune your learning rate to compensate.
Leslie N. Smith has written some excellent papers on a methodical approach to hyperparameter tuning. A great place to start is A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, momentum, and weight decay. He recommends you start by reading the diagrams, which are very well done.
| https://stackoverflow.com/questions/61122561/ |
How can I trim / remove part of a Tensor to match the shape of another Tensor with PyTorch? | I have 2 tensors:
outputs: torch.Size([4, 27, 161]) pred: torch.Size([4, 30, 161])
I want to cut pred (from the end) so that it'll have the same dimensions as outputs.
What's the best way to do it with PyTorch?
| You can use Narrow
e.g:
a = torch.randn(4,30,161)
a.size() # torch.Size([4, 30, 161])
a.narrow(1,0,27).size() # torch.Size([4, 27, 161])
| https://stackoverflow.com/questions/61122798/ |
Way too much resources are used with Pytorch | I am using pytorch to train a DQN model. With ubuntu, if I use htop, I get
As you can see, all resources are used and I am a bit worried about that.
Here is my code.
Is there a way to use less resource? Do I have to add my requirement using pytorch?
Be aware that there's no GPUs on my machine, just CPUs
| Yes, there is. You can use torch.set_num_threads(...) to specify the number of threads. Depending on the PyTorch version you use, maybe this function will not work correctly. See why in this issue. In there, you'll see that if needed you can use environment variables to limit OpenMP or MKL threads usage via OMP_NUM_THREADS=? and MKL_NUM_THREADS=? respectively, where ? is the number of threads.
Keep in mind that these things are expected to run on GPUs with thousands of cores, so I would limit CPU usage only when extremely necessary.
| https://stackoverflow.com/questions/61123978/ |
How to use ITK to convert PNG into tensor for PyTorch | I'm trying to run a C++ PyTorch framework and ran into the following problem.
I successfully scripted a model and is now ready to run. Now I have to feed in a png image to the model.
I found someone with simmilar issue on the internet, his idea was to use ITK module to read in a PNG file and convert it to a array, then make it to Tensor.
PNG -> RGBPixel[] -> tensor
So the following is what I am trying out right now.
using PixelTyupe = itk::RGBPixel<unsinged char>;
const unsigned int Dimension = 3;
typedef itk::Image<PixelType, Dimension> ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
typedef itk::ImageRegionIterator<ImageType> IteratorType;
typename ImageType::RegionType region = itk_img->GetLargestPossibleRegion();
const typename ImageType::SizeType size = region.GetSize();
int len = size[0] * size[1] * size[2]; // This ends up 1920 * 1080 * 1
PixelType rowdata[len];
int count = 0;
IteratorType iter(itk_img, itk_img->GetRequestedRegion());
// convert itk to array
for (iter.GoToBegin(); !iter.IsAtEnd(); ++iter) {
rowdata[count] = iter.Get();
count++;
} // count = 1920 * 1080
// convert array to tensor
tensor_img = torch::from_blob(rowdata, {3, (int)size[0], (int)size[1]}, torch::kShort). clone(); // Segmenation Fault
When I try to print log data, it holds three numbers like 84 85 83, so I suppose the PNG file is successfully read.
However, I can't get the last part of the code to work. What I need is 3:1920:1080 tensor, but I don't think the three RGBPixel value is understood properly by the function.
And apart from that, I don't see why the dimension is set to 3.
I would appreciate any kind of help.
| You don't need dimension 3, Dimension = 2 is sufficient. If the layout you need is RGBx1920x1080, then PixelType* rowdata = itk_img->GetBufferPointer(); would get you that layout without further processing. As torch::from_blob does not take ownership of the buffer, the other person was trying to use .clone(). You don't have to do that either, assuming you keep the itk_img in scope, or muck around with its reference count and deleter.
The crash probably comes from saying the buffer has short pixels (torch::kShort), when it has uchar.
| https://stackoverflow.com/questions/61125616/ |
How to deserialize a PyTorch saved model with private methods inside a class? | I used the PyTorch saving method to serialize a bunch of essential objects. Among those, there was one class referencing a private method inside the __init__ of that same class. Now, after the serialization, I can't deserialize (unpickle) files because the private method is not accessible outside the class. Any idea how to solve or bypass it? I need to recover the data saved into the attributes of that class.
File ".conda/envs/py37/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-a5666d77c70f>", line 1, in <module>
torch.load("snapshots/model.pth", map_location='cpu')
File ".conda/envs/py37/lib/python3.7/site-packages/torch/serialization.py", line 529, in load
return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)
File ".conda/envs/py37/lib/python3.7/site-packages/torch/serialization.py", line 702, in _legacy_load
result = unpickler.load()
AttributeError: 'Trainer' object has no attribute '__iterator'
EDIT-1:
Here there is a piece of code that will generate the problem I’m facing right now.
import torch
class Test:
def __init__(self):
self.a = min
self.b = max
self.c = self.__private # buggy
def __private(self):
return None
test = Test()
torch.save({"test": test}, "file.pkl")
torch.load("file.pkl")
However, if you remove the private attribute from the method, you won’t get any error.
import torch
class Test:
def __init__(self):
self.a = min
self.b = max
self.c = self.private # not buggy
def private(self):
return None
test = Test()
torch.save({"test": test}, "file.pkl")
torch.load("file.pkl")
| This question is similar to Python multiprocessing - mapping private method, but can not be marked as duplicate because of the open bounty.
The issue arises from this open issue on the Python bug tracker: Objects referencing private-mangled names do not roundtrip properly under pickling, and is related to the way pickle handles name-mangling. More details on this answer: https://stackoverflow.com/a/57497698/6352677.
At this point, the only workaround is not using private methods in __init__.
| https://stackoverflow.com/questions/61128428/ |
Difficulty in understanding the tokenizer used in Roberta model | from transformers import AutoModel, AutoTokenizer
tokenizer1 = AutoTokenizer.from_pretrained("roberta-base")
tokenizer2 = AutoTokenizer.from_pretrained("bert-base-cased")
sequence = "A Titan RTX has 24GB of VRAM"
print(tokenizer1.tokenize(sequence))
print(tokenizer2.tokenize(sequence))
Output:
['A', 'ĠTitan', 'ĠRTX', 'Ġhas', 'Ġ24', 'GB', 'Ġof', 'ĠVR', 'AM']
['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M']
Bert model uses WordPiece tokenizer. Any word that does not occur in the WordPiece vocabulary is broken down into sub-words greedily. For example, 'RTX' is broken into 'R', '##T' and '##X' where ## indicates it is a subtoken.
Roberta uses BPE tokenizer but I'm unable to understand
a) how BPE tokenizer works?
b) what does G represents in each of tokens?
| This question is extremely broad, so I'm trying to give an answer that focuses on the main problem at hand. If you feel the need to have other questions answered, please open another question focusing on one question at a time, see the [help/on-topic] rules for Stackoverflow.
Essentially, as you've correctly identified, BPE is central to any tokenization in modern deep networks. I highly recommend you to read the original BPE paper by Sennrich et al., in which they also highlight a bit more of the history of BPEs.
In any case, the tokenizers for any of the huggingface models are pretrained, meaning that they are usually generated from the training set of the algorithm beforehand. Common implementations such as SentencePiece also give a bit better understanding of it, but essentially the task is framed as a constrained optimization problem, where you specify a maximum number of k allowed vocabulary words (the constraint), and the algorithm tries to then keep as many words intact without exceeding k.
if there are not enough words to cover the whole vocabulary, smaller units are used to approximate the vocabulary, which results in the splits observed in the example you gave.
RoBERTa uses a variant called "byte-level BPE", the best explanation is probably given in this study by Wang et al.. The main benefit is, that it results in a smaller vocabulary while maintaining the quality of splits, from what I understand.
The second part of your question is easier to explain; while BERT highlights the merging of two subsequent tokens (with ##), RoBERTa's tokenizer instead highlights the start of a new token with a specific unicode character (in this case, \u0120, the G with a dot). The best reason I could find for this was this thread, which argues that it basically avoids the use of whitespaces in training.
| https://stackoverflow.com/questions/61134275/ |
Error in Transforming custom Dataset in Pytorch | I was following this tutorial: https://pytorch.org/tutorials/beginner/data_loading_tutorial.html for making my own custom data loader for MuNuSeg Dataset but I am stuck a point. The dataloader is working fine but when I add transforms to it, I get errors.
I am facing an issue similar to what is mentioned here :
Error Utilizing Pytorch Transforms and Custom Dataset
According to the answer there I have made custom transform for each of the inbuilt transforms so that one whole sample is transformed at the same time. Below are my custom transforms
class AffineTrans(object):
def __init__(self, degrees, translate):
self.degrees = degrees
self.translate = translate
def __call__(self, sample):
image, contour, clrmask = sample['image'], sample['contour'], sample['clrmask']
TF = transforms.RandomAffine(degrees = self.degrees, translate=self.translate)
image = TF(image)
contour = TF(contour)
clrmask = (clrmask)
class Flip(object):
def __call__(self, sample):
image, contour, clrmask = sample['image'], sample['contour'], sample['clrmask']
TF1 = transforms.RandomHorizontalFlip()
TF2 = transforms.RandomVerticalFlip()
image = TF1(image)
contour = TF1(contour)
clrmask = TF1(clrmask)
image = TF2(image)
contour = TF2(contour)
clrmask = TF2(clrmask)
class ClrJitter(object):
def __init__(self, brightness, contrast, saturation, hue):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
def __call__(self, sample):
image, contour, clrmask = sample['image'], sample['contour'], sample['clrmask']
TF = transforms.ColorJitter(self.brightness, self.contrast, self.saturation, self.hue)
image = TF(image)
contour = TF(contour)
clrmask = TF(clrmask)
And composed them in the following way
composed = transforms.Compose([RandomCrop(256),
AffineTrans(15.0,(0.1,0.1)),
Flip(),
ClrJitter(10, 10, 10, 0.01),
ToTensor()])
And here's the trainLoader Code
class trainLoader(Dataset):
def __init__(self, transform=None):
"""
Args:
transform (callable, optional): Optional transform to be applied
on a sample.
"""
[self.train_data , self.test_data1, self.test_data2] = dirload()
self.transform = transform
def __len__(self):
return(len(self.train_data[0]))
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
img_name = self.train_data[0][idx]
contour_name = self.train_data[1][idx]
color_name = self.train_data[2][idx]
image = cv2.imread(img_name)
contour = cv2.imread(contour_name)
clrmask = cv2.imread(color_name)
sample = {'image': image, 'contour': contour, 'clrmask': clrmask}
if self.transform:
sample = self.transform(sample)
return sample
To check the working of the above code I am doing the following
train_dat = trainLoader(composed)
for i in range(len(train_dat)):
sample = train_dat[i]
print(i, sample['image'].shape, sample['contour'].shape, sample['clrmask'].shape)
cv2.imshow('sample',sample['image'])
cv2.waitKey()
if i == 3:
break
But I am still, again and again, Encountering the following error
runcell(0, 'F:/Moodle/SEM 8/SRE/code/MoNuSeg/main.py')
runcell(1, 'F:/Moodle/SEM 8/SRE/code/MoNuSeg/main.py')
Traceback (most recent call last):
File "F:\Moodle\SEM 8\SRE\code\MoNuSeg\main.py", line 212, in <module>
sample = train_dat[i]
File "F:\Moodle\SEM 8\SRE\code\MoNuSeg\main.py", line 109, in __getitem__
sample = self.transform(sample)
File "F:\Moodle\Anaconda3\lib\site-packages\torchvision\transforms\transforms.py", line 60, in __call__
img = t(img)
File "F:\Moodle\SEM 8\SRE\code\MoNuSeg\main.py", line 156, in __call__
image = TF(image)
File "F:\Moodle\Anaconda3\lib\site-packages\torchvision\transforms\transforms.py", line 1018, in __call__
ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img.size)
File "F:\Moodle\Anaconda3\lib\site-packages\torchvision\transforms\transforms.py", line 992, in get_params
max_dx = translate[0] * img_size[0]
TypeError: 'int' object is not subscriptable
This is quite an ambiguous error as I exactly don't get what is the error is
Any help would be really appreciated
| The problem is that you're passing a NumPy array, whereas the transform expects a PIL Image. You can fix that by adding transforms.ToPILImage() as the first transform:
composed = transforms.Compose([
transforms.ToPILImage(),
RandomCrop(256),
AffineTrans(15.0,(0.1,0.1)),
Flip(),
ClrJitter(10, 10, 10, 0.01),
ToTensor()
])
Assuming you have a from torchvision import transforms at the beginning.
The root of the problem is that you're using OpenCV to load the images:
def __getitem__(self, idx):
# [...]
image = cv2.imread(img_name)
and you could replace these loading calls from OpenCV to PIL to solve the problem as well.
Just so you know, for NumPy array, the .size() returns an int, which is causing you the problem. Check in the following code the difference:
import numpy as np
from PIL import Image
# NumPy
img = np.zeros((30, 30))
print(img.size) # output: 900
# PIL
pil_img = Image.fromarray(img)
print(pil_img.size) # output: (30, 30)
| https://stackoverflow.com/questions/61146458/ |
Fine-tuning Resnet using pre-convoluted features | As we know that convolution layers are expensive to calculate , I would like to compute the output of the convolution layers once and use them to train the fully connected layer of my Resnet, in order to speed up the process.
In the case of a VGG model, we can compute the output of the first convolutional part as follows
x = model_vgg.features(inputs)
But how can I do to extract features from a Resnet?
Thanks in advance
| I guess you can try hacking through the net. I'll use resnet18 as an example:
import torch
from torch import nn
from torchvision.models import resnet18
net = resnet18(pretrained=False)
print(net)
You'll see something like:
....
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
(fc): Linear(in_features=512, out_features=1000, bias=True)
Let's store the Linear layer somewhere, and in its place, put a dummy layer. Then the output of the whole net is actually the output of the conv layers.
x = torch.randn(4,3,32,32) # dummy input of batch size 4 and 32x32 rgb images
out = net(x)
print(out.shape)
>>> 4, 1000 # batch size 4, 1000 default class predictions
store_fc = net.fc # Save the actual Linear layer for later
net.fc = nn.Identity() # Add a layer which actually does nothing
out = net(x)
print(out.shape)
>>> 4, 512 # batch size 4, 512 features that are the input to the actual fc layer.
| https://stackoverflow.com/questions/61147354/ |
PyTorch's Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same but my data has been pushed to GPU | I receive the error:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same
yet I made sure to send my data as well as my model on the GPU. Anyone can help ?
My code is:
net.cuda()
'''
print('pyTorch style summay: ',net)
print('Keras style summary:\n')
summary(net,(2,128,128))
'''
criterion=nn.MSELoss()
#optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9)
learning_rate = 1e-4
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
print('\nLossFun=',str(criterion))
hf=h5py.File(fn,'r')
print(hf['trainingset'])
tr=np.array(hf['trainingset'])
trtg=np.array(hf['targetsTraining'])
hf.close()
tr = np.moveaxis(tr,3,2)
trtg = np.moveaxis(trtg,3,2)
tr = torch.FloatTensor(tr)
trtg = torch.FloatTensor(trtg)
tr.cuda()
trtg.cuda()
batch_size=16
epochs=2
# run the main training loop
for epoch in range(epochs):
for batch_idx in range(batch_size):#batch_idx, (data, target) in enumerate(train_loader):
data = tr[batch_idx:batch_idx+batch_size-1,:,:,:]
target = trtg[batch_idx:batch_idx+batch_size-1,:,:,:]
data, target = Variable(data), Variable(target)
# resize data from (batch_size, 1, 28, 28) to (batch_size, 28*28)
#data = data.view(-1, 28*28)
optimizer.zero_grad()
net_out = net(data)
loss = criterion(net_out, target)
loss.backward()
optimizer.step()
batch_idx += 1
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch, batch_idx * len(data), len(train_loader.dataset),100. * batch_idx / len(train_loader), loss.data[0]))
I don't understand why tr.cuda() and trtg.cuda() is not enough! How can I force them to go to cuda?
| Tensor.cuda() doesn't actually change the tensor in place. It creates a copy of the tensor on the GPU and returns the copy. With this in mind you probably want
tr = tr.cuda()
trtg = trtg.cuda()
This is actually different than nn.Module.cuda() which is performed in-place and actually modifies the registered parameters and buffers of the module.
| https://stackoverflow.com/questions/61149598/ |
How to set the next n elements of a Numpy / PyTorch array to some value? | If I have a variable side_inputs, with .shape of [48, 161]. I want to set the last n values to some other value.
My other variable, side_input has a .shape of [45, 161].
I want to set the last 45 elements of side_inputs to side_input with:
side_inputs[:45,:] = side_input
But I get an error:
RuntimeError: The expanded size of the tensor (48) must match the existing size (45) at non-singleton dimension 0. Target sizes: [48, 161]. Tensor sizes: [45, 161]
| side_inputs[:-45, :] = side_input
| https://stackoverflow.com/questions/61150980/ |
Understanding cdist() function | What does this new_cdist() function actually do? More specifically:
Why is there a sqrt() operation when the AdderNet paper does not use it in its backward propagation equation?
How is needs_input_grad[] used?
def new_cdist(p, eta):
class cdist(torch.autograd.Function):
@staticmethod
def forward(ctx, W, X):
ctx.save_for_backward(W, X)
out = -torch.cdist(W, X, p)
return out
@staticmethod
def backward(ctx, grad_output):
W, X = ctx.saved_tensors
grad_W = grad_X = None
if ctx.needs_input_grad[0]:
_temp1 = torch.unsqueeze(X, 2).expand(X.shape[0], X.shape[1], W.shape[0]).permute(1, 0, 2)
_temp2 = torch.unsqueeze(W.transpose(0, 1), 1)
_temp = torch.cdist(_temp1, _temp2, p).squeeze().transpose(0, 1)
grad_W = torch.matmul(grad_output, _temp)
# print('before norm: ', torch.norm(grad_W))
grad_W = eta * np.sqrt(grad_W.numel()) / torch.norm(grad_W) * grad_W
print('after norm: ', torch.norm(grad_W))
if ctx.needs_input_grad[1]:
_temp1 = torch.unsqueeze(W, 2).expand(W.shape[0], W.shape[1], X.shape[0]).permute(1, 0, 2)
_temp2 = torch.unsqueeze(X.transpose(0, 1), 1)
_temp = torch.cdist(_temp1, _temp2, p).squeeze().transpose(0, 1)
_temp = torch.nn.functional.hardtanh(_temp, min_val=-1., max_val=1.)
grad_X = torch.matmul(grad_output.transpose(0, 1), _temp)
return grad_W, grad_X
return cdist().apply
I mean that it seems to be related to a new type of back-propagation equation and adaptive learning rate.
| Actually, the AdderNet paper does use the sqrt. It is in the adaptive learning rate computation (Algorithm 1, line 6). More specifically, you can see that Eq. 12:
is what is written in this line:
# alpha_l = eta * np.sqrt(grad_W.numel()) / torch.norm(grad_W)
grad_W = eta * np.sqrt(grad_W.numel()) / torch.norm(grad_W) * grad_W
and the sqrt() comes from Eq. 13:
where k denotes the number of elements in F_l to average the l2-norm, and η is a hyper-parameter to control the learning rate of adder filters.
About your second question: needs_input_grad is just a variable to check if the inputs really require gradients. [0] in this case would refer to W, and [1] to X. You can read more about it here.
| https://stackoverflow.com/questions/61154470/ |
PyTorch torch.max over multiple dimensions | Have tensor like :x.shape = [3, 2, 2].
import torch
x = torch.tensor([
[[-0.3000, -0.2926],[-0.2705, -0.2632]],
[[-0.1821, -0.1747],[-0.1526, -0.1453]],
[[-0.0642, -0.0568],[-0.0347, -0.0274]]
])
I need to take .max() over the 2nd and 3rd dimensions. I expect some like this [-0.2632, -0.1453, -0.0274] as output. I tried to use: x.max(dim=(1,2)), but this causes an error.
| Now, you can do this. The PR was merged (Aug 28 2020) and it is now available in the nightly release.
Simply use torch.amax():
import torch
x = torch.tensor([
[[-0.3000, -0.2926],[-0.2705, -0.2632]],
[[-0.1821, -0.1747],[-0.1526, -0.1453]],
[[-0.0642, -0.0568],[-0.0347, -0.0274]]
])
print(torch.amax(x, dim=(1, 2)))
# Output:
# >>> tensor([-0.2632, -0.1453, -0.0274])
Original Answer
As of today (April 11, 2020), there is no way to do .min() or .max() over multiple dimensions in PyTorch. There is an open issue about it that you can follow and see if it ever gets implemented. A workaround in your case would be:
import torch
x = torch.tensor([
[[-0.3000, -0.2926],[-0.2705, -0.2632]],
[[-0.1821, -0.1747],[-0.1526, -0.1453]],
[[-0.0642, -0.0568],[-0.0347, -0.0274]]
])
print(x.view(x.size(0), -1).max(dim=-1))
# output:
# >>> values=tensor([-0.2632, -0.1453, -0.0274]),
# >>> indices=tensor([3, 3, 3]))
So, if you need only the values: x.view(x.size(0), -1).max(dim=-1).values.
If x is not a contiguous tensor, then .view() will fail. In this case, you should use .reshape() instead.
Update August 26, 2020
This feature is being implemented in PR#43092 and the functions will be called amin and amax. They will return only the values. This is probably being merged soon, so you might be able to access these functions on the nightly build by the time you're reading this :) Have fun.
| https://stackoverflow.com/questions/61156894/ |
Subsets and Splits