instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
Understanding content of pretrained model | from torchvision import models
model = models.vgg16(pretrained=True).features
for i, module in enumerate(model.modules()):
print('-' * 60)
print(type(module))
print(module)
What is 'module' in model.modules() (modules() Returns an iterator over all modules in the network.)? Why torch.nn.modules.container.Sequential is stored along with single layers?
Output:
------------------------------------------------------------
<class 'torch.nn.modules.container.Sequential'>
Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace=True)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace=True)
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace=True)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace=True)
(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace=True)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace=True)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace=True)
(16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(18): ReLU(inplace=True)
(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace=True)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace=True)
(23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(25): ReLU(inplace=True)
(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(27): ReLU(inplace=True)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace=True)
(30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.pooling.MaxPool2d'>
MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.pooling.MaxPool2d'>
MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.pooling.MaxPool2d'>
MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.pooling.MaxPool2d'>
MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.conv.Conv2d'>
Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
------------------------------------------------------------
<class 'torch.nn.modules.activation.ReLU'>
ReLU(inplace=True)
------------------------------------------------------------
<class 'torch.nn.modules.pooling.MaxPool2d'>
MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
| nn.Module.modules will return all modules contained inside the model recursively, that includes parent submodules and children submodules that they may have of their own. You can instead use nn.Module.children to get the direct child submodules:
for child in module.children():
print(child)
If you want to investigate with recursion you could do:
def print_children(module, i=0):
if len(list(module.modules())) == 1:
return print(' '*i, module)
for child in module.children():
print_children(child, i+2)
| https://stackoverflow.com/questions/69376573/ |
How to delete / replace layer in existing model? |
How to delete some layers from pretrained network (for example remove single ReLU activation layer)?
How to replace some layers by type in pretrained network (for example replace MaxPool2d with AvrPool)?
| Assuming you know the structure of your model, you can:
>>> model = torchvision.models(pretrained=True)
Select a submodule and interact with it as you would with any other nn.Module. This will depend on your model's implementation. For example, submodule are often accessible via attributes (e.g. model.features), however this is not always the case, for instance nn.Sequential use indices: model.features[18] to select one of the relu activations. Also do note: not all layers are registered inside the nn.Module, non-parametric functions such as most activation functions can be applied via the functional approach directly in the forward of the module.
For a given nn.Module m you can extract its layer name by using type(m).__name__. A canonical approach is to filter the layers of model.modules and only keep the max pool layers, then replace those with average pool layers:
>>> maxpools = [k for k, m in model.named_modules()
... if type(m).__name__ == 'MaxPool2d']
['features.4', 'features.9', 'features.16', 'features.23', 'features.30']
We can extract the parent module name for each of those layers:
>>> maxpools = [k.split('.') for k, m in model.named_modules()
... if type(m).__name__ == 'MaxPool2d']
[['features', '4'],
['features', '9'],
['features', '16'],
['features', '23'],
['features', '30']]
Here they all come from the same parent module model.features. Finally, we can fetch the layer reference in order to overwrite their value:
>>> for *parent, k in maxpools:
... model.get_submodule('.'.join(parent))[int(k)] = nn.AvgPool2d(2,2)
Resulting in:
VGG(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace=True)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace=True)
(4): AvgPool2d(kernel_size=2, stride=2, padding=0)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace=True)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace=True)
(9): AvgPool2d(kernel_size=2, stride=2, padding=0)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace=True)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace=True)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace=True)
(16): AvgPool2d(kernel_size=2, stride=2, padding=0)
(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(18): ReLU(inplace=True)
(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace=True)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace=True)
(23): AvgPool2d(kernel_size=2, stride=2, padding=0)
(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(25): ReLU(inplace=True)
(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(27): ReLU(inplace=True)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace=True)
(30): AvgPool2d(kernel_size=2, stride=2, padding=0)
)
(avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
(classifier): Sequential(
(0): Linear(in_features=25088, out_features=4096, bias=True)
(1): ReLU(inplace=True)
(2): Dropout(p=0.5, inplace=False)
(3): Linear(in_features=4096, out_features=4096, bias=True)
(4): ReLU(inplace=True)
(5): Dropout(p=0.5, inplace=False)
(6): Linear(in_features=4096, out_features=1000, bias=True)
)
)
| https://stackoverflow.com/questions/69376651/ |
What is default download path for Pytorch models on MacOS? | What is default download path for Pytorch models (from torchvision) on MacOS?
I can't see anything in home dir ls -la ~/ | grep torch.
| You should have the path it displayed when you first download the pre-trained weights for that model, something like this:
| https://stackoverflow.com/questions/69377017/ |
create Pytorch dataset without downloading | Quite new here, hope this isn't to much of simple question.
I am trying to get into deep learning, starting with pytorch.
Thing is, all tutorials I see use downloading in order to build a data set for training and testing. Unfortunately, I am restricted with my internet connection, meaning I can't download directly from the web.
What I can do is download files and transfer them into my computer.
So my question is - in order to use a previously downloaded dataset in pytorch:
Where should I store it?
How do I create a dataset once I have the files on my computer?
If any other information seems important to you I'll be glad to hear, I'm a serious newbie..
Thank you very much!
| Not sure which dataset you are asking for. Since you mentioned the "tutorials", I am guessing that you just want to work with a dataset that comes with some library in PyTorch ecosystem (e.g. torchvision).
Dataset classess in PyTorch ecosystem have a "root" argument in their constrcutors.
mnist = MNIST(root='/some/path', download=True)
You can simply download it on some machine with internet, and transfer the contents of the folder /some/path to your machine at /my/machine/path. And simply point to it and turn off the download
# on your machine without internet
mnist = MNIST(root='/my/machine/path', download=False)
This should work.
| https://stackoverflow.com/questions/69379111/ |
Why is my Transformer implementation losing to a BiLSTM? | I am dealing with a sequence tagging problem and I am using a single Transformer Encoder to obtain logits from each element of the sequence. Having experimented both with Transformer and BiLSTM it looks like in my case BiLSTM is working better, so I was wondering if maybe it is because my Transformer implementation has some problem... Below is my implementation of the Transformer Encoder and related functions for creating padding mask and positional embeddings:
def create_mask(src, lengths):
"""Create a mask hiding future tokens
Parameters:
src (tensor): the source tensor having shape [batch_size, number_of_steps, features_dimensions]
length (list): a list of integers representing the length (i.e. number_of_steps) of each sample in the batch."""
mask = []
max_len = src.shape[1]
for index, i in enumerate(src):
# The mask consists in tensors having false at the step number that doesn't need to be hidden and true otherwise
mask.append([False if (i+1)>lengths[index] else True for i in range(max_len)])
return torch.tensor(mask)
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000, device = 'cpu'):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.device = device
position = torch.arange(max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
pe = torch.zeros(1, max_len, d_model)
pe[0, :, 0::2] = torch.sin(position * div_term)
pe[0, :, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:, :x.size(1), :].to(self.device)
return self.dropout(x)
class Transformer(nn.Module):
"""Class implementing transformer ecnoder, partially based on
https://pytorch.org/tutorials/beginner/transformer_tutorial.html"""
def __init__(self, in_dim, h_dim, n_heads, n_layers, dropout=0.2, drop_out = 0.0, batch_first = True, device = 'cpu', positional_encoding = True):
super(Transformer, self).__init__()
self.model_type = 'Transformer'
self.pos_encoder = PositionalEncoding(in_dim, dropout, device = device)
encoder_layers = nn.TransformerEncoderLayer(in_dim, n_heads, h_dim, dropout)
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, n_layers, norm=nn.LayerNorm(in_dim))
self.in_dim = in_dim
self.drop_out = drop_out
self.positional_encoding = positional_encoding
def forward(self, src, mask = None, line_len=None):
src = src * math.sqrt(self.in_dim)
if self.positional_encoding:
src = self.pos_encoder(src)
if line_len is not None and mask is None:
mask = create_mask(src, line_len)
else:
mask = None
output = self.transformer_encoder(src, src_key_padding_mask = mask)
if self.drop_out:
output = F.dropout(output, p = self.drop_out)
return src, output
As it can be seen, the above network outputs the hidden states and then I pass them into an additional linear layer and train with a CrossEntropy loss over two classes and Adam optimizer. I have tried multiple combinations of hyperparameters but the BiLSTM still performs better. Can anyone spot anything off in my Transformer or suggest why I experience such a counterintuitive result?
| This may be surprising, but Transformers don't always beat LSTMs. For example, Language Models with Transformers states:
Transformer architectures are suboptimal for language model itself. Neither self-attention nor the positional encoding in the Transformer is able to efficiently incorporate the word-level sequential context crucial to language modeling.
If you run the Transformer tutorial code itself (on which your code is based), you'll also see LSTM do better there. See this thread on stats.SE for more discussion on this topic (disclaimer: both the question and the answer there are mine)
| https://stackoverflow.com/questions/69380237/ |
Multi-label classification return more than 1 class in each label | How to train a Multi-label classification model when each label should return more than 1 class?
Example:
Image classification have 2 label: style with 4 classes and layout with 5 classes.
An image in list should return 2 style and 3 layout like [1 0 1 0] [1 1 0 0 1]
My sample net:
class MyModel(nn.Module):
def __init__(self, n__classes=32):
super().__init__()
self.base_model = models.resnet50(pretrained=True).to(device)
last_channel = self.base_model.fc.in_features
self.base_model.fc = nn.Sequential()
self.layout = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(last_channel, n_classes_layout),
nn.Sigmoid()
)
self.style = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(last_channel, n_classes_style),
nn.Sigmoid()
)
def forward(self, x):
base = self.base_model(x)
return self.layout(base), self.style(base)
def loss_fn(outputs, targets):
o1, o2 = outputs
t1, t2 = targets
| I am not sure what you referring label to but it seems you have a multi output model predicting on one hand style, and on the other layout. So I am assuming you are dealing with a multi-task network with two "independent" outputs which are supervised separately with two-loss terms.
Consider one of those two: you can consider this multi-label classification task as outputting n values each one estimating the probability that the corresponding label is present in the input. In your first task, you have four classes, on the second task, you have five.
Unlike a single-label classification task, here you wish to output one activation per label: you can use a sigmoid activation per logit. Then apply the Binary Cross Entropy loss on each of those outputs. In PyTorch, you can use BCELoss, which handles multi-dimensional tensors. In practice you could concatenate the two outputs from the two tasks, do the same with the target labels and call the criterion once.
| https://stackoverflow.com/questions/69381429/ |
Pytorch: "KeyError: Caught KeyError in DataLoader worker process 0." | Problem Description:
I am trying to load image data using Pytorch custom dataset. I did a little dive deep and found that my images set consist of 2 types of shape (512,512,3) and (1024,1024) . My assumption is, because of the above reason, it is throwing the below error.
Note: The code is able to read some of the images but, it is throwing the below error message for few of them. This was the reason to do a little EDA on the image data and found that there were 2 different shapes of images in the dataset.
Q1. How to preprocess such image data for training?
Q2. Is there any other reasons why I might be seeing the below error message?
Error message:
KeyError Traceback (most recent call last)
<ipython-input-163-aa3385de8026> in <module>
----> 1 train_features, train_labels = next(iter(train_dataloader))
2 print(f"Feature batch shape: {train_features.size()}")
3 print(f"Labels batch shape: {train_labels.size()}")
4 img = train_features[0].squeeze()
5 label = train_labels[0]
~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/utils /data/dataloader.py in __next__(self)
519 if self._sampler_iter is None:
520 self._reset()
521 data = self._next_data()
522 self._num_yielded += 1
523 if self._dataset_kind == _DatasetKind.Iterable and \
~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/utils/data/dataloader.py in _next_data(self)
1201 else:
1202 del self._task_info[idx]
1203 return self._process_data(data)
1204
1205 def _try_put_index(self):
~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/utils/data/dataloader.py in _process_data(self, data)
1227 self._try_put_index()
1228 if isinstance(data, ExceptionWrapper):
1229 data.reraise()
1230 return data
1231
~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/_utils.py in reraise(self)
423 # have message field
424 raise self.exc_type(message=msg)
425 raise self.exc_type(msg)
426
427
KeyError: Caught KeyError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pandas /core/indexes/base.py", line 2898, in get_loc
return self._engine.get_loc(casted_key)
File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1032, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1039, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 16481
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 287, in _worker_loop
data = fetcher.fetch(index)
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
data = [self.dataset[idx] for idx in possibly_batched_index]
File "<ipython-input-161-f38b78d77dcb>", line 19, in __getitem__
img_path =os.path.join(self.img_dir,self.image_ids[idx])
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pandas/core/series.py", line 882, in __getitem__
return self._get_value(key)
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pandas/core/series.py", line 990, in _get_value
loc = self.index.get_loc(label)
File "/home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2900, in get_loc
raise KeyError(key) from err
KeyError: 16481
Code:
from torchvision.io import read_image
import torch
from torchvision import transforms
from sklearn.model_selection import train_test_split
from torch.utils.data import Dataset
class CustomImageDataset(Dataset):
# init
def __init__(self,dataset,transforms=None,target_transforms=None):
#self.train_data = pd.read_csv("Data/train_data.csv")
self.image_ids = dataset.image_id
self.image_labels = dataset.label
self.img_dir = 'Data/images'
self.transforms = transforms
self.target_transforms = target_transforms
# len
def __len__(self):
return len(self.image_ids)
# getitem
def __getitem__(self,idx):
# image path
img_path =os.path.join(self.img_dir,self.image_ids[idx])
# image
image = read_image(img_path)
label = self.image_labels[idx]
# transform image
if self.transforms:
image = self.transforms(image)
# transform target
if self.target_transforms:
label = self.target_transforms(label)
return image, label
Code: train_data is the pandas object of the csv file which has the image id, labesl information.
from sklearn.model_selection import train_test_split
X_train, X_test = train_test_split(train_data, test_size=0.1, random_state=42)
train_df = CustomImageDataset(X_train)
train_dataloader = torch.utils.data.DataLoader(
train_df,
batch_size=64,
num_workers=1,
shuffle=True,
)
| found the issue with the code.
Pytorch Custom Dataloader function "getitem" uses idx to retrieve data and my guess is, it know the range of idx from len function, ex: 0, till len(rows in dataset).
In my case, I already had a panda dataset (train_data) with idx as one of the column. When I randomly split it into X_train and X_test, few of the data rows were moved to X_test along with the idx.
Now, when I send X_train to the custom dataloader, it is trying to get row's image_id with an idx and that idx just happens to be in X_test dataset. This lead to error as keyerror: 16481 i.e row with idx=16481 is not present in the X_train dataset. It was moved to X_test during split.
phew...
| https://stackoverflow.com/questions/69393214/ |
Equivalent of torch EmbeddingBag | Torch claim that EmbeddingBag with mode="sum" is equivalent to Embedding followed by torch.sum(dim=1), but how can I implement it in detail? Let's say we have
"EE = nn.EmbeddingBag(n, m, mode="sum", sparse=True)", how can we replace the "nn.EmbeddingBag" by "nn.Embeeding" and "torch.sum" equivalently? Many thanks
| Consider the following example where all four implementations yield the same result:
nn.EmbeddingBag:
>>> embedding_sum = nn.EmbeddingBag(10, 3, mode='sum')
>>> embedding_sum(input, torch.zeros(1).long())
nn.functional.embedding_bag:
>>> F.embedding_bag(input, embedding_sum.weight, torch.zeros(1).long(), mode='sum')
nn.Embedding:
>>> embedding = nn.Embedding(10, 3)
>>> embedding.weight = embedding_sum.weight
>>> embedding(input).sum(0)
nn.functional.embedding:
>>> F.embedding(input, embedding_sum.weight).sum(0)
| https://stackoverflow.com/questions/69394994/ |
Dataloader throwing error TypeError: new(): data must be a sequence (got map) | I am trying to implement bidirectional LSTM on time series data. The main file calls the dataloader to load the data for the model.
Main.py
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import numpy as np
import time
import utils
import models
from models import rits_i
from models import brits_i
from models import rits
from models import brits
import argparse
import data_loader
import pandas as pd
import ujson as json
from sklearn import metrics
from ipdb import set_trace
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type = int, default = 1000)
parser.add_argument('--batch_size', type = int, default = 32)
parser.add_argument('--model', type = str)
args = parser.parse_args()
def train(model):
optimizer = optim.Adam(model.parameters(), lr = 1e-3)
data_iter = data_loader.get_loader(batch_size = args.batch_size)
for epoch in range(args.epochs):
model.train()
run_loss = 0.0
for idx, data in enumerate(data_iter):
data = utils.to_var(data)
ret = model.run_on_batch(data, optimizer)
run_loss += ret['loss'].data[0]
print('\r Progress epoch {}, {:.2f}%, average loss {}'.format(epoch, (idx + 1) * 100.0 / len(data_iter), run_loss / (idx + 1.0)),)
if epoch % 1 == 0:
evaluate(model, data_iter)
def evaluate(model, val_iter):
model.eval()
labels = []
preds = []
evals = []
imputations = []
for idx, data in enumerate(val_iter):
data = utils.to_var(data)
ret = model.run_on_batch(data, None)
pred = ret['predictions'].data.cpu().numpy()
label = ret['labels'].data.cpu().numpy()
is_train = ret['is_train'].data.cpu().numpy()
eval_masks = ret['eval_masks'].data.cpu().numpy()
eval_ = ret['evals'].data.cpu().numpy()
imputation = ret['imputations'].data.cpu().numpy()
evals += eval_[np.where(eval_masks == 1)].tolist()
imputations += imputation[np.where(eval_masks == 1)].tolist()
# collect test label & prediction
pred = pred[np.where(is_train == 0)]
label = label[np.where(is_train == 0)]
labels += label.tolist()
preds += pred.tolist()
labels = np.asarray(labels).astype('int32')
preds = np.asarray(preds)
print('AUC {}'.format(metrics.roc_auc_score(labels, preds)))
evals = np.asarray(evals)
imputations = np.asarray(imputations)
print('MAE', np.abs(evals - imputations).mean())
print('MRE', np.abs(evals - imputations).sum() / np.abs(evals).sum())
def run():
model = getattr(models, args.model).Model()
if torch.cuda.is_available():
model = model.cuda()
train(model)
if __name__ == '__main__':
run()
data_loader.py
import os
import time
import ujson as json
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
class MySet(Dataset):
def __init__(self):
super(MySet, self).__init__()
self.content = open('./json/json').readlines()
indices = np.arange(len(self.content))
val_indices = np.random.choice(indices, len(self.content) // 5)
self.val_indices = set(val_indices.tolist())
def __len__(self):
return len(self.content)
def __getitem__(self, idx):
rec = json.loads(self.content[idx])
if idx in self.val_indices:
rec['is_train'] = 0
else:
rec['is_train'] = 1
return rec
def collate_fn(recs):
forward = map(lambda x: x['forward'], recs)
backward = map(lambda x: x['backward'], recs)
def to_tensor_dict(recs):
values = torch.FloatTensor(map(lambda r: map(lambda x: x['values'], r), recs))
masks = torch.FloatTensor(map(lambda r: map(lambda x: x['masks'], r), recs))
deltas = torch.FloatTensor(map(lambda r: map(lambda x: x['deltas'], r), recs))
forwards = torch.FloatTensor(map(lambda r: map(lambda x: x['forwards'], r), recs))
evals = torch.FloatTensor(map(lambda r: map(lambda x: x['evals'], r), recs))
eval_masks = torch.FloatTensor(map(lambda r: map(lambda x: x['eval_masks'], r), recs))
return {'values': values, 'forwards': forwards, 'masks': masks, 'deltas': deltas, 'evals': evals, 'eval_masks': eval_masks}
ret_dict = {'forward': to_tensor_dict(forward), 'backward': to_tensor_dict(backward)}
ret_dict['labels'] = torch.FloatTensor(map(lambda x: x['label'], recs))
ret_dict['is_train'] = torch.FloatTensor(map(lambda x: x['is_train'], recs))
return ret_dict
def get_loader(batch_size = 64, shuffle = True):
data_set = MySet()
data_iter = DataLoader(dataset = data_set, \
batch_size = batch_size, \
num_workers = 4, \
shuffle = shuffle, \
pin_memory = True, \
collate_fn = collate_fn
)
return data_iter
but I am unable to resolve the error TypeError: new(): data must be a sequence (got map)
Following message is being received in the terminal:
C:\Users\ankit\anaconda3\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 61292 --file C:/Users/ankit/PycharmProjects/BRITS/main.py --epochs 1000 --batch_size 32 --model brits
Connected to pydev debugger (build 212.4746.96)
Traceback (most recent call last):
File "C:\Users\ankit\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 521, in __next__
data = self._next_data()
File "C:\Users\ankit\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 1203, in _next_data
return self._process_data(data)
File "C:\Users\ankit\anaconda3\lib\site-packages\torch\utils\data\dataloader.py", line 1229, in _process_data
data.reraise()
File "C:\Users\ankit\anaconda3\lib\site-packages\torch\_utils.py", line 425, in reraise
raise self.exc_type(msg)
TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "C:\Users\ankit\anaconda3\lib\site-packages\torch\utils\data\_utils\worker.py", line 287, in _worker_loop
data = fetcher.fetch(index)
File "C:\Users\ankit\anaconda3\lib\site-packages\torch\utils\data\_utils\fetch.py", line 47, in fetch
return self.collate_fn(data)
File "C:\Users\ankit\PycharmProjects\BRITS\data_loader.py", line 48, in collate_fn
ret_dict = {'forward': to_tensor_dict(forward), 'backward': to_tensor_dict(backward)}
File "C:\Users\ankit\PycharmProjects\BRITS\data_loader.py", line 38, in to_tensor_dict
values = torch.FloatTensor(map(lambda r: map(lambda x: x['values'], r), recs))
TypeError: new(): data must be a sequence (got map)
The input data is in the jason format (below is the partial data):
{"forward":[{"evals":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.9056552797,0.0,0.0,0.0,-0.6644796629,0.0,0.0,0.0,0.0,0.0,0.2233221525,0.9872348884,1.5032897407,0.0,0.0,0.0,0.0,-0.1197213235,0.0,0.0,-1.2017103673,0.0,0.0,2.16039189,0.0],"deltas":[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],"forwards":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.9056552797,0.0,0.0,0.0,-0.6644796629,0.0,0.0,0.0,0.0,0.0,0.2233221525,0.9872348884,1.5032897407,0.0,0.0,0.0,0.0,-0.1197213235,0.0,0.0,-1.2017103673,0.0,0.0,2.16039189,0.0],"masks":[0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,1,0,0,1,0],"values":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.9056552797,0.0,0.0,0.0,-0.6644796629,0.0,0.0,0.0,0.0,0.0,0.2233221525,0.9872348884,1.5032897407,0.0,0.0,0.0,0.0,-0.1197213235,0.0,0.0,-1.2017103673,0.0,0.0,2.16039189,0.0],"eval_masks":[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]},{"evals":[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,-1.5117099666,0.0,0.0,0.0,0.0,0.0,0.2569139277,0.6703649195,0.8156657086,0.0,0.0,0.0,0.0,-0.3034796866,0.0,0.0,0.0,0.0,0.0,-0.5174302535,0.0],"deltas":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0],"forwards":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.9056552797,0.0,0.0,0.0,-1.5117099666,0.0,0.0,0.0,0.0,0.0,0.2569139277,0.6703649195,0.8156657086,0.0,0.0,0.0,0.0,-0.3034796866,0.0,0.0,-1.2017103673,0.0,0.0,-0.5174302535,0.0],"masks":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0,1,0,0,0,0,0,1,0],"values":[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,-1.5117099666,0.0,0.0,0.0,0.0,0.0,0.2569139277,0.6703649195,0.8156657086,0.0,0.0,0.0,0.0,-0.3034796866,0.0,0.0,0.0,0.0,0.0,-0.5174302535,0.0],"eval_masks":[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]},{"evals":[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,-1.3987459261,0.0,0.0,0.0,0.0,0.0,-0.4149215779,-0.0992249514,0.1738832786,0.0,0.0,0.0,0.0,-0.1197213235,0.0,0.0,0.0,0.0,0.0,0.3156699689,0.0],"deltas":[2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,2.0,0.0,2.0,2.0,2.0,2.0,2.0,0.0,0.0,0.0,2.0,2.0,2.0,2.0,0.0,2.0,2.0,2.0,2.0,2.0,0.0,2.0]
I researched and got that it might be issue with python 3 but I ran on python 2 but still facing the same issue. Please help me resolve the issue.
| I haven't looked or tried running all of your code, but at a glance, this line is clearly wrong
torch.FloatTensor(map(lambda r: map(lambda x: x['values'], r), recs))
In python3, map() returns a map object, not a list. FloatTensor(..) expects the later, i.e. a list. Just cast all your map objects with list()
torch.FloatTensor(list(map(lambda r: map(lambda x: x['values'], r), recs)))
| https://stackoverflow.com/questions/69395367/ |
How to select half precision (BFLOAT16 vs FLOAT16) for your trained model? | how will you decide what precision works best for your inference model? Both BF16 and F16 takes two bytes but they use different number of bits for fraction and exponent.
Range will be different but I am trying to understand why one chose one over other.
Thank you
|--------+------+----------+----------|
| Format | Bits | Exponent | Fraction |
|--------+------+----------+----------|
| FP32 | 32 | 8 | 23 |
| FP16 | 16 | 5 | 10 |
| BF16 | 16 | 8 | 7 |
|--------+------+----------+----------|
Range
bfloat16: ~1.18e-38 β¦ ~3.40e38 with 3 significant decimal digits.
float16: ~5.96eβ8 (6.10eβ5) β¦ 65504 with 4 significant decimal digits precision.
| bfloat16 is generally easier to use, because it works as a drop-in replacement for float32. If your code doesn't create nan/inf numbers or turn a non-0 into a 0 with float32, then it shouldn't do it with bfloat16 either, roughly speaking. So, if your hardware supports it, I'd pick that.
Check out AMP if you choose float16.
| https://stackoverflow.com/questions/69399917/ |
Functionally is torch.multinomial the same as torch.distributions.categorical.Categorical? | For example, if I provide a probability array of [0.5, 0.5], both functions will sample the index [0,1] with equal probability?
| Yes:
[torch.distributions.categorical.Categorical()] is equivalent to the distribution that torch.multinomial() samples from.
https://pytorch.org/docs/stable/distributions.html#Categorical
| https://stackoverflow.com/questions/69403103/ |
what is the meaning of 'per-layer learning rate' in Fast R-CNN paper? | I'm reading a paper about Fast-RCNN model.
In the paper section 2.3 part of 'SGD hyper-parameters', it said that All layers use a per-layer learning rate of 1 for weights and 2 for biases and a global learning rate of 0.001
Is 'per-layer learning rate' same as 'layer-specific learning rate' that give different learning rate by layers? If so, I can't understand how they('per-layer learning rate' and 'global learning rate') can be apply at the same time?
I found the example of 'layer-specific learning rate' in pytorch.
optim.SGD([
{'params': model.some_layers.parameters()},
{'params': model.some_layers.parameters(), 'lr': 1}
], lr=1e-3, momentum=0.9)
According to paper, Is this the correct approach?
Sorry for may English
| The per-layer terminology in that paper is slightly ambiguous. They aren't referring to the layer-specific learning rates.
All layers use a per-layer learning rate of 1 for weights and 2 for biases and a global learning rate of 0.001.
The concerned statement is w.r.t. Caffe framework in which Fast R-CNN was originally written (github link).
They meant that they're setting the learning rate multiplier of weights and biases to be 1 and 2 respectively.
Check any prototxt file in the repo e.g. CaffeNet/train.prototxt.
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
Thus, the effective learning rate is going to be base_lr*lr_mult, and here, the base learning rate is 0.001, which is defined in solver.prototxt.
| https://stackoverflow.com/questions/69406476/ |
How to use SciBERT in the best manner? | I'm trying to use BERT models to do text classification. As the text is about scientific texts, I intend to use the SicBERT pre-trained model: https://github.com/allenai/scibert
I have faced several limitations which I want to know if there is any solutions for them:
When I want to do tokenization and batching, it only allows me to use max_length of <=512. Is there any way to use more tokens. Doen't this limitation of 512 mean that I am actually not using all the text information during training? Any solution to use all the text?
I have tried to use this pretrained library with other models such as DeBERTa or RoBERTa. But it doesn't let me. I has only worked with BERT. Is there anyway I can do that?
I know this is a general question, but any suggestion that I can improve my fine tuning (from data to hyper parameter, etc)? Currently, I'm getting ~75% accuracy. Thanks
Codes:
tokenizer = BertTokenizer.from_pretrained('allenai/scibert_scivocab_uncased')
encoded_data_train = tokenizer.batch_encode_plus(
df_train.text.values,
add_special_tokens=True,
return_attention_mask=True,
padding=True,
max_length=256
)
input_ids_train = encoded_data_train['input_ids']
attention_masks_train = encoded_data_train['attention_mask']
labels_train = torch.tensor(df_train.label.values)
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataloader_train = DataLoader(dataset_train,
sampler=RandomSampler(dataset_train),
batch_size=batch_size)
model = BertForSequenceClassification.from_pretrained('allenai/scibert_scivocab_uncased',
num_labels=len(labels),
output_attentions=False,
output_hidden_states=False)
epochs = 1
optimizer = AdamW(model.parameters(), lr=1e-5, eps=1e-8)
scheduler = get_linear_schedule_with_warmup(optimizer,
num_training_steps=len(dataloader_train)*epochs)
|
When I want to do tokenization and batching, it only allows me to use max_length of <=512. Is there any way to use more tokens. Doen't this limitation of 512 mean that I am actually not using all the text information during training? Any solution to use all the text?
Yes, you are not using the complete text. And this is one of the limitations of BERT and T5 models, which limit to using 512 and 1024 tokens resp. to the best of my knowledge.
I can suggest you to use Longformer or Bigbird or Reformer models, which can handle sequence lengths up to 16k, 4096, 64k tokens respectively. These are really good for processing longer texts like scientific documents.
I have tried to use this pretrained library with other models such as DeBERTa or RoBERTa. But it doesn't let me. I has only worked with BERT. Is there anyway I can do that?
SciBERT is actually a pre-trained BERT model.
See this issue for more details where they mention the feasibility of converting BERT to ROBERTa:
Since you're working with a BERT model that was pre-trained, you unfortunately won't be able to change the tokenizer now from a WordPiece (BERT) to a Byte-level BPE (RoBERTa).
I know this is a general question, but any suggestion that I can
improve my fine tuning (from data to hyper parameter, etc)? Currently,
I'm getting ~79% accuracy.
I would first try to tune the most important hyperparameter learning_rate. I would then explore different values for hyperparameters of AdamW optimizer and num_warmup_steps hyperparamter of the scheduler.
| https://stackoverflow.com/questions/69406937/ |
Performance with IPEX | I tried linear regression & gradient descent in PyTorch. (https://www.analyticsvidhya.com/blog/2021/08/linear-regression-and-gradient-descent-in-pytorch/)
I've imported Ipex with the following command:
import intel_pytorch_extension as ipex
How can I convert the model to ipex? And how can I check that the performance has improved? Any help here?
| After importing IPEX, use the below command while defining a model:
def model(X, IPEX=True):
return X @ w.t() + b
We have verified the code from the link you shared. You could replace model(X) with model(X, IPEX=True)
Performance with IPEX has improved drastically. Without IPEX, we could see some difference between Actual Target values & Model Predictions. Where as, with IPEX values has no difference.
| https://stackoverflow.com/questions/69408207/ |
Replicate softmax of pytorch | I am trying to implement the softmax function in pytorch, but cant get the output of my implementation to match the output of pytorch's implementation.
I am trying to do this because I would like to go on to implement a masked softmax that would not include certain indices in the sum for the denominator, and set the output for those masked indexes.
I would like to calculate this for a matrix where each row in the output sums to 1. My current implentation is :
def my_softmax(x):
exp = x.exp()
return exp / exp.sum(1, keepdim=True)
However the output isnt the same for my implementation and pytorch's:
>>> t = torch.randn(3, 2)
>>> t
tensor([[-1.1881, -0.1085],
[ 0.5825, 1.0719],
[-0.5309, -1.3774]])
>>> my_softmax(t)
tensor([[0.2536, 0.7464],
[0.3800, 0.6200],
[0.6998, 0.3002]])
>>> t.softmax(1)
tensor([[0.2536, 0.7464],
[0.3800, 0.6200],
[0.6998, 0.3002]])
>>> my_softmax(t) == t.softmax(1)
tensor([[False, True],
[False, False],
[ True, True]])
Why do these different implementations produce different results?
| This works
import torch
def my_softmax(x):
means = torch.mean(x, 1, keepdim=True)[0]
x_exp = torch.exp(x-means)
x_exp_sum = torch.sum(x_exp, 1, keepdim=True)
return x_exp/x_exp_sum
t = torch.randn(3, 2)
s1 = my_softmax(t)
s2 = t.softmax(1)
print(torch.allclose(s1, s2))
True
P.S. taken from discussion
https://discuss.pytorch.org/t/how-to-implement-the-exactly-same-softmax-as-f-softmax-by-pytorch/44263
| https://stackoverflow.com/questions/69417191/ |
StyleGan2 ADA PyTorch Output Image Resolution Assertion Error | I am trying to produce an image using StyleGan2.
Executing this cell:
!python train.py --gpus=1 --cfg=$config --metrics=None --outdir=./results --data=$dataset_path --snap=$snapshot_count --resume=$resume_from --augpipe=$augs --initstrength=$aug_strength --gamma=$gamma_value --mirror=$mirror_x --mirrory=False --nkimg=$train_count
outputs the following:
Output directory: ./results/00001-datasets-mirror-11gb-gpu-gamma50-bg-resumecustom
Training data: /content/datasets.zip
Training duration: 25000 kimg
Number of GPUs: 1
Number of images: 608
Image resolution: 600
Conditional model: False
Dataset x-flips: True
Creating output directory...
Launching processes...
Loading training set...
Num images: 1216
Image shape: [3, 600, 600]
Label shape: [0]
then gives me the assertion error down below:
assert img_resolution >= 4 and img_resolution & (img_resolution - 1) == 0
Assertion Error:
I checked the source of the error.
But to be fair I didn't understand it.
| I have found:
The issue is the input dimension of the image must be at least [3, 1024, 1024] mine was [3, 600, 600]
| https://stackoverflow.com/questions/69421650/ |
slice Pytorch tensors which are saved in a list | I have the following code segment to generate random samples. The generated samples is a list, where each entry of the list is a tensor. Each tensor has two elements. I would like to extract the first element from all tensors in the list; and extract the second element from all tensors in the list as well. How to perform this kind of tensor slice operation
import torch
import pyro.distributions as dist
num_samples = 250
# note that both covariance matrices are diagonal
mu1 = torch.tensor([0., 5.])
sig1 = torch.tensor([[2., 0.], [0., 3.]])
dist1 = dist.MultivariateNormal(mu1, sig1)
samples1 = [pyro.sample('samples1', dist1) for _ in range(num_samples)]
samples1
| I'd recommend torch.cat with a list comprehension:
col1 = torch.cat([t[0] for t in samples1])
col2 = torch.cat([t[1] for t in samples1])
Docs for torch.cat: https://pytorch.org/docs/stable/generated/torch.cat.html
ALTERNATIVELY
You could turn your list of 1D tensors into a single big 2D tensor using torch.stack, then do a normal slice:
samples1_t = torch.stack(samples1)
col1 = samples1_t[:, 0] # : means all rows
col2 = samples1_t[:, 1]
Docs for torch.stack: https://pytorch.org/docs/stable/generated/torch.stack.html
| https://stackoverflow.com/questions/69422219/ |
Get a 128 dim feature vector from a pretrained model without fine tuning in Pytorch | I need visual features from a set of images in order to have a kind of embedding of a input image. The dimension I need is 128.
I thought of removing the last layer of a pretrained model such as ResNet50, than replace the last fully connected layer with a flatten layer and do a forward pass for each image. The issue is that after the flatten layer ResNet50 gives you a 512 dim feature vector. If I add another fully connected layer with output dim of 128 I need to retrain and fine tuning the network since I'm adding new parameters.
Is there any way to get a 128 dim feature vector from the last layer of 512 dim feature vector without adding learnable parameters?
| You could apply a Principal Component Analysis (PCA) on your features retrieved from the pre-trained model to reduce the dimensionality to 128 components.
| https://stackoverflow.com/questions/69424452/ |
PyTorch attach extra connection when building model | I have the following Resnet prototype on Pytorch:
Resnet_Classifier(
(activation): ReLU()
(model): Sequential(
(0): Res_Block(
(mod): Sequential(
(0): Conv1d(1, 200, kernel_size=(5,), stride=(1,), padding=same)
(1): ReLU()
(2): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(3): Conv1d(200, 200, kernel_size=(5,), stride=(1,), padding=same)
(4): ReLU()
(5): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(6): Conv1d(200, 200, kernel_size=(5,), stride=(1,), padding=same)
(7): ReLU()
(8): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
(shortcut): Conv1d(1, 200, kernel_size=(1,), stride=(1,), padding=same)
)
(1): ReLU()
(2): Flatten(start_dim=1, end_dim=-1)
(3): Dropout(p=0.1, inplace=False)
(4): Linear(in_features=40000, out_features=2, bias=True)
(5): Softmax(dim=1)
)
)
Input sample shape is (1, 200).
It seems to be absolutely okay but, when I try to get graph in tensorboard, I get the following structure:
Somehow my Residual block connected with Linear. Does this connection really corresponds my net structure?
Model definition:
class Res_Block(nn.Module):
def __init__(self, in_ch, out_ch, ks, stride, activation):
super(Res_Block, self).__init__()
self.mod = nn.Sequential(
nn.Conv1d(in_ch, out_ch, ks, stride, padding='same'),
deepcopy(activation),
nn.BatchNorm1d(out_ch),
nn.Conv1d(out_ch, out_ch, ks, stride, padding='same'),
deepcopy(activation),
nn.BatchNorm1d(out_ch),
nn.Conv1d(out_ch, out_ch, ks, stride, padding='same'),
deepcopy(activation),
nn.BatchNorm1d(out_ch)
)
self.shortcut = nn.Conv1d(in_ch, out_ch, kernel_size=1, stride=1, padding='same')
def forward(self, X):
return self.mod(X) + self.shortcut(X)
layers = []
layers.append(Res_Block(1, 200, 5, 1, nn.ReLU()))
layers.append(nn.ReLU())
layers.append(nn.Flatten())
layers.append(nn.Dropout(0.2))
layers.append(nn.Linear(200 * 200, 2))
layers.append(nn.Softmax(dim=1))
R = nn.Sequential(*layers)
| I solved the problem by removing nn.Sequential in Res_Block __init__ and adding self.l1, self.l2 ... instead. (I also removed some layers and added maxpool but only after I solved the problem)
class Res_Block(nn.Module):
def __init__(self, in_shape, out_ch, ks, stride, activation):
super(Res_Block, self).__init__()
self.l1 = nn.Conv1d(in_shape, out_ch, ks, stride, padding='same')
self.l2 = deepcopy(activation)
self.l3 = nn.BatchNorm1d(out_ch)
self.l4 = nn.Conv1d(out_ch, out_ch, ks, stride, padding='same')
self.l5 = nn.BatchNorm1d(out_ch)
self.shortcut = nn.Conv1d(in_shape, out_ch, kernel_size=1, stride=1, padding='same')
def forward(self, X):
return self.l5(self.l4(self.l3(self.l2(self.l1(X))))) + self.shortcut(X)
The corresponding tensorboard structure is
The only one left question is why did that help me solve the problem.
| https://stackoverflow.com/questions/69427862/ |
How to get a Histogram of PyTorch tensors in batches? | Is there a way to get the histograms of torch tensors in batches?
For Example:
x is a tensor of shape (64, 224, 224)
# x will have shape of (64, 256)
x = batch_histogram(x, bins=256, min=0, max=255)
| It is possible to do this with torch.nn.functional.one_hot in a single line of code:
torch.nn.functional.one_hot(data_tensor, num_classes).sum(dim=-2)
The rationale is that one_hot does respect batches and, for each value v in the last dimension of the given tensor, creates a tensor filled with 0s, with the exception of the v-th component, which is 1. We them sum over all such one-hot encodings to obtain how many times v appears in each row of data in the 2-nd last dimension (which was the last dimension in tensor_data).
One possibly serious drawback of this method is memory usage, since each value with be expanded into a tensor of size num_classes (so, the size of tensor_data is multiplied by num_classes). This memory usage is temporary, however, since sum collapses again this extra dimension and the result will typically be smaller than tensor_data. I say "typically" because if num_classes is much larger than the size of the last dimension of tensor_data then the result will be correspondingly larger.
Here's the code with documentation, followed by pytest tests:
def batch_histogram(data_tensor, num_classes=-1):
"""
Computes histograms of integral values, even if in batches (as opposed to torch.histc and torch.histogram).
Arguments:
data_tensor: a D1 x ... x D_n torch.LongTensor
num_classes (optional): the number of classes present in data.
If not provided, tensor.max() + 1 is used (an error is thrown if tensor is empty).
Returns:
A D1 x ... x D_{n-1} x num_classes 'result' torch.LongTensor,
containing histograms of the last dimension D_n of tensor,
that is, result[d_1,...,d_{n-1}, c] = number of times c appears in tensor[d_1,...,d_{n-1}].
"""
return torch.nn.functional.one_hot(data_tensor, num_classes).sum(dim=-2)
def test_batch_histogram():
data = [2, 5, 1, 1]
expected = [0, 2, 1, 0, 0, 1]
run_test(data, expected)
data = [
[2, 5, 1, 1],
[3, 0, 3, 1],
]
expected = [
[0, 2, 1, 0, 0, 1],
[1, 1, 0, 2, 0, 0],
]
run_test(data, expected)
data = [
[[2, 5, 1, 1], [2, 4, 1, 1], ],
[[3, 0, 3, 1], [2, 3, 1, 1], ],
]
expected = [
[[0, 2, 1, 0, 0, 1], [0, 2, 1, 0, 1, 0], ],
[[1, 1, 0, 2, 0, 0], [0, 2, 1, 1, 0, 0], ],
]
run_test(data, expected)
def test_empty_data():
data = []
num_classes = 2
expected = [0, 0]
run_test(data, expected, num_classes)
data = [[], []]
num_classes = 2
expected = [[0, 0], [0, 0]]
run_test(data, expected, num_classes)
data = [[], []]
run_test(data, expected=None, exception=RuntimeError) # num_classes not provided for empty data
def run_test(data, expected, num_classes=-1, exception=None):
data_tensor = torch.tensor(data, dtype=torch.long)
if exception is None:
expected_tensor = torch.tensor(expected, dtype=torch.long)
actual = batch_histogram(data_tensor, num_classes)
assert torch.equal(actual, expected_tensor)
else:
with pytest.raises(exception):
batch_histogram(data_tensor, num_classes)
| https://stackoverflow.com/questions/69429586/ |
Is it possible to store some tensors on CPU and other on GPU for training neural network in PyTorch? | I designed a neural network in PyTorch, which is demanding a lot of GPU memory or else runs with a very small batch size.
The GPU Runtime error is causing due to three lines of code, which stores two new tensors and does some operations.
I don't want to run my code with a small batch size. So, I want to execute those three lines of code (and hence storing those new tensors) on CPU and remaining all other code on GPU as usual.
Is it possible to do?
| It is possible.
You can use the command .to(device=torch.device('cpu') to move the relevant tensors from GPU to CPU, and back to GPU afterwards:
orig_device = a.device # store the device from which the tensor originated
# move tensors a and b to CPU
a = a.to(device=torch.device('cpu'))
b = b.to(device=torch.device('cpu'))
# do some operation on a and b - it will be executed on CPU
res = torch.bmm(a, b)
# put the result back to GPU
res = res.to(device=orig_device)
A few notes:
Moving tensors between devices, or between GPU and CPU is not an unusual event. The term used to describe it is "model parallel" - you can google it for more details and examples.
Note that .to() operation is not an "in place" operation.
Moving tensor back and forth between GPU and CPU takes time. It might not be worthwhile using "model parallelism" of this type in this case. If you are struggling with GPU space, you might consider gradient accumulation instead
| https://stackoverflow.com/questions/69430320/ |
Test Intel Extension for Pytorch(IPEX) in multiple-choice from huggingface / transformers | I am trying out one huggingface sample with SWAG dataset
https://github.com/huggingface/transformers/tree/master/examples/pytorch/multiple-choice
I would like to use Intel Extension for Pytorch in my code to increase the performance.
Here I am using the one without training (run_swag_no_trainer)
In the run_swag_no_trainer.py , I made some changes to use ipex .
#Code before changing is given below:
device = accelerator.device
model.to(device)
#After adding ipex:
import intel_pytorch_extension as ipex
device = ipex.DEVICE
model.to(device)
While running the below command, its taking too much time.
export DATASET_NAME=swag
accelerate launch run_swag_no_trainer.py \
--model_name_or_path bert-base-cased \
--dataset_name $DATASET_NAME \
--max_seq_length 128 \
--per_device_train_batch_size 32 \
--learning_rate 2e-5 \
--num_train_epochs 3 \
--output_dir /tmp/$DATASET_NAME/
Is there any other method to test the same on intel ipex?
| First you have to understand, which factors actually increases the running time. Following are these factors:
The large input size.
The data structure; shifted mean, and unnormalized.
The large network depth, and/or width.
Large number of epochs.
The batch size not compatible with physical available memory.
Very small or high learning rate.
For fast running, make sure to work on the above factors, like:
Reduce the input size to the appropriate dimensions that assures no loss in important features.
Always preprocess the input to make it zero mean, and normalized it by dividing it by std. deviation or difference in max, min values.
Keep the network depth and width that is not to high or low. Or always use the standard architecture that are theoretically proven.
Always make sure of the epochs. If you are not able to make any further improvements in your error or accuracy beyond a defined threshold, then there is no need to take more epochs.
The batch size should be decided based on the available memory, and number of CPUs/GPUs. If the batch cannot be loaded fully in memory, then this will lead to slow processing due to lots of paging between memory and the filesystem.
Appropriate learning rate should be determine by trying multiple, and using that which gives the best reduction in error w.r.t. number of epochs.
| https://stackoverflow.com/questions/69433514/ |
ERROR: while installing Ipex using docker centos image | Unable to install Ipex using docker centos image
I pulled this docker image: docker pull sysstacks/dlrs-pytorch-centos
Tried to run on my linux machine with this command: docker run -it sysstacks/dlrs-pytorch-centos bash
I was trying to install Ipex using centos docker image (image name: sysstacks/dlrs-pytorch-centos) unfortunately i got this error.
after setting env
enter image description here
[root@0d96884d3a05 /]# python -m pip install torch_ipex==1.9.0 -f https://software.intel.com/ipex-whl-stable
Looking in links: https://software.intel.com/ipex-whl-stable
ERROR: Exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 180, in _main
status = self.run(options, args)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 204, in wrapper
return func(self, options, args)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 319, in run
reqs, check_supported_wheels=not options.target_dir
File "/usr/local/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 128, in resolve
requirements, max_rounds=try_to_avoid_resolution_too_deep
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 473, in resolve
state = resolution.resolve(requirements, max_rounds=max_rounds)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 341, in resolve
name, crit = self._merge_into_criterion(r, parent=None)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 172, in _merge_into_criterion
if not criterion.candidates:
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/resolvelib/structs.py", line 139, in __bool__
return bool(self._sequence)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 143, in __bool__
return any(self)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 129, in <genexpr>
return (c for c in iterator if id(c) not in self._incompatible_ids)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 30, in _iter_built
for version, func in infos:
File "/usr/local/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 272, in iter_index_candidate_infos
hashes=hashes,
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/package_finder.py", line 879, in find_best_candidate
candidates = self.find_all_candidates(project_name)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/package_finder.py", line 824, in find_all_candidates
page_candidates = list(page_candidates_it)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/sources.py", line 134, in page_candidates
yield from self._candidates_from_page(self._link)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/package_finder.py", line 783, in process_project_url
html_page = self._link_collector.fetch_page(project_url)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/collector.py", line 512, in fetch_page
return _get_html_page(location, session=self.session)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/collector.py", line 422, in _get_html_page
resp = _get_html_response(url, session=session)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/index/collector.py", line 137, in _get_html_response
"Cache-Control": "max-age=0",
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/requests/sessions.py", line 555, in get
return self.request('GET', url, **kwargs)
File "/usr/local/lib/python3.6/site-packages/pip/_internal/network/session.py", line 449, in request
return super().request(method, url, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/cachecontrol/adapter.py", line 53, in send
resp = super(CacheControlAdapter, self).send(request, **kw)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/requests/adapters.py", line 449, in send
timeout=timeout
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/urllib3/connectionpool.py", line 696, in urlopen
self._prepare_proxy(conn)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/urllib3/connectionpool.py", line 964, in _prepare_proxy
conn.connect()
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/urllib3/connection.py", line 359, in connect
conn = self._connect_tls_proxy(hostname, conn)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/urllib3/connection.py", line 506, in _connect_tls_proxy
ssl_context=ssl_context,
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/urllib3/util/ssl_.py", line 432, in ssl_wrap_socket
ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
File "/usr/local/lib/python3.6/site-packages/pip/_vendor/urllib3/util/ssl_.py", line 474, in _ssl_wrap_socket_impl
return ssl_context.wrap_socket(sock)
File "/usr/lib64/python3.6/ssl.py", line 365, in wrap_socket
_context=self, _session=session)
File "/usr/lib64/python3.6/ssl.py", line 732, in __init__
raise ValueError("check_hostname requires server_hostname")
NOTE:
I have tried all these methods shown below but none of them worked
Why requests raise this exception "check_hostname requires server_hostname"?
| I think the issue is with your proxy, can you please try below commands in your docker container:
export HTTP_PROXY=http://x.x.x.x
export https_proxy=http://x.x.x.x
export HTTPS_PROXY=http://x.x.x.x
export http_proxy=http://x.x.x.x
Change x with your proxy ip
| https://stackoverflow.com/questions/69435344/ |
Missing seed functions to create reproducible RL experiments with Open AI Gym and PyTorch | I am using a simple DDQN-PER (https://github.com/higgsfield/RL-Adventure/blob/master/4.prioritized%20dqn.ipynb) to run my RL experiments. This could be used as a minimal and verifiable code for my question.
Also, here are the seed functions that I have found to be useful -
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
env.seed(seed)
env.action_space.seed(seed)
Despite this, I cannot reproduce my experiments. I believe I am missing some seed function and will appreciate inputs on the same.
| Check you gym Version. There has been a major recent upgrade with v0.20 .
Here is also a blog post, describing that the new environments should be deterministic, quoting the essence:
Determinism
Up until now, the ALE hasnβt been completely deterministic. There
exist games that implement their own PRNG seeded by various methods
which depend on the consoleβs state. We now properly control for this
source of stochasticity and can now say with confidence that the
emulator is 100% deterministic.
| https://stackoverflow.com/questions/69439942/ |
converting tensorflow transpose to pytorch | What is the equivalent function of
x = tf.transpose(y, perm=[2, 0, 1])
in pytorch?
For instance, If I have
import torch
y=torch.randn(10, 480, 640)
How can I convert y to x in pytorch?
| You can use torch.Tensor.permute:
>>> x = y.permute(2, 0, 1)
| https://stackoverflow.com/questions/69440822/ |
Save a model weights when a program receives TIME LIMIT while learning on a SLURM cluster | I use a deep learning models written in pytorch_lightning (pytorch) and train them on slurm clusters. I submit job like this:
sbatch --gpus=1 -t 100 python train.py
When requested GPU time ends, slurm kills my program and shows such message:
Epoch 0: : 339it [01:10, 4.84it/s, loss=-34] slurmstepd: error: *** JOB 375083 ON cn-007 CANCELLED AT 2021-10-04T22:20:54 DUE TO TIME LIMIT ***
How can I configure a Trainer to save model when available time end?
I know about automatic saving after each epoch, but I have only one long epoch that lasts >10 hours, so this case is not working for me.
| You can use Slurm's signalling mechanism to pass a signal to your application when it's within a certain number of seconds of the timelimit (see man sbatch). In your submission script use --signal=USR1@30 to send USR1 30 seconds before the timelimit is reached. Your submit script would contain these lines:
#SBATCH -t 100
#SBATCH --signal=USR1@30
srun python train.py
Then, in your code, you can handle that signal like this:
import signal
def handler(signum, frame):
print('Signal handler got signal ', signum)
# e.g. exit(0), or call your pytorch save routines
# enable the handler
signal.signal(signal.SIGUSR1, handler)
# your code here
You need to call your Python application via srun in order for Slurm to be able to propagate the signal to the Python process. (You can probably use --signal on the command line to sbatch, I tend to prefer writing self-contained submit scripts :))
Edit: This link has a nice summary of the issues involved with signal propagation and Slurm.
| https://stackoverflow.com/questions/69441573/ |
Sideffects when changind some elements of nn.Parameter | I want to have some nn.Parameter that depend on data, e.g. different values for different people. I realized while training one person, the results of the other people also change. I created a small demo below.
I tried to make everything deterministic and as expected, changing the size of nn.Parameter does not change the results. After training for 100 epochs, I always get [1.0605, 1.0715, 1.0622, 0.9702] for all_calibration_params[0]. But all other parameters of all_calibration_params also change, and they all change by the same value, with all_calibration_params = nn.Parameter(torch.ones(10, 4)) I get [0.8455, 0.8455, 0.8455, 0.8455] for all 9 other values. I would expect these values to stay [1, 1, 1, 1]. Can anyone please explain to me, why the other values change even though I do not use them during training?
Thank you.
import torch
from pytorch_lightning import LightningModule, Trainer, seed_everything
from torch import nn
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
class DemoDataset(Dataset):
"""
Generate random data, only for person 0.
Data is always random but output is always 1.
"""
def __init__(self):
pass
def __len__(self) -> int:
return 1_000
def __getitem__(self, idx):
return {
'person': torch.zeros(1),
'data': torch.rand(1),
'output': torch.ones(1),
}
class DemoModel(LightningModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.all_calibration_params = nn.Parameter(torch.ones(3, 4)) # all values are 1
self.fc_1 = nn.Linear(1, 4)
self.fc_2 = nn.Linear(4 + 4, 1)
def forward(self, person: torch.Tensor, data: torch.Tensor):
x = self.fc_1(data)
calibration_params = self.all_calibration_params[person].squeeze(1)
x = torch.cat((x, calibration_params), dim=1)
x = self.fc_2(x)
return x
class Model(DemoModel):
def __init__(self, learning_rate: float, weight_decay: float, *args, **kwargs):
super().__init__(*args, **kwargs)
self.learning_rate = learning_rate
self.weight_decay = weight_decay
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
def training_step(self, train_batch: dict, batch_idx: int):
data, person, output = train_batch['data'], train_batch['person'].long(), train_batch['output']
pred = self(person, data)
loss = F.mse_loss(pred, output)
return loss
if __name__ == '__main__':
seed_everything(42)
model = Model(learning_rate=1e-4, weight_decay=1e-5)
dataset = DemoDataset()
dataloader = DataLoader(dataset, batch_size=64)
print(model.all_calibration_params)
trainer = Trainer(
max_epochs=100,
deterministic=True
)
trainer.fit(model, dataloader)
print(model.all_calibration_params)
# model.all_calibration_params[1] should be [1, 1, 1, 1]
print(model.all_calibration_params[1], torch.ones(1, 4))
Output:
tensor([[1.0605, 1.0715, 1.0622, 0.9702],
[0.8455, 0.8455, 0.8455, 0.8455],
[0.8455, 0.8455, 0.8455, 0.8455]], requires_grad=True)
EDIT:
I added a small test if the other elements in nn.Parameter change the output, but the do not, so I do not understand why they are affected while training.
batch = next(iter(dataloader))
data, person = batch['data'], batch['person'].long()
output_org = model(person, data)
print(output_org[0])
model.freeze()
model.all_calibration_params[1:] = torch.ones(2, 4)
model.unfreeze()
output_mod = model(person, data)
print(output_mod[0])
print(torch.equal(output_org, output_mod))
Output:
tensor([0.6334], grad_fn=<SelectBackward>)
tensor([0.6334], grad_fn=<SelectBackward>)
True
| Your dataset always returns a 0 index for the 'person', i.e. self.all_calibration_params[person] will always select the first rows.
The reason the other two rows are getting updated is because of the weight decay that was set on the optimizer. This will update all parameters regardless of whether they were used or not during the model inference.
| https://stackoverflow.com/questions/69442568/ |
Getting multiple variables in TensorFlow and other frameworks (overheads) | If I have the following graph and want to get the values of tensors T1 and T2 in TF without eager execution, how would I do this? I only know of eval() or session.run() (running that twice could be an option) or tf.print(), but printing is not desired (for performance reasons).
Especially, how is this functionality implemented in TensorFlow? Does this impose a big overhead towards just getting T2? I would be happy to be pointed to relevant resources as well.
I'm generally looking for discussions on this -- if people want to add comparisons to how other frameworks do this (Caffe, Torch, CNTK, Theano, Chainer, DyNet, etc.), that's great! In the end, I am trying to understand how these frameworks could be expanded by operators that return operator-specfic metrics that a user can use to monitor training.
Thanks!
| you can pass multiple parameters to session.run, and it will run the network once and return each of those parameters.
For example (from the docs):
a = tf.constant([10, 20])
b = tf.constant([1.0, 2.0])
u, v = session.run([a, b])
| https://stackoverflow.com/questions/69445120/ |
Pytorch: '<=' not supported between instances of 'float' and 'function' | I am trying to calculate Intersection over Union (IOU) score. Here's my code implementation, which works fine.
def IoU(predict: torch.Tensor, target: torch.Tensor):
i = (predict & target).float().sum()
u = (predict | target).float().sum()
x = i/u
IOU = x.item()
return IoU
But when I run my unit test:
def test_IoU1():
pred = torch.tensor([[1, 0], [1, 0]])
target = torch.tensor([[1, 0], [1, 1]])
iou = IoU(pred,target)
assert 0.66 <= iou
assert iou <= 2/3
I get:
TypeError: '<=' not supported between instances of 'float' and 'function'
How do I fix this without changing anything on the unit test? Thank you
| In this function
def IoU(predict: torch.Tensor, target: torch.Tensor):
i = (predict & target).float().sum()
u = (predict | target).float().sum()
x = i/u
IOU = x.item()
return IoU
You are returning IoU which is the name of function, I suppose you need to return IOU. So the correct way would be -
def IoU(predict: torch.Tensor, target: torch.Tensor):
i = (predict & target).float().sum()
u = (predict | target).float().sum()
x = i/u
IOU = x.item()
return IOU
| https://stackoverflow.com/questions/69445929/ |
Pytorch different outputs between with transpose | Let I have a tensor dimension of (B, N^2, C)
and I reshape it into (B, C, N, N).
I think that I have two choices below
A = torch.rand(5, 100, 20) # Original Tensor
# First Method
B = torch.transpose(2, 1)
B = B.view(5, 20, 10, 10)
# Second Method
C = A.view(5, 20, 10, 10)
Both methods work but the outputs are slightly different and I cannot catch the difference between them.
Thanks
| The difference between B and C is that you have used torch.transpose which means you have swapped two axes, this means you have changed the layout of the memory. The view at the end is just a nice interface for you to access your data but it has no effect on the underlying data of your tensor. What it comes down to is a contiguous memory data buffer.
If you take a smaller example, something we can grasp more easily:
>>> A = torch.rand(1, 4, 3)
tensor([[[0.2656, 0.5920, 0.3774],
[0.8447, 0.5984, 0.0614],
[0.5160, 0.8048, 0.6260],
[0.1644, 0.3144, 0.1040]]])
Here swapping axis=1 and axis=2 comes down to a batched transpose (in mathematical terms):
>>> B = A.transpose(2, 1)
tensor([[[0.4543, 0.7447, 0.7814, 0.3444],
[0.9766, 0.2732, 0.4766, 0.0387],
[0.0123, 0.7260, 0.8939, 0.8581]]])
In terms of memory layout A has the following memory arangement:
>>> A.flatten()
tensor([0.4543, 0.9766, 0.0123, 0.7447, 0.2732, 0.7260, 0.7814, 0.4766, 0.8939,
0.3444, 0.0387, 0.8581])
While B has a different layout. By layout I mean memory arrangement, I am not referring to its shape which is irrelevant:
>>> B.flatten()
tensor([0.4543, 0.7447, 0.7814, 0.3444, 0.9766, 0.2732, 0.4766, 0.0387, 0.0123,
0.7260, 0.8939, 0.8581])
As I said reshaping i.e. building a view on top of a tensor doesn't change its memory layout, it's an abstraction level to better manipulate tensors.
So in the end, yes you end up with two different results: C shares the same data as A, while B is a copy and has a different memory layout.
| https://stackoverflow.com/questions/69446402/ |
Why torch.autograd.grad() returns None with torch.cat? | I know the torch.autograd.grad() returns None if the gradient is stopped somehow, however, I am wondering what is wrong with the following snippet?
x = torch.rand(6, requires_grad=True)
y = x.pow(2).sum()
z = torch.cat([x])
grad1 = torch.autograd.grad(y, x, allow_unused=True)
grad2 = torch.autograd.grad(y, z, allow_unused=True)
print(f'grad1 = {grad1}, grad = {grad2}')
The output is grad1 = (tensor([0.3705, 0.7468, 0.6102, 1.8640, 0.3518, 0.5397]),), grad = (None,).
I am expecting the grad2 is the same to grad1, because z is essentially the x. May I know why please?
Update: After reading the post and the help from @Ivan, I conclude the reason is x is a leaf node of y but z is not any more. x is the leaf node of both y and z in the computation graph, but there is no direct path from z to y, so the torch.autograd.grad returns None.
Note: The returned value None does not necessarily guarantee the values are 0.
| Tensor z was not used to compute the value of y, as such it is not connected to its computation graph, and you won't get a gradient on z, since it's not connected to y.
On the other hand, the following will work:
>>> y = x.pow(2).sum()
>>> torch.autograd.grad(y, x, allow_unused=True)
(tensor([0.3134, 1.6802, 0.1989, 0.8495, 1.9203, 1.0905]),)
>>> z = torch.cat([x])
>>> y = z.pow(2).sum()
>>> torch.autograd.grad(y, z, allow_unused=True)
(tensor([0.3134, 1.6802, 0.1989, 0.8495, 1.9203, 1.0905]),)
| https://stackoverflow.com/questions/69447539/ |
Get grads of parameters w.r.t a loss term in pytorch | I my Pytorch training i use a composite loss function defined as :
.
In order to update the weights alpha and beta, i need to compute three values : which are the the means of the gradients of the loss terms w.r.t to all the weights in the network.
Is there an efficient way to write it in pytorch ?
My training code look like :
for epoc in range(1, nb_epochs+1):
#init
optimizer_fo.zero_grad()
#get the current loss
loss_total = mynet_fo.loss(tensor_xy_dirichlet,g_boundaries_d,tensor_xy_inside,tensor_f_inter,tensor_xy_neuman,g_boundaries_n)
#compute gradients
loss_total.backward(retain_graph=True)
#optimize
optimizer_fo.step()
Where my .loss() function directly return the sum of the terms. I've thinking of make a second forward pass and call backward on each Loss term independently but it would be very expensive.
| 1- Using torch.autograd.grad
You can get the different terms of your gradient only by back-propagating multiple times on your network. In order to avoid having to perform multiple inferences on your input, you can use the torch.autograd.grad utility function instead of doing a conventional backward pass backward. This means you won't pollute the gradients coming from the different terms.
Here is a minimal example that shows the basic idea:
>>> x = torch.rand(1, 10, requires_grad=True)
>>> lossA = x.pow(2).sum()
>>> lossB = x.mean()
Then perform one backward pass on each term out of place. You have to retain the graph on all calls but the last:
>>> gradA = torch.autograd.grad(lossA, x, retain_graph=True)
(tensor([[1.5810, 0.6684, 0.1467, 0.6618, 0.5067, 0.2368, 0.0971, 0.4533, 0.3511,
1.9858]]),)
>>> gradB = torch.autograd.grad(lossB, x)
(tensor([[0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000,
0.1000]]),)
This method has some limitations since you are receiving your parameters' gradient as a tuple which is not that convenient.
2- Caching the results of backward
An alternative solution consists in caching the gradient after each successive backward call:
>>> lossA = x.pow(2).sum()
>>> lossB = x.mean()
>>> lossA.backward(retain_graph=True)
Store the gradient and clear the .grad attributes (don't forget to do so otherwise the gradient of lossA will pollute gradB. You will have to adapt this to the general case when handling multiple tensor parameters:
>>> x.gradA = x.grad
>>> x.grad = None
Backward pass on the next loss term:
>>> lossB.backward()
>>> x.gradB = x.grad
Then you can interact with each gradient term locally (i.e. on each parameter separately):
>>> x.gradA, x.gradB
(tensor([[1.5810, 0.6684, 0.1467, 0.6618, 0.5067, 0.2368, 0.0971, 0.4533, 0.3511,
1.9858]]),
tensor([[0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000, 0.1000,
0.1000]]))
The latter method seems more practical.
This essentially comes down to torch.autograd.grad vs torch.autograd.backward, i.e. out-of-place vs in-place... and will ultimately depends on your needs. You can read more about these two functions here.
| https://stackoverflow.com/questions/69448198/ |
Output of nn.Linear is different for the same input | In torch==1.7.1+cu101, I have two tensors
import torch
a = torch.rand(1,5,10)
b = torch.rand(100,1,10)
and a feed-forward network
import torch.nn as nn
l = nn.Linear(10,10)
I force one row of them to be equal:
a[0,0] = b[80][0].clone()
Then I feed both tensors to l:
r1 = l(a)
r2 = l(b)
Apparently, since a[0,0] is equal to b[80,0], r1[0,0] must be equal to r2[80,0].
But it turns out to be like:
(r1[0,0] == r2[80,0]).all()
>>> False
I've fixed the randomness by:
seed = 42
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
Does anyone know why (r1[0,0] == r2[80,0]).all() is False?
| If you were to print r1[0, 0] and r2[80, 0], you'd see that they are extremely similar. Even identical within the number of printed digits.
However, if you print r1[0, 0] - r2[80, 0] you'll see that the resulting entries are not perfectly 0.0 (though they are close to it), meaning that r1[0, 0] and r2[80, 0] are close but not perfectly identical.
Now, if we were to do take those individual vectors out first, and then pass them through the linear layer like this:
r1_small = l(a[0, 0])
r2_small = l(b[80, 0])
print((r1_small == r2_small).all()) # tensor(True)
we get that they are perfectly identical, even despite being floats.
So, that means that some difference is introduced by the identical vectors being smaller parts of bigger tensors when they are passed through the linear layer.
It's also very much worth noting that the same difference does not arise when the first n-1 dimensions are all powers of 2:
a2 = torch.randn(8, 8, 10)
b2 = torch.randn(4, 16, 10)
a2[0, 0] = b2[1, 0].clone()
r1_2 = l(a2)
r2_2 = l(b2)
print((r1_2[0, 0] == r2_2[1, 0]).all()) # tensor(True)
So, while I don't know the details, I suspect it has to do with byte alignment.
In general, testing for perfect equality between float values that should be mathematically equal will not always give the expected results. So how do we handle these differences? You can use torch.isclose or torch.allclose to check for imperfect equality.
| https://stackoverflow.com/questions/69459859/ |
pytorch optim.SGD with momentum how to check "velocity"? | I have a noob question: from the SGD doc they provided the equation of SGD with momentum, which indicates that apart from current gradient weight.grad, we also need to save the velocity from the previous step (something like weight.prev_v?). I know nn.Parameter object has .data and .grad attributes, but does it also saves a .prev_v? Do you know how pytorch works? Thanks!
Edit: Basically I'd like to know where does pytorch save velocity from the previous step?
| Those are stored inside the state attribute of the optimizer. In the case of torch.optim.SGD the momentum values are stored a dictionary under the 'momentum_buffer' key, as you can see in the source code.
Here is a minimal example:
>>> m = nn.Linear(10,10)
>>> optim = torch.optim.SGD(m.parameters(), lr=1.e-3, momentum=.9)
>>> m(torch.rand(1, 10)).mean().backward()
>>> optim.step()
>>> optim.state
defaultdict(dict, {0: {}, Parameter containing: ...})
>>> list(optim.state.values())[0]
{'momentum_buffer': tensor([...])}
| https://stackoverflow.com/questions/69465707/ |
Is there a function for picking the max value in a pytorch tensor which follows a requirenment | I am programming an othello bot in python using reinforcment learning and pytorch. In the program, I scan the board for legal moves. The AI should choose the move with the highest probability of beeing good, and that is legal according to the previose calculation. Here I need a function that works something like this:
a = torch.tensor([1,2,3,4,5])
b = torch.tensor([True, True, False, True, False], dtype=bool)
print(torch.somefunction(a,b))
The output should be the id of the max value in a, in this case 3. Does this function exist? And if not, are there any other whay of doing this?
| Assuming there is at least one non-negative value in your tensor, you multiply it by the mask itself to remove excluded values in the sorting:
>>> torch.argmax(a*b)
tensor(3)
If that's not the case, you can still get away with it, using torch.where by replacing the excluded values with some value that will get ignored by the argmax (e.g. a.min()):
>>> torch.where(b, a, a.min()).argmax()
tensor(3)
| https://stackoverflow.com/questions/69466550/ |
Tuple of Tensors | I recently asked one part of this question. I am building a chatbot, and there is a function that makes the problems. The function is given below:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = Variable(torch.stack(torch.Tensor(inputs),1).cuda())
else:
batch_inputs = Variable(torch.stack(torch.Tensor(inputs),1))
return batch_inputs, lengths_inputs
But when I try to run the chatbot code , it gives me this error:
stack(): argument 'tensors' (position 1) must be tuple of Tensors, not tensor
For that reason, I fixed the function like this:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = torch.stack(inputs, 1).cuda()
else:
batch_inputs = torch.stack(inputs, 1)
return batch_inputs, lengths_inputs
But it still gives me error, and the error is like this:
TypeError: expected Tensor as element 0 in argument 0, but got list
What should I do now in this situation?
| Since the vec and length are both integers, you can use torch.tensor directly:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = torch.tensor(inputs, device='cuda')
else:
batch_inputs = torch.tensor(inputs)
return batch_inputs, lengths_inputs
| https://stackoverflow.com/questions/69467986/ |
pyro: how to specify conditional distribution | I am trying to use pyro for specifying a Bayesian network. I have a child node D which is continuous and it has three discrete nodes are parents, each with 10 possible states:
So, I first define my discrete nodes as:
import torch
import pyro
import pyro.distributions as dist
def model(data):
A = pyro.sample("A", dist.Dirichlet(torch.ones(10)))
B = pyro.sample("B", dist.Dirichlet(torch.ones(10)))
C = pyro.sample("C", dist.Dirichlet(torch.ones(10)))
Now, as I understand I need to define P(D|A, B, C). I want to model this as a normal distribution but not sure how to do this conditioning. My plan is to put priors on this distribution parameters and then use MCMC or HMC to estimate the posterior distribution and learn the model parameters.
However, not sure how to proceed with the model definition.
| Good thing about pyro is that the model definition is very pythonic. The underlying PyTorch machinery can track dependencies for you.
All you need is use the samples A, B and C and compute the parameters of the conditional p(D|A,B,C)
def cond_mean(a, b, c):
return # use a,b,c to compute mean
def cond_scale(a, b, c):
return # use a,b,c to compute scale
def model(data):
A = pyro.sample("A", dist.Dirichlet(torch.ones(10)))
B = pyro.sample("B", dist.Dirichlet(torch.ones(10)))
C = pyro.sample("C", dist.Dirichlet(torch.ones(10)))
D = pyro.sample("D", dist.Normal(loc=cond_mean(A, B, C), scale=cond_scale(A, B, C)
...
| https://stackoverflow.com/questions/69472294/ |
When I was trying to run IPEX on DevCloud it is showing "Illegal instruction" | I was trying image classification using IPEX on DevCloud but it is showing "Illegal instruction" for me.
qsub -I -l nodes=1:gpu:ppn=2 -d .
python3 inf.py
| qsub -I -l nodes=1:gpu:ppn=2 -d .
This command is used to assign one full GPU node.
IPEX don't support gpu as mentioned here:
https://github.com/intel/intel-extension-for-pytorch/issues/149#issuecomment-812348623
This could be the reason for that error.
Try using below commands:
qsub -I
python3 inf.py
| https://stackoverflow.com/questions/69477016/ |
FastGAN - RuntimeError: Error(s) in loading state_dict for Generator | I'm running FastGAN (https://github.com/odegeasslbc/FastGAN-pytorch) on Google Colab and now trying to resume training from a saved .pth generated by the network. However, it keeps throwing this error:
Traceback (most recent call last):
File "train.py", line 202, in
train(args)
File "train.py", line 117, in train
netG.load_state_dict(ckpt['g'])
File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1407, in load_state_dict
self.__class__.__name__, "\n\t".join(error_msgs)))
RuntimeError: Error(s) in loading state_dict for Generator:
Missing key(s) in state_dict: "init.init.0.weight_orig", "init.init.0.weight", "init.init.0.weight_u", "init.init.0.weight_orig", "init.init.0.weight_u", "init.init.0.weight_v", "init.init.1.weight", "init.init.1.bias", "init.init.1.running_mean", "init.init.1.running_var", "feat_8.1.weight_orig", "feat_8.1.weight", "feat_8.1.weight_u", "feat_8.1.weight_orig", "feat_8.1.weight_u", "feat_8.1.weight_v", "feat_8.2.weight", "feat_8.3.weight", "feat_8.3.bias", "feat_8.3.running_mean", "feat_8.3.running_var", "feat_8.5.weight_orig", "feat_8.5.weight", "feat_8.5.weight_u", "feat_8.5.weight_orig", "feat_8.5.weight_u", "feat_8.5.weight_v", "feat_8.6.weight", "feat_8.7.weight", "feat_8.7.bias", "feat_8.7.running_mean", "feat_8.7.running_var", "feat_16.1.weight_orig", "feat_16.1.weight", "feat_16.1.weight_u", "feat_16.1.weight_orig", "feat_16.1.weight_u", "feat_16.1.weight_v", "feat_16.2.weight", "feat_16.2.bias", "feat_16.2.running_mean", "feat_16.2.running_var", "feat_32.1.weight_orig", "feat_32.1.weight", "feat_32.1.weight_u", "feat_32.1.weight_orig", "feat_32.1.weight_u", "feat_32.1.weight_v", "feat_32.2.weight", "feat_32.3.weight", "feat_32.3.bias", "feat_32.3.running_mean", "feat_32.3.running_var", "feat_32.5.weight_orig", "feat_32.5.weight", "feat_32.5.weight_u", "feat_32.5.weight_orig", "feat_32.5.weight_u", "feat_32.5.weight_v", "feat_32.6.weight", "feat_32.7.weight", "feat_32.7.bias", "feat_32.7.running_mean", "feat_32.7.running_var", "feat_64.1.weight_orig", "feat_64.1.weight", "feat_64.1.weight_u", "feat_64.1.weight_orig", "feat_64.1.weight_u", "feat_64.1.weight_v", "feat_64.2.weight", "feat_64.2.bias", "feat_64.2.running_mean", "feat_64.2.running_var", "feat_128.1.weight_orig", "feat_128.1.weight", "feat_128.1.weight_u", "feat_128.1.weight_orig", "feat_128.1.weight_u", "feat_128.1.weight_v", "feat_128.2.weight", "feat_128.3.weight", "feat_128.3.bias", "feat_128.3.running_mean", "feat_128.3.running_var", "feat_128.5.weight_orig", "feat_128.5.weight", "feat_128.5.weight_u", "feat_128.5.weight_orig", "feat_128.5.weight_u", "feat_128.5.weight_v", "feat_128.6.weight", "feat_128.7.weight", "feat_128.7.bias", "feat_128.7.running_mean", "feat_128.7.running_var", "feat_256.1.weight_orig", "feat_256.1.weight", "feat_256.1.weight_u", "feat_256.1.weight_orig", "feat_256.1.weight_u", "feat_256.1.weight_v", "feat_256.2.weight", "feat_256.2.bias", "feat_256.2.running_mean", "feat_256.2.running_var", "se_64.main.1.weight_orig", "se_64.main.1.weight", "se_64.main.1.weight_u", "se_64.main.1.weight_orig", "se_64.main.1.weight_u", "se_64.main.1.weight_v", "se_64.main.3.weight_orig", "se_64.main.3.weight", "se_64.main.3.weight_u", "se_64.main.3.weight_orig", "se_64.main.3.weight_u", "se_64.main.3.weight_v", "se_128.main.1.weight_orig", "se_128.main.1.weight", "se_128.main.1.weight_u", "se_128.main.1.weight_orig", "se_128.main.1.weight_u", "se_128.main.1.weight_v", "se_128.main.3.weight_orig", "se_128.main.3.weight", "se_128.main.3.weight_u", "se_128.main.3.weight_orig", "se_128.main.3.weight_u", "se_128.main.3.weight_v", "se_256.main.1.weight_orig", "se_256.main.1.weight", "se_256.main.1.weight_u", "se_256.main.1.weight_orig", "se_256.main.1.weight_u", "se_256.main.1.weight_v", "se_256.main.3.weight_orig", "se_256.main.3.weight", "se_256.main.3.weight_u", "se_256.main.3.weight_orig", "se_256.main.3.weight_u", "se_256.main.3.weight_v", "to_128.weight_orig", "to_128.weight", "to_128.weight_u", "to_128.weight_orig", "to_128.weight_u", "to_128.weight_v", "to_big.weight_orig", "to_big.weight", "to_big.weight_u", "to_big.weight_orig", "to_big.weight_u", "to_big.weight_v", "feat_512.1.weight_orig", "feat_512.1.weight", "feat_512.1.weight_u", "feat_512.1.weight_orig", "feat_512.1.weight_u", "feat_512.1.weight_v", "feat_512.2.weight", "feat_512.3.weight", "feat_512.3.bias", "feat_512.3.running_mean", "feat_512.3.running_var", "feat_512.5.weight_orig", "feat_512.5.weight", "feat_512.5.weight_u", "feat_512.5.weight_orig", "feat_512.5.weight_u", "feat_512.5.weight_v", "feat_512.6.weight", "feat_512.7.weight", "feat_512.7.bias", "feat_512.7.running_mean", "feat_512.7.running_var", "se_512.main.1.weight_orig", "se_512.main.1.weight", "se_512.main.1.weight_u", "se_512.main.1.weight_orig", "se_512.main.1.weight_u", "se_512.main.1.weight_v", "se_512.main.3.weight_orig", "se_512.main.3.weight", "se_512.main.3.weight_u", "se_512.main.3.weight_orig", "se_512.main.3.weight_u", "se_512.main.3.weight_v", "feat_1024.1.weight_orig", "feat_1024.1.weight", "feat_1024.1.weight_u", "feat_1024.1.weight_orig", "feat_1024.1.weight_u", "feat_1024.1.weight_v", "feat_1024.2.weight", "feat_1024.2.bias", "feat_1024.2.running_mean", "feat_1024.2.running_var".
Unexpected key(s) in state_dict: "module.init.init.0.weight_orig", "module.init.init.0.weight_u", "module.init.init.0.weight_v", "module.init.init.1.weight", "module.init.init.1.bias", "module.init.init.1.running_mean", "module.init.init.1.running_var", "module.init.init.1.num_batches_tracked", "module.feat_8.1.weight_orig", "module.feat_8.1.weight_u", "module.feat_8.1.weight_v", "module.feat_8.2.weight", "module.feat_8.3.weight", "module.feat_8.3.bias", "module.feat_8.3.running_mean", "module.feat_8.3.running_var", "module.feat_8.3.num_batches_tracked", "module.feat_8.5.weight_orig", "module.feat_8.5.weight_u", "module.feat_8.5.weight_v", "module.feat_8.6.weight", "module.feat_8.7.weight", "module.feat_8.7.bias", "module.feat_8.7.running_mean", "module.feat_8.7.running_var", "module.feat_8.7.num_batches_tracked", "module.feat_16.1.weight_orig", "module.feat_16.1.weight_u", "module.feat_16.1.weight_v", "module.feat_16.2.weight", "module.feat_16.2.bias", "module.feat_16.2.running_mean", "module.feat_16.2.running_var", "module.feat_16.2.num_batches_tracked", "module.feat_32.1.weight_orig", "module.feat_32.1.weight_u", "module.feat_32.1.weight_v", "module.feat_32.2.weight", "module.feat_32.3.weight", "module.feat_32.3.bias", "module.feat_32.3.running_mean", "module.feat_32.3.running_var", "module.feat_32.3.num_batches_tracked", "module.feat_32.5.weight_orig", "module.feat_32.5.weight_u", "module.feat_32.5.weight_v", "module.feat_32.6.weight", "module.feat_32.7.weight", "module.feat_32.7.bias", "module.feat_32.7.running_mean", "module.feat_32.7.running_var", "module.feat_32.7.num_batches_tracked", "module.feat_64.1.weight_orig", "module.feat_64.1.weight_u", "module.feat_64.1.weight_v", "module.feat_64.2.weight", "module.feat_64.2.bias", "module.feat_64.2.running_mean", "module.feat_64.2.running_var", "module.feat_64.2.num_batches_tracked", "module.feat_128.1.weight_orig", "module.feat_128.1.weight_u", "module.feat_128.1.weight_v", "module.feat_128.2.weight", "module.feat_128.3.weight", "module.feat_128.3.bias", "module.feat_128.3.running_mean", "module.feat_128.3.running_var", "module.feat_128.3.num_batches_tracked", "module.feat_128.5.weight_orig", "module.feat_128.5.weight_u", "module.feat_128.5.weight_v", "module.feat_128.6.weight", "module.feat_128.7.weight", "module.feat_128.7.bias", "module.feat_128.7.running_mean", "module.feat_128.7.running_var", "module.feat_128.7.num_batches_tracked", "module.feat_256.1.weight_orig", "module.feat_256.1.weight_u", "module.feat_256.1.weight_v", "module.feat_256.2.weight", "module.feat_256.2.bias", "module.feat_256.2.running_mean", "module.feat_256.2.running_var", "module.feat_256.2.num_batches_tracked", "module.se_64.main.1.weight_orig", "module.se_64.main.1.weight_u", "module.se_64.main.1.weight_v", "module.se_64.main.3.weight_orig", "module.se_64.main.3.weight_u", "module.se_64.main.3.weight_v", "module.se_128.main.1.weight_orig", "module.se_128.main.1.weight_u", "module.se_128.main.1.weight_v", "module.se_128.main.3.weight_orig", "module.se_128.main.3.weight_u", "module.se_128.main.3.weight_v", "module.se_256.main.1.weight_orig", "module.se_256.main.1.weight_u", "module.se_256.main.1.weight_v", "module.se_256.main.3.weight_orig", "module.se_256.main.3.weight_u", "module.se_256.main.3.weight_v", "module.to_128.weight_orig", "module.to_128.weight_u", "module.to_128.weight_v", "module.to_big.weight_orig", "module.to_big.weight_u", "module.to_big.weight_v", "module.feat_512.1.weight_orig", "module.feat_512.1.weight_u", "module.feat_512.1.weight_v", "module.feat_512.2.weight", "module.feat_512.3.weight", "module.feat_512.3.bias", "module.feat_512.3.running_mean", "module.feat_512.3.running_var", "module.feat_512.3.num_batches_tracked", "module.feat_512.5.weight_orig", "module.feat_512.5.weight_u", "module.feat_512.5.weight_v", "module.feat_512.6.weight", "module.feat_512.7.weight", "module.feat_512.7.bias", "module.feat_512.7.running_mean", "module.feat_512.7.running_var", "module.feat_512.7.num_batches_tracked", "module.se_512.main.1.weight_orig", "module.se_512.main.1.weight_u", "module.se_512.main.1.weight_v", "module.se_512.main.3.weight_orig", "module.se_512.main.3.weight_u", "module.se_512.main.3.weight_v", "module.feat_1024.1.weight_orig", "module.feat_1024.1.weight_u", "module.feat_1024.1.weight_v", "module.feat_1024.2.weight", "module.feat_1024.2.bias", "module.feat_1024.2.running_mean", "module.feat_1024.2.running_var", "module.feat_1024.2.num_batches_tracked".
Any idea what might be happening here?
Thanks so much for any help!
| This is common when changing the attribute name of the submodules in your nn.Module.
Notice how most of your layer keys here differ from the ones contained in the loaded state dict because of their prefix: all keys in the dictionary have a 'module.' prefix.
A quick fix you be to slice away this prefix. You could for instance usea dict comprehension:
loaded_state = {k.replace('module.', ''): v for k, v in ckpt['g'].items()}
netG.load_state_dict(loaded_state)
| https://stackoverflow.com/questions/69478457/ |
How can i implement the __getitem__ method in PyTorch for the sinus | I am starting with PyTorch and i am trying to create a Network that is predicting the sinus of x. I tried to create a DataSet like this:
class SinusDataset(Dataset):
def __init__(self, size: int = 1000):
self.size = size
def __len__(self):
return self.size
def __getitem__(self, idx: int)->Tensor:
if idx > self.size:
raise ValueError
return idx, math.sin(idx)
I do not think that is the proper way to implement this. How should I Implemented the `__get__Β΄ method?
| You could initialize your input and labels on init and save those in lists. Then, in your __getitem__ function, pick instances from those two using the provided idx integer. Something like:
class SinusDataset(Dataset):
def __init__(self, size: int = 1000):
self.x = torch.linspace(0, 1, size)
self.y = torch.sin(self.x)
def __len__(self) -> int:
return len(self.x)
def __getitem__(self, idx: int):
return return self.x[idx][None], self.y[idx][None]
Then you can use the dataset by wrapping a torch.utils.data.DataLoader:
>>> dl = DataLoader(SinusDataset(100), batch_size=4, shuffle=True)
>>> for x, y in dl:
... print(x, y)
... break
tensor([0.2452, 0.6116, 0.0791, 0.6667]) tensor([0.2428, 0.5742, 0.0790, 0.6184])
In this case it would be more appropriate to inherit from torch.utils.data.TensorDataset directly. This comes with both __len__ and __getitem__ implemented for you (see source):
class SinusDataset(TensorDataset):
def __init__(self, size: int = 1000):
x = torch.linspace(0, 1, 1000)[:,None]
y = torch.sin(x)[:,None]
super().__init__(x, y)
This is slightly more advanced but it is considered best practice to inherit from the closest built-in torch.utils.data.Dataset class instead of writing the same methods yourself.
Inference example:
>>> model = nn.Sequential(nn.Linear(1, 4),
nn.ReLU(),
nn.Linear(4, 1))
>>> x, y = next(iter(dl))
>>> model(x)
tensor([[-0.0640],
[ 0.1461],
[-0.0882],
[ 0.2259]], grad_fn=<AddmmBackward>)
| https://stackoverflow.com/questions/69482493/ |
unable to load pytorch model for evaluation | I have a .pth model saved and I am trying to load to do inference using the following code
model = GatherModel()
model.load_state_dict(torch.load('/content/CIGIN/weights/cigin.tar'))
and I am getting this error shown below. why I am getting this.
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-8-3bff0e426886> in <module>()
----> 1 model.load_state_dict(torch.load('/content/CIGIN/weights/cigin.tar'))
/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict)
1405 if len(error_msgs) > 0:
1406 raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
-> 1407 self.__class__.__name__, "\n\t".join(error_msgs)))
1408 return _IncompatibleKeys(missing_keys, unexpected_keys)
1409
RuntimeError: Error(s) in loading state_dict for GatherModel:
Missing key(s) in state_dict: "lin0.weight", "lin0.bias", "set2set.lstm.weight_ih_l0", "set2set.lstm.weight_hh_l0", "set2set.lstm.bias_ih_l0", "set2set.lstm.bias_hh_l0", "message_layer.weight", "message_layer.bias", "conv.bias", "conv.edge_func.0.weight", "conv.edge_func.0.bias", "conv.edge_func.2.weight", "conv.edge_func.2.bias".
Unexpected key(s) in state_dict: "solute_pass.U_0.weight", "solute_pass.U_0.bias", "solute_pass.U_1.weight", "solute_pass.U_1.bias", "solute_pass.U_2.weight", "solute_pass.U_2.bias", "solute_pass.M_0.weight", "solute_pass.M_0.bias", "solute_pass.M_1.weight", "solute_pass.M_1.bias", "solute_pass.M_2.weight", "solute_pass.M_2.bias", "solvent_pass.U_0.weight", "solvent_pass.U_0.bias", "solvent_pass.U_1.weight", "solvent_pass.U_1.bias", "solvent_pass.U_2.weight", "solvent_pass.U_2.bias", "solvent_pass.M_0.weight", "solvent_pass.M_0.bias", "solvent_pass.M_1.weight", "solvent_pass.M_1.bias", "solvent_pass.M_2.weight", "solvent_pass.M_2.bias", "lstm_solute.weight_ih_l0", "lstm_solute.weight_hh_l0", "lstm_solute.bias_ih_l0", "lstm_solute.bias_hh_l0", "lstm_solvent.weight_ih_l0", "lstm_solvent.weight_hh_l0", "lstm_solvent.bias_ih_l0", "lstm_solvent.bias_hh_l0", "lstm_gather_solute.weight_ih_l0", "lstm_gather_solute.weight_hh_l0", "lstm_gather_solute.bias_ih_l0", "lstm_gather_solute.bias_hh_l0", "lstm_gather_solvent.weight_ih_l0", "lstm_gather_solvent.weight_hh_l0", "lstm_gather_solvent.bias_ih_l0", "lstm_gather_solvent.bias_hh_l0", "first_layer.weight", "first_layer.bias", "second_layer.weight", "second_layer.bias", "third_layer.weight", "third_layer.bias", "fourth_layer.weight", "fourth_layer.bias".
I have tried using strict=False in state_dict but I am getting this error
_IncompatibleKeys(missing_keys=['lin0.weight', 'lin0.bias', 'set2set.lstm.weight_ih_l0', 'set2set.lstm.weight_hh_l0', 'set2set.lstm.bias_ih_l0', 'set2set.lstm.bias_hh_l0', 'message_layer.weight', 'message_layer.bias', 'conv.bias', 'conv.edge_func.0.weight', 'conv.edge_func.0.bias', 'conv.edge_func.2.weight', 'conv.edge_func.2.bias'], unexpected_keys=['solute_pass.U_0.weight', 'solute_pass.U_0.bias', 'solute_pass.U_1.weight', 'solute_pass.U_1.bias', 'solute_pass.U_2.weight', 'solute_pass.U_2.bias', 'solute_pass.M_0.weight', 'solute_pass.M_0.bias', 'solute_pass.M_1.weight', 'solute_pass.M_1.bias', 'solute_pass.M_2.weight', 'solute_pass.M_2.bias', 'solvent_pass.U_0.weight', 'solvent_pass.U_0.bias', 'solvent_pass.U_1.weight', 'solvent_pass.U_1.bias', 'solvent_pass.U_2.weight', 'solvent_pass.U_2.bias', 'solvent_pass.M_0.weight', 'solvent_pass.M_0.bias', 'solvent_pass.M_1.weight', 'solvent_pass.M_1.bias', 'solvent_pass.M_2.weight', 'solvent_pass.M_2.bias', 'lstm_solute.weight_ih_l0', 'lstm_solute.weight_hh_l0', 'lstm_solute.bias_ih_l0', 'lstm_solute.bias_hh_l0', 'lstm_solvent.weight_ih_l0', 'lstm_solvent.weight_hh_l0', 'lstm_solvent.bias_ih_l0', 'lstm_solvent.bias_hh_l0', 'lstm_gather_solute.weight_ih_l0', 'lstm_gather_solute.weight_hh_l0', 'lstm_gather_solute.bias_ih_l0', 'lstm_gather_solute.bias_hh_l0', 'lstm_gather_solvent.weight_ih_l0', 'lstm_gather_solvent.weight_hh_l0', 'lstm_gather_solvent.bias_ih_l0', 'lstm_gather_solvent.bias_hh_l0', 'first_layer.weight', 'first_layer.bias', 'second_layer.weight', 'second_layer.bias', 'third_layer.weight', 'third_layer.bias', 'fourth_layer.weight', 'fourth_layer.bias'])
| The error basically says that there are weights defined by architecture you are using that are not in the state_dict, and also there are weights that are not defined by the architecture, but are present in the state_dict. Are you sure that whatever is defined by GatherModel() is the same architecture that created the state_dict in the first place? Because this error indicates that the answer is no.
| https://stackoverflow.com/questions/69489840/ |
maxpooling what should the indices be when there're multiple max values? | What to do when there are multiple values in the kernel that equals to the max? For example, for these values:
array([[0., 0.],
[0., 0.]])
The max is simply 0. What should max indices look like? should it be True's for all occurrence of max:
array([[ True, True],
[ True, True]])
Or the first occurrence of the max:
array([[ True, False],
[False, False]])
Pytorch uses the first occurrence of the max, while some source uses the other one (he uses pos = np.where(result == view, 1, 0), which essentially records 1 for all occurrence of max).
Edit: for forward prop it doesn't matter, but during backpropagation, for example, if the upstream gradient is [[1,1],[1,1]], then the gradient of current node will be different: [[1,1],[1,1]] (all occurrence) vs [[1,0],[0,0]] (first occurrence)
| After even a single back-propagation it is very unlikely that the kernel values will remain equal. So it shouldn't be a real issue, should it?
| https://stackoverflow.com/questions/69496151/ |
Why are torch.version.cuda and deviceQuery reporting different versions? | I have a doubt about the CUDA version installed on my system and being effectively used by my software.
I have done some research online but could not find a solution to my doubt.
The issue which helped me a bit in my understanding and is the most related to what I will ask below is this one.
Description of the problem:
I created a virtualenvironment with virtualenvironmentwrapper and then I installed pytorch in it.
After some time I realized I did not have CUDA installed on my system.
You can find it out by doing:
nvcc βV
If nothing is returned it means that you did not install CUDA (as far as I understood).
Therefore, I followed the instructions here
And I installed CUDA with this official link.
Then, I installed the nvidia-development-kit simply with
sudo apt install nvidia-cuda-toolkit
Now, if in my virtualenvironment I do:
nvcc -V
I get:
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Sun_Jul_28_19:07:16_PDT_2019
Cuda compilation tools, release 10.1, V10.1.243
However, if (always in the virtualenvironment) I do:
python -c "import torch; print(torch.version.cuda)"
I get:
10.2
This is the first thing I don't understand. Which version of CUDA am I using in my virtualenvironment?
Then, if I run the sample deviceQuery (from the cuda-samples folder - the samples can be installed by following this link) I get:
./deviceQuery
./deviceQuery Starting...
CUDA Device Query (Runtime API) version (CUDART static linking)
Detected 1 CUDA Capable device(s)
Device 0: "NVIDIA GeForce RTX 2080 Super with Max-Q Design"
CUDA Driver Version / Runtime Version 11.4 / 11.4
CUDA Capability Major/Minor version number: 7.5
Total amount of global memory: 7974 MBytes (8361279488 bytes)
(048) Multiprocessors, (064) CUDA Cores/MP: 3072 CUDA Cores
GPU Max Clock rate: 1080 MHz (1.08 GHz)
Memory Clock rate: 5501 Mhz
Memory Bus Width: 256-bit
L2 Cache Size: 4194304 bytes
Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384)
Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers
Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers
Total amount of constant memory: 65536 bytes
Total amount of shared memory per block: 49152 bytes
Total shared memory per multiprocessor: 65536 bytes
Total number of registers available per block: 65536
Warp size: 32
Maximum number of threads per multiprocessor: 1024
Maximum number of threads per block: 1024
Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)
Maximum memory pitch: 2147483647 bytes
Texture alignment: 512 bytes
Concurrent copy and kernel execution: Yes with 3 copy engine(s)
Run time limit on kernels: Yes
Integrated GPU sharing Host Memory: No
Support host page-locked memory mapping: Yes
Alignment requirement for Surfaces: Yes
Device has ECC support: Disabled
Device supports Unified Addressing (UVA): Yes
Device supports Managed Memory: Yes
Device supports Compute Preemption: Yes
Supports Cooperative Kernel Launch: Yes
Supports MultiDevice Co-op Kernel Launch: Yes
Device PCI Domain ID / Bus ID / location ID: 0 / 1 / 0
Compute Mode:
< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 11.4, CUDA Runtime Version = 11.4, NumDevs = 1
Result = PASS
Why is it now mentioned CUDA version 11.4? Is it because I am using the NVIDIA_CUDA-11.4_Samples I guess?
Another information is the following. If I check in my /usr/local folder I see three folders related to CUDA.
If I do:
cd /usr/local && ll | grep -i CUDA
I get:
lrwxrwxrwx 1 root root 22 Oct 7 11:33 cuda -> /etc/alternatives/cuda/
lrwxrwxrwx 1 root root 25 Oct 7 11:33 cuda-11 -> /etc/alternatives/cuda-11/
drwxr-xr-x 16 root root 4096 Oct 7 11:33 cuda-11.4/
Is that normal?
Thanks for your help.
| torch.version.cuda is just defined as a string. It doesn't query anything. It doesn't tell you which version of CUDA you have installed. It only tells you that the PyTorch you have installed is meant for that (10.2) version of CUDA. But the version of CUDA you are actually running on your system is 11.4.
If you installed PyTorch with, say,
conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia
then you should also have the necessary libraries (cudatoolkit) in your Anaconda directory, which may be different from your system-level libraries.
However, note that these depend on the NVIDIA display drivers:
Installing cudatoolkit does not install the drivers (nvidia.ko), which you need to install separately on your system.
| https://stackoverflow.com/questions/69497328/ |
How can you iterate through dict items at the same time with variable dict length? | I want to iterate through a dict that has n keys and values.
eg:
d = {0:"batched data", 1:"batched data", 2:"batched data", ..., n: "batched data"}
Since the batched data is of the pytorch DataLoader form, it is not indexable only iterable.
Thus, how can I iterate through all of the dict batched data at once:
I was thinking zip may be useful, but I was unsure how to compute this when the length is variable.
For instance if n=3:
for index, data in enumerate(zip(d[0],d[1],d[2])):
would work, but how can this be generalized for any number of dict elements?
| Looking at the output of your command:
for index, data in enumerate(zip(d[0],d[1],d[2])):
print("{} -> {}".format(index, data))
it seems to me that this will handle the generic case:
d = {0:"batched data", 1:"batched data", 2:"batched data", 3: "batched data"}
for index, data in enumerate(zip(*d.values())):
print("{} -> {}".format(index, data))
Output:
0 -> ('b', 'b', 'b', 'b')
1 -> ('a', 'a', 'a', 'a')
2 -> ('t', 't', 't', 't')
3 -> ('c', 'c', 'c', 'c')
4 -> ('h', 'h', 'h', 'h')
5 -> ('e', 'e', 'e', 'e')
6 -> ('d', 'd', 'd', 'd')
7 -> (' ', ' ', ' ', ' ')
8 -> ('d', 'd', 'd', 'd')
9 -> ('a', 'a', 'a', 'a')
10 -> ('t', 't', 't', 't')
11 -> ('a', 'a', 'a', 'a')
| https://stackoverflow.com/questions/69498875/ |
Why do torch.add and torch.einsum return different results? | t=m+n
x=torch.einsum('xyzw,xyzw->xyzw',m,n)
When I try this code, I get x that's different from t, which is surprising. Why does this happen?
| einsum is actually a product of its inputs. It's only a sum over the indexes that do not occur in the output.
So,
x=torch.einsum('xyzw,xyzw->xyzw',m,n)
is actually equivalent to
x = m * n
| https://stackoverflow.com/questions/69499333/ |
'1D target tensor expected' error when using pytorch tensorDataset class | I am wondering why this error is occuring. My hunch tells me that the tensorDataset reads the last column as being the labels, but I don't know why it would behave that way if I input a separate dataset for labels as the second argument. Also, can someone explain exactly how one-hot encoding works and how I can fix this problem because I only want one label per item?
Error: return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported
Code:
if __name__ == '__main__':
inputs_file = pd.read_csv('dataset.csv')
targets_file = pd.read_csv('labels.csv')
inputs = inputs_file.iloc[1:1001].values
targets = targets_file.iloc[1:1001].values
inputs = torch.tensor(inputs, dtype=torch.float32)
targets = torch.tensor(targets)
dataset = TensorDataset(inputs, targets)
val_size = 200
test_size = 100
train_size = len(dataset) - (val_size + test_size)
# Divide dataset into 3 unique random subsets
training_data, validation_data, test_data = random_split(dataset, [train_size, val_size, test_size])
batch_size = 50
train_loader = DataLoader(training_data, batch_size, shuffle=True, num_workers=4, pin_memory=True)
valid_loader = DataLoader(validation_data, batch_size*2, num_workers=4, pin_memory=True)
| From what I gather from the comments discussion, the error is reproduced by the following.
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset, random_split
inputs = torch.randn(999, 11, dtype=torch.float32)
targets = torch.randint(5, (999, 1), dtype=torch.long)
# you need this to adapt from pandas, but not for this example code
# inputs = torch.tensor(inputs, dtype=torch.float32)
# targets = torch.tensor(targets)
dataset = TensorDataset(inputs, targets)
val_size = 200
test_size = 100
train_size = len(dataset) - (val_size + test_size)
# Divide dataset into 3 unique random subsets
training_data, validation_data, test_data = random_split(dataset, [train_size, val_size, test_size])
batch_size = 50
train_loader = DataLoader(training_data, batch_size, shuffle=True, num_workers=4, pin_memory=True)
valid_loader = DataLoader(validation_data, batch_size*2, num_workers=4, pin_memory=True)
# guess model. More on this in a moment
model = nn.Sequential(
nn.Linear(11, 8),
nn.Linear(8, 5),
)
loss_func = nn.CrossEntropyLoss()
for features, labels in train_loader:
out = model(features)
loss = loss_func(out, labels)
print(f"{loss = }")
break
Solution 1
Add labels.squeeze(-1) to the loop body a la
for features, labels in train_loader:
out = model(features)
labels = labels.squeeze()
loss = loss_func(out, labels)
print(f"{loss = }")
break
Solution 2
Flatten your targets initially with
targets = torch.tensor(targets[:, 0])
In response to
Now I am getting this error: RuntimeError: mat1 and mat2 shapes cannot be multiplied (11x1 and 11x8) I should also add that I am using a hidden layer of size 8 and i have 5 classes
My architecture is a guess at what you're using, but as the code above is resolved by the target reshape, I'll need more to be more helpful.
Perhaps some documentation to assist? CrossEntropyLoss The example code shows the expected shape of the targets being N, rather than N, 1 or N, classes.
| https://stackoverflow.com/questions/69502691/ |
PyTorch Batch masked select implementation | How can I perform a batched masked_select?
Given:
x = torch.tensor([[1., 2., 2., 2., 3.],
[1., 2., 4., 3., 2.]])
The desired output would be:
tensor([[1., 3., 1., 1., 1.],
[1., 4., 3., 1., 1.]])
Here is a possible approach:
x = torch.tensor([[1., 2., 2., 2., 3.],
[1., 2., 4., 3., 2.]])
ones = torch.tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
masks = torch.tensor([[ True, False, False, False, True],
[ True, False, True, True, False]])
for i in range(x.size(0)):
mask = masks[i]
s = torch.masked_select(x[i], mask)
ones[i][:s.size(0)] = s
Are there any alternative solutions?
| The main issue with those kinds of problems is that the intermediate result is non-homogenous: in your batch elements will have different numbers of masked values. This is an issue if we want to apply PyTorch builtins. Here I am providing two solutions to perform this operation.
1- Using a list comprehension
Go through the batch elements, mask and pad by the appropriate amount:
>>> pad = lambda v: F.pad(v, [0, len(m)-len(v)], value=1)
>>> torch.stack([pad(r[m]) for r, m in zip(x, masks)])
tensor([[1., 3., 1., 1., 1.],
[1., 4., 3., 1., 1.]])
This is rather straightforward and similar to your approach.
2- Using torch.scatter
A vectorized alternative is to construct the correct value and index tensors such that we can apply torch.scatter and obtain the desired result. The trick here is to work with flattened tensors. From x and masks we first want to get access to nz and idx defined as:
nz: the non-masked values from x (using masks of course), i.e. we need to find:
tensor([1., 3., 1., 4., 3.])
idx: their corresponding indices in the output tensor when flattened.
tensor([ 0, 1, 5, 6, 7])
Then we can apply scatter with something like out = ones.scatter(dim=0, idx, nz) which will effectively perform: out[idx[i]] = nz[i].
To construct nz, we can directly index x with masksindices of non-zero values using on masks:
>>> nz = x[masks]
tensor([1., 3., 1., 4., 3.])
For idx it will be a little bit more tricky. We can sort the mask itself, flatten it and get the non-zero values using torch.Tensor.nonzero. When sorted, the True values end up at the beginning of each rows:
>>> idx = masks.sort(1, True).values.view(-1).nonzero()[:,0]
tensor([ 0, 1, 5, 6, 7])
Finally we can apply torch.scatter and reshape to get the desired result:
>>> torch.ones(x.numel()).scatter(0, idx, nz).view_as(x)
tensor([[1., 3., 1., 1., 1.],
[1., 4., 3., 1., 1.]])
The usage of torch.scatter here is limited since the inputs are one-dimensional. An equivalent approach is to simply to:
>>> o = torch.ones(x.numel())
>>> o[idx] = nz
>>> o.view_as(x)
Complete approach:
>>> idx = masks.sort(1, True)[0].view(-1).nonzero()[:,0]
>>> torch.ones(x.numel()).scatter(0, idx, x[masks]).view_as(x)
tensor([[1., 3., 1., 1., 1.],
[1., 4., 3., 1., 1.]])
| https://stackoverflow.com/questions/69503156/ |
How can I solve the wrong shape in DataLoader? | I have a text dataset that I want to use for a GAN and it should turn to onehotencode and this is how I Creating a Custom Dataset for my files
class Dataset2(torch.utils.data.Dataset):
def __init__(self, list_, labels):
'Initialization'
self.labels = labels
self.list_IDs = list_
def __len__(self):
'Denotes the total number of samples'
return len(self.list_IDs)
def __getitem__(self, index):
'Generates one sample of data'
# Select sample
mylist = self.list_IDs[index]
# Load data and get label
X = F.one_hot(mylist, num_classes=len(alphabet))
y = self.labels[index]
return X, y
It is working well and every time I call it, it works just fine but the problem is when I use DataLoader and try to use it, its shape is not the same as it just came out of the dataset, this is the shape that came out of the dataset
x , _ = dataset[1]
x.shape
torch.Size([1274, 22])
and this is the shape that came out dataloader
dataloader = DataLoader(dataset, batch_size=64, shuffle=True)
one = []
for epoch in range(epochs):
for i, (real_data, _) in enumerate(dataloader):
one.append(real_data)
one[3].shape
torch.Size([4, 1274, 22])
this 4 is number of samples in my data but it should not be there, how can I fix this problem?
| You confirmed you only had four elements in your dataset. You have wrapped your dataset with a data loader with batch_size=64 which is greater than 4. This means the dataloader will only output a single batch containing 4 elements.
In turn, this means you only append a single element per epoch, and one[3].shape is a batch (the only batch of the data loader), shaped (4, 1274, 22).
| https://stackoverflow.com/questions/69514847/ |
Increasing num of layers in LSTM increases the input dimensions in Pytorch? | This is my LSTM model and I am finding a peculiar problem while training it.
class LSTM1(nn.Module):
def __init__(self, num_classes, input_size, hidden_size, num_layers, seq_length,drop_prob=0.0):
super(LSTM1, self).__init__()
self.num_classes = num_classes #number of classes
self.num_layers = num_layers #number of layers
self.input_size = input_size #input size
self.hidden_size = hidden_size #hidden state
self.seq_length = seq_length #sequence length
self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size,
num_layers=num_layers, dropout=drop_prob,batch_first=True) #lstm
# self.dropout = nn.Dropout(drop_prob)
# self.fc_1 = nn.Linear(hidden_size, num_classes)
self.fc_1 = nn.Linear(hidden_size, 64) #fully connected 1
self.fc = nn.Linear(64, num_classes) #fully connected last layer
self.relu = nn.ReLU()
def forward(self,x):
# h_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).to(device) #hidden state
# c_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).to(device) #internal state
# Propagate input through LSTM
output, (hn, cn) = self.lstm(x) #lstm with input, hidden, and internal state
hn = hn.view(-1, self.hidden_size) #reshaping the data for Dense layer next
#out = self.dropout(hn)
out = self.relu(hn)
out = self.fc_1(out) #first Dense
out = self.relu(out) #relu
out = self.fc(out) #Final Output
out = self.relu(out) #relu
return out
My training data has these dimensions where the first one is the input and second the labels
Training Shape torch.Size([8051, 1, 201]) torch.Size([8051, 1])
When I train with num_layers variable = 1 for the LSTM layer it works fine.
However, when I increase the num_layers to 2 I get the error which says
Training Shape torch.Size([8051, 1, 201]) torch.Size([8051, 1])
Testing Shape torch.Size([4930, 1, 201]) torch.Size([4930, 1])
C:\Users\adity\miniconda3\envs\pytorch3\lib\site-packages\torch\nn\modules\loss.py:528: UserWarning: Using a target size (torch.Size([8051, 1])) that is different to the input size (torch.Size([16102, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
return F.mse_loss(input, target, reduction=self.reduction)
Traceback (most recent call last):
File "C:\Users\adity\OneDrive - Louisiana State University\Documents\CSC 7343 HW\hw1.py", line 135, in <module>
loss = criterion(outputs.to(device), y_train_tensors.to(device))
File "C:\Users\adity\miniconda3\envs\pytorch3\lib\site-packages\torch\nn\modules\module.py", line 1051, in _call_impl
return forward_call(*input, **kwargs)
File "C:\Users\adity\miniconda3\envs\pytorch3\lib\site-packages\torch\nn\modules\loss.py", line 528, in forward
return F.mse_loss(input, target, reduction=self.reduction)
File "C:\Users\adity\miniconda3\envs\pytorch3\lib\site-packages\torch\nn\functional.py", line 3089, in mse_loss
expanded_input, expanded_target = torch.broadcast_tensors(input, target)
File "C:\Users\adity\miniconda3\envs\pytorch3\lib\site-packages\torch\functional.py", line 73, in broadcast_tensors
return _VF.broadcast_tensors(tensors) # type: ignore[attr-defined]
RuntimeError: The size of tensor a (16102) must match the size of tensor b (8051) at non-singleton dimension 0
When I changed layers to 3 the error says the size of tensor should be 24153.
Why is the input dimensions changing when I increase num_layers?
| The issue is that you are flattening hn, according to the documentation page, its shape is (D*num_layers, N, Hout), i.e. it depends on the number of hidden layers. So you will either have to change the fully connected that is following or only take the last hidden state of your LSTM.
| https://stackoverflow.com/questions/69516225/ |
How to delete tensors from pytorch graph? | I'm doing predictions on images for object detection in a for loop.
I've actually ran into the same issue with tensorflow and hoped I could solve it with pytorch.
At least now it seems I have found out what the issue is (naively assuming it's the same for tensorflow)
I predict like this
model = detection.fasterrcnn_resnet50_fpn(pretrained=True,
progress=True,pretrained_backbone=True).to(DEVICE)
for i in tqdm(range(train.shape[0])):
image = cv2.imread(train_img_paths[i])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = image.transpose((2, 0, 1))
image = image / 255.0
image = np.expand_dims(image, axis=0)
image = torch.FloatTensor(image)
image = image.to(DEVICE)
predictions = model(image)[0]
Now through the garbage collector I found that each and every image stays in the graph.
Is there away to avoid it?
I have not been able to use dataloader or dataset with the detection models (same with tensorflow hub)
| Don't forget when you're doing testing to turn gradient accumulation off. You can do this by either wrapping your code like:
with torch.no_grad():
model.eval()
out = model(x)
or if your code is a function, using a decorator to do the same thing:
@torch.no_grad()
def model_proc(model,x):
model.eval()
return model(x)
| https://stackoverflow.com/questions/69516766/ |
Pytorch argmax across multiple dimensions | I have a 4D tensor, and I would like to get the argmax across the last two dimensions. torch.argmax only accepts integers as the "dim" argument, not tuples.
How can I accomplish this?
Here's what I had in mind, but I can't figure out how to match up the dimensions of my two "indices" tensors. original_array is shape [1, 512, 37, 59].
max_vals, indices_r = torch.max(original_array, dim=2)
max_vals, indices_c = torch.max(max_vals, dim=2)
indices = torch.hstack((indices_r, indices_c))
| As others mentioned, its best to flatten the last two dimensions and apply argmax
original_array = torch.rand(1, 512, 37, 59)
original_flatten = original_array.view(1, 512, -1)
_, max_ind = original_flatten.max(-1)
.. you will get the linear index of the maximum values. In case you want the 2D indecies of the maximum values, you can do "unflatten" the indecies using the number of columns
# 59 is the number of columns for the (37, 59) part
torch.stack([max_ind // 59, max_ind % 59], -1)
this will give you a (1, 512, 2) where each last 2 dim contains 2D coordinates.
| https://stackoverflow.com/questions/69518359/ |
How to Define Model in Native Pytorch Format and Import Into LightningModule Without Copy and Pasting? | Let's say I have a native pytorch model like this
class NormalAutoEncoder(nn.Module)):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(nn.Linear(28 * 28, 64), nn.ReLU(), nn.Linear(64, 3))
self.decoder = nn.Sequential(nn.Linear(3, 64), nn.ReLU(), nn.Linear(64, 28 * 28))
def forward(self, x):
# in lightning, forward defines the prediction/inference actions
embedding = self.encoder(x)
return embedding
How can I have the __init__ and forward functions (basically, the whole network) into a pytorch lighting module without copying and pasting?
| Simple. Make use of Python's inheritance mechanism.
If the following is a native PyTorch module
class NormalAutoEncoder(nn.Module):
def __init__(self):
super().__init__()
self.encoder = ...
self.decoder = ...
def forward(self, x):
embedding = ...
return embedding
Then have your new LightningAutoEncoder that also inherits from NormalAutoEncoder
class LightningAutoEncoder(LightningModule, NormalAutoEncoder):
def __init__(self, ...):
LightningModule.__init__(self) # only LightningModule's init
NormalAutoEncoder.__init__(self, ...) # this basically executes __init__() of the NormalAutoEncoder
def forward(self, x):
# offloads its execution to NormalAutoEncoder's forward() method
return NormalAutoEncoder.forward(self, x)
That's it. No copy-pasting.
| https://stackoverflow.com/questions/69519135/ |
How to specify the axis over which to get the elements in PyTorch | I was looking for an answer around SO, but tbh, don't even know how to phrase a question.
Given a tensor, how do I get indices over a specified axis
Here is a simple example
indices = torch.tensor([2, 4, 5])
# Depending on the context I need either
y = x[indices]
# Or
y = x[:, indices]
# Or any other axis
y = x[:, :, :, indices]
Here is a usecase where I need this behavior
def remove_weaklings(x: Tensor, percentage: float, axis: int) -> Tensor:
all_axes = set(range(x.ndim)) - set([axis])
y = x
# Sumup over all other axes
for a in all_axes:
y = y.sum(axis=a, keepdim=True)
y = y.squeeze()
# Get the sorted list
_, idx = torch.sort(y)
# Get only a fraction of the list
idx = idx[:int(percentage * len(idx))]
# Get the indices over some axis
# !!! This part not sure how to solve !!!
return x.get_over_axis(axis=axis, indices=idx)
| I think you are looking for topk:
def remove_weaklings(x, percentage, axis):
k = int(percentage * x.shape[axis])
return torch.topk(x, k, dim=axis)
If you want a more generic solution, you can use numpy's slicing:
def get_over_axis(x, indices, axis):
i = []
for d_ in range(x.dim()):
if d_ == axis:
i.append(indices)
else:
i.append(np.s_[:])
return x[tuple(i)]
| https://stackoverflow.com/questions/69522798/ |
pytorch - Model_heplers.py in is_overridden > raise ValueError(βExpected a parentβ) | I am running on a new remote server a code that used to work on another remote server. I think I setup things in the same way, but when I run my training script, I get this error:
Traceback (most recent call last):
File "/home/andrea/code/vertikal-machine-learning/source/model/hss_bearing_mk2/hss_bearing_mk2/models/train_model.py", line 144, in <module>
seq_len=seq_len, mname=mname)
File "/home/andrea/code/vertikal-machine-learning/source/model/hss_bearing_mk2/hss_bearing_mk2/models/pytorch_models.py", line 321, in train_test
trainer.fit(model, datamodule=dm)
File "/home/andrea/anaconda3/envs/hss_bearing_mk2/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 552, in fit
self._run(model)
File "/home/andrea/anaconda3/envs/hss_bearing_mk2/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 849, in _run
self.config_validator.verify_loop_configurations(model)
File "/home/andrea/anaconda3/envs/hss_bearing_mk2/lib/python3.7/site-packages/pytorch_lightning/trainer/configuration_validator.py", line 34, in verify_loop_configurations
self.__verify_train_loop_configuration(model)
File "/home/andrea/anaconda3/envs/hss_bearing_mk2/lib/python3.7/site-packages/pytorch_lightning/trainer/configuration_validator.py", line 49, in __verify_train_loop_configuration
has_training_step = is_overridden("training_step", model)
File "/home/andrea/anaconda3/envs/hss_bearing_mk2/lib/python3.7/site-packages/pytorch_lightning/utilities/model_helpers.py", line 45, in is_overridden
raise ValueError("Expected a parent")
ValueError: Expected a parent
Here is the part of code that looks buggy for some reason:
model = get_model(mname=mname)
dm = DataModule(
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
X_test=X_test,
y_test=y_test,
keys_train=keys_train,
keys_val=keys_val,
keys_test=keys_test,
seq_len=seq_len,
batch_size=batch_size,
num_workers=4
)
# trainer.logger_connector.callback_metrics
trainer.fit(model, datamodule=dm)
Is it something related to environment setup? Something overridden by something something??
Can someone point me in the right direction?
EDIT: I tried to run my project locally in a newly created environment and I have the same error.
EDIT 2: My DataModule inherits from LightningDataModule
class DataModule(pl.LightningDataModule):
| The problem was that model was inheriting from nn.Module instead of from pl.LightningModule
| https://stackoverflow.com/questions/69526806/ |
How to use soft labels in computer vision with PyTorch? | I have an image dataset with soft labels (i.e. the images don't belong to a single class, but rather I have a probability distribution saying that there's a 66% chance this image belong in one class and 33% chance it belongs in some other class).
I am struggling to figure out how to setup my PyTorch code to allow this to be represented by the model and outputted correctly. The probabilities are saved in a csv file. I have looked at the PyTorch docs and other resources which mention the cross entropy loss function but I am still unclear how to import the data successfully and make use of soft labels.
| What you are trying to solve is a multi-label classification task, i.e. instances can be classified with more than one label at a time. You cannot use torch.CrossEntropyLoss since it only allows for single-label targets. So you have two options:
Either use a soft version of the nn.CrossEntropyLoss function, this can be done by implementing the loss by hand allowing for soft targets. You can find such implementation on Soft Cross Entropy in PyTorch.
Or consider the task a multiple "independent" binary classification tasks, in this case, you would use nn.BCEWithLogitsLoss (this layer contains a sigmoid function).
| https://stackoverflow.com/questions/69530476/ |
How can I download to my pc an image dataset after loading it into a dataloader in pytorch? | I've been following this article:
https://github.com/moein-shariatnia/Deep-Learning/tree/main/Image%20Colorization%20Tutorial
And I have a problem. I'm trying to download the images I have loaded into the pytorch dataloader, but since they are chosen randomly from a larger dataset I can't figure it out.
How can I download the exact images that I've loaded into "train_dl" to my PC (as a folder) after they are being chosen? I have already trained my model on these exact images, so I'll need them for future work.
| Dataloaders should have a dataset attribute which you can use to find the paths in your code
In the code:
class ColorizationDataset(Dataset):
def __init__(self, paths, split='train'):
...
self.split = split
self.size = SIZE
self.paths = paths #<<<<- IMPORTANT LINE HERE
def __getitem__(self, idx):
...
def __len__(self):
return len(self.paths)
def make_dataloaders(batch_size=16, n_workers=4, pin_memory=True, **kwargs): # A handy function to make our dataloaders
dataset = ColorizationDataset(**kwargs)
dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=n_workers,
pin_memory=pin_memory)
return dataloader
So, to get the items from your dataloader you can run:
train_paths = train_dl.dataset.paths
You can loop through this list to save the images individually (not recommended) or just save it as text with the train/val/test splits as separate files.
| https://stackoverflow.com/questions/69532024/ |
Indexing one element per row in PyTorch matrix | Let price be a PyTorch tensor with shape (num_days, num_products).
Let purchased_product_by_day be an integer tensor with shape (num_days,), with values in range(num_products).
Intuitively, price lists the price, for each day, of each product, and purchased_product_by_day are the indices of purchased products, one per day.
To obtain a tensor containing the expense per day, I can write
price[list(range(num_days)), purchased_product_by_day]
but this iterates over days at the Python level. I would like to obtain the same tensor on the C level.
I tried
price[:, purchased_product_by_day]
but that does not work, being equivalent to indexing each row by purchased_product_by_day for each day and stacking the results.
Is there a way to do that without iteration at the Python level?
| Based on Row-wise Element Indexing in PyTorch for C++, the solution in Python is
price.gather(1, purchased_product_by_day.unsqueeze(1)).squeeze()
| https://stackoverflow.com/questions/69533202/ |
Working of numpy array to torch tensor conversion | I want to know how the conversion from a NumPy array to a tensor happens in PyTorch as well as Tensorflow. Does it create a copy of the entire array or there is some in-place mechanism?
Secondly, how to clear the memory that was used earlier by the NumPy array that was later converted into a tensor.
|
When device is CPU in PyTorch, PyTorch and Numpy uses the same internal representation of n-dimensional arrays in memory, so when converted from a Numpy array to a PyTorch tensor no copy operation is performed, only the way they are represented internally is changed. Refer here.
Python garbage collector uses reference counts for clearing unused memory similar to shared pointers in C++.
| https://stackoverflow.com/questions/69535146/ |
PyTorch CUDA: "to(device)" vs "device=device" for tensors? | I found a somewhat similar question here What is the difference between model.to(device) and model=model.to(device)?, but I would like to check again if the same applies to my example:
Using .to(self.device)
mask = torch.tril(torch.ones(len_q, len_k)).type(torch.BoolTensor).to(self.device)`
and
Using device=self.device
mask = torch.tril(torch.ones((trg_len, trg_len), device = self.device)).bool()
Are they both accomplishing the same thing - ensuring that mask goes to the GPU?
| The torch.Tensor.to function will make a copy of your tensor on the destination device. While setting the device option on initialization will place it there on init, so there is no copy involved.
So in your case you would rather do:
>>> mask = torch.tril(torch.ones(len_q, len_k), device=self.device)
But to give an answer to your question, both have the effect of placing mask on self.device. The only difference is that in the former you will have a copy of your data on both devices.
The same can be said for torch.Tensor.bool vs. initializing with dtype:
>>> torch.randint(0, 1, (10,)).bool()
Will make a copy, while the following won't:
>>> torch.randint(0, 1, (10,), dtype=torch.bool)
However, torch.tril doesn't provide a dtype option, so it is not relevant here.
| https://stackoverflow.com/questions/69537802/ |
How to assign numbers to characters in dictionary? | I have a sequence generation and in the final result, I have a tensor that contains my sequence, I have that tensor which is one_hot_encoded and an alphabet and I try to inverse that one_hot_encoded to characters, I try dictionary and argmax function but I could not find any solution that can do it all tensor at once and most of the answers do just one character
int_to_char = dict((i, c) for i, c in enumerate(alphabet))
inverted = int_to_char[argmax(onehot_encoded[0])]
print(inverted)
this is how I use argmax and its answer
a.argmax(-1)
tensor([10, 4, 17, ..., 19, 16, 20])
these are alphabet and expected result
alphabet = ['A', 'C', 'D', 'E', 'F', 'G','H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y', '*', 'X']
data = "MFVFLVLLPLVSSQCVNLTTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFSNVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASTEKSNIIRGWIFGTTLDSKTQSLLIVNNATNVVIKVCEFQFCNDPFLGVYYHKNNKSLMESEFRVYSSANNCTFEYVSQPFLMDLEGKQGNFKNXREFVFKNIDGYFKIYSKHTPINLVRDLPQGFSALEPLVDLPIGINITRFQTLLALHRSYLTPGDSSSGWTAGAAAYYVGYLQPRTFLLKYNENGTITDAVDCALDPLSETKCTLKSFTVEKGIYQTSNFRVQPTESIVRFPNITNLCPFGEVFNATRFASVYAWNRKRISNCVADYSVLYNSASFSTFKCYGVSPTKLNDLCFTNVYADSFVIRGDEVRQIAPGQTGKIADYNYKLPDDFTGCVIAWNSNNLDSKVGGNYNYLYRLFRKSNLKPFERDISTEIYQAGSTPCNGVKGFNCYFPLQSYGFQPTNGVGYQPYRVVVLSFELLHAPATVCGPKKSTNLVKNKCVNFNFNGLTGTGVLTESNKKFLPFQQFGRDIADTTDAVRDPQTLEILDITPCSFGGVSVITPGTNTSNQVAVLYQGVNCTEVPVAIHADQLTPTWRVYSTGSNVFQTRAGCLIGAEHVNNSYECDIPIGAGICASYQTQTNSPRRARSVASQSIIAYTMSLGAENSVAYSNNSIAIPTNFTISVTTEILPVSMTKTSVDCTMYICGDSTECSNLLLQYGSFCTQLNRALTVIAVEQDKNTQEVFAQVKQIYKTPPIKDFGGFNFSQILPDPSKPSKRSFIEDLLFNKVTLADAGFIKQYGDCLGDIAARDLICAQKFNGLTVLPPLLTDEMIAQYTSALLAGTITSGWTFGAGAALQIPFAMQMAYRFNGIGVTQNVLYENQKLIANQFNSAIGKIQDSLSSTASALGKLQDVVNQNAQALNTLVKQLSSNFGAISSVLNDILSRLDKVEAEVQIDRLITGRLQSLQTYVTQQLIRAAEIRASANLAATKMSECVLGQSKRVDFCGKGYHLMSFPQSAPHGVVFLHVTYVPAQEKNFTTAPAICHDGKAHFPREGVFVSNGTHWFVTQRNFYEPQIITTDNTFVSGNCDVVIGIVNNTVYDPLQPELDSFKEELDKYFKNHTSPDVDLGDISGINASVVNIQKEIDRLNEVAKNLNESLIDLQELGKYEQYIKWPWYIWLGFIAGLIAIVMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEPVLKGVKLHYT*"
I want to turn this tensor into characters based on an alphabet, How can I do that?
| Given a sequence of ints, here is a sample:
encoded = torch.tensor([10, 4, 17, 19, 16, 20])
You could apply a list comprehension on your sequence, accessing alphabet to extract the letter corresponding to each index:
>>> ''.join(alphabet[e] for e in encoded)
MFVYT*
Given a str sequence of letters:
data = 'MFVFLVLLPLVSSQCVNLTTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFSNVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASTEKSNIIRGWIFGTTLDSKTQSLLIVNNATNVVIKVCEFQFCNDPFLGVYYHKNNKSLMESEFRVYSSANNCTFEYVSQPFLMDLEGKQGNFKNXREFVFKNIDGYFKIYSKHTPINLVRDLPQGFSALEPLVDLPIGINITRFQTLLALHRSYLTPGDSSSGWTAGAAAYYVGYLQPRTFLLKYNENGTITDAVDCALDPLSETKCTLKSFTVEKGIYQTSNFRVQPTESIVRFPNITNLCPFGEVFNATRFASVYAWNRKRISNCVADYSVLYNSASFSTFKCYGVSPTKLNDLCFTNVYADSFVIRGDEVRQIAPGQTGKIADYNYKLPDDFTGCVIAWNSNNLDSKVGGNYNYLYRLFRKSNLKPFERDISTEIYQAGSTPCNGVKGFNCYFPLQSYGFQPTNGVGYQPYRVVVLSFELLHAPATVCGPKKSTNLVKNKCVNFNFNGLTGTGVLTESNKKFLPFQQFGRDIADTTDAVRDPQTLEILDITPCSFGGVSVITPGTNTSNQVAVLYQGVNCTEVPVAIHADQLTPTWRVYSTGSNVFQTRAGCLIGAEHVNNSYECDIPIGAGICASYQTQTNSPRRARSVASQSIIAYTMSLGAENSVAYSNNSIAIPTNFTISVTTEILPVSMTKTSVDCTMYICGDSTECSNLLLQYGSFCTQLNRALTVIAVEQDKNTQEVFAQVKQIYKTPPIKDFGGFNFSQILPDPSKPSKRSFIEDLLFNKVTLADAGFIKQYGDCLGDIAARDLICAQKFNGLTVLPPLLTDEMIAQYTSALLAGTITSGWTFGAGAALQIPFAMQMAYRFNGIGVTQNVLYENQKLIANQFNSAIGKIQDSLSSTASALGKLQDVVNQNAQALNTLVKQLSSNFGAISSVLNDILSRLDKVEAEVQIDRLITGRLQSLQTYVTQQLIRAAEIRASANLAATKMSECVLGQSKRVDFCGKGYHLMSFPQSAPHGVVFLHVTYVPAQEKNFTTAPAICHDGKAHFPREGVFVSNGTHWFVTQRNFYEPQIITTDNTFVSGNCDVVIGIVNNTVYDPLQPELDSFKEELDKYFKNHTSPDVDLGDISGINASVVNIQKEIDRLNEVAKNLNESLIDLQELGKYEQYIKWPWYIWLGFIAGLIAIVMVTIMLCCMTSCCSCLKGCCSCGSCCKFDEDDSEPVLKGVKLHYT'
You could apply a list comprehension on your sequence, this time retrieving the index in alphabet for each letter:
>>> encoding = [alphabet.index(x) for x in data]
Alternatively you can use map:
>>> encoding = map(lambda x: alphabet.index(x), data)
| https://stackoverflow.com/questions/69538073/ |
Correct way to compute VGG features for Perceptual loss | While computing VGG Perceptual loss, although I have not seen, I feel it is alright to wrap the computation of VGG features for the GT image inside torch.no_grad().
So basically I feel the following will be alright,
with torch.no_grad():
gt_vgg_features = self.vgg_features(gt)
nw_op_vgg_features = self.vgg_features(nw_op)
# Now compute L1 loss
or one should use,
gt_vgg_features = self.vgg_features(gt)
nw_op_vgg_features = self.vgg_features(nw_op)
In both approaches requires_grad for VGG parameters is set False and VGG put in eval() mode.
The first approach will save a lot of GPU resources and feel should be numerically equal to the second one as no backpropagation is required through GT images. But in most implementations, I find the second approach used for computing VGG perceptual loss.
So which option we should go for implementing VGG perceptual loss in PyTorch?
| The first way:
with torch.no_grad():
gt_vgg_features = self.vgg_features(gt)
nw_op_vgg_features = self.vgg_features(nw_op)
Although VGG is in eval mode and its parameters are kept fix, you still need to propagate gradients through it from the loss on the features to the output nw_op.
However, there's no reason to compute these gradients w.r.t gt.
| https://stackoverflow.com/questions/69539176/ |
How to concatenate along a dimension of a single pytorch tensor? | I wrote a custom pytorch Dataset and the __getitem__() function return a tensor with shape (250, 150), then I used DataLoader to generate a batch of data with batch size 10. My intension was to have a batch with shape (2500, 150) as concatenation of these 10 tensors along dimension 0, but the output of DataLoader has shape (10, 250, 150). How do I transform the output of DataLoader into shape (2500, 150) as concatenation along dimension 0?
| PyTorch DataLoader will always add an extra batch dimension at 0th index. So, if you get a tensor of shape (10, 250, 150), you can simple reshape it with
# x is of shape (10, 250, 150)
x_ = x.view(-1, 150)
# x_ is of shape (2500, 150)
Or, to be more correct, you can supply a custom collator to your dataloader
def custom_collate(batch):
# each item in batch is (250, 150) as returned by __getitem__
return torch.cat(batch, 0)
dl = DataLoader(dataset, batch_size=10, collate_fn=custom_collate, ...)
This will create properly sized tensor right in the dataloder itself, so no need for any post-processing with .view().
| https://stackoverflow.com/questions/69541564/ |
PyTorch `torch.no_grad` vs `torch.inference_mode` | PyTorch has new functionality torch.inference_mode as of v1.9 which is "analogous to torch.no_grad... Code run under this mode gets better performance by disabling view tracking and version counter bumps."
If I am just evaluating my model at test time (i.e. not training), is there any situation where torch.no_grad is preferable to torch.inference_mode? I plan to replace every instance of the former with the latter, and I expect to use runtime errors as a guardrail (i.e. I trust that any issue would reveal itself as a runtime error, and if it doesn't surface as a runtime error then I assume it is indeed preferable to use torch.inference_mode).
More details on why inference mode was developed are mentioned in the PyTorch Developer Podcast.
| Yes, torch.inference_mode is indeed preferable to torch.no_grad in all situations where inference mode does not throw a runtime error. Check here and here.
| https://stackoverflow.com/questions/69543907/ |
How padding works in PyTorch | Normally if I understood well PyTorch implementation of the Conv2D layer, the padding parameter will expand the shape of the convolved image with zeros to all four sides of the input. So, if we have an image of shape (6,6) and set padding = 2 and strides = 2 and kernel = (5,5), the output will be an image of shape (1,1). Then, padding = 2 will pad with zeroes (2 up, 2 down, 2 left and 2 right) resulting in a convolved image of shape (5,5)
However when running the following script :
import torch
from torch import nn
x = torch.ones(1,1,6,6)
y = nn.Conv2d(in_channels= 1, out_channels=1,
kernel_size= 5, stride = 2,
padding = 2,)(x)
I got the following outputs:
y.shape
==> torch.Size([1, 1, 3, 3]) ("So shape of convolved image = (3,3) instead of (5,5)")
y[0][0]
==> tensor([[0.1892, 0.1718, 0.2627, 0.2627, 0.4423, 0.2906],
[0.4578, 0.6136, 0.7614, 0.7614, 0.9293, 0.6835],
[0.2679, 0.5373, 0.6183, 0.6183, 0.7267, 0.5638],
[0.2679, 0.5373, 0.6183, 0.6183, 0.7267, 0.5638],
[0.2589, 0.5793, 0.5466, 0.5466, 0.4823, 0.4467],
[0.0760, 0.2057, 0.1017, 0.1017, 0.0660, 0.0411]],
grad_fn=<SelectBackward>)
Normally it should be filled with zeroes. I'm confused. Can anyone help please?
| The input is padded, not the output. In your case, the conv2d layer will apply a two-pixel padding on all sides just before computing the convolution operation.
For illustration purposes,
>>> weight = torch.rand(1, 1, 5, 5)
Here we apply a convolution with padding=2:
>>> x = torch.ones(1,1,6,6)
>>> F.conv2d(x, weight, stride=2, padding=2)
tensor([[[[ 5.9152, 8.8923, 6.0984],
[ 8.9397, 14.7627, 10.8613],
[ 7.2708, 12.0152, 9.0840]]]])
And we don't use any padding but instead apply it ourselves on the input:
>>> x_padded = F.pad(x, (2,)*4)
tensor([[[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]]])
>>> F.conv2d(x_padded, weight, stride=2)
tensor([[[[ 5.9152, 8.8923, 6.0984],
[ 8.9397, 14.7627, 10.8613],
[ 7.2708, 12.0152, 9.0840]]]])
| https://stackoverflow.com/questions/69544256/ |
forward() not overridden in implementation of nn.Module in an example | In this example, we see the following implementation of nn.Module:
class Net(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super().__init__()
self.conv1 = GCNConv(in_channels, hidden_channels)
self.conv2 = GCNConv(hidden_channels, out_channels)
def encode(self, x, edge_index):
x = self.conv1(x, edge_index).relu()
return self.conv2(x, edge_index)
def decode(self, z, edge_label_index):
return (z[edge_label_index[0]] * z[edge_label_index[1]]).sum(dim=-1)
def decode_all(self, z):
prob_adj = z @ z.t()
return (prob_adj > 0).nonzero(as_tuple=False).t()
However, in the docs we have that 'forward(*input)' "Should be overridden by all subclasses."
Why is that not then the case in this example?
| This Net module is meant to be used via two separate interfaces encoder and decode, at least it seems so... Since it doesn't have a forward implementation, then yes it is improperly inheriting from nn.Module. However, the code is still "valid", and will run properly but may have some side effects if you are using forward hooks.
The standard way of performing inference on a nn.Module is to call the object, i.e. calling the __call__ function. This __call__ function is implemented by the parent class nn.Module and will in turn do two things:
handle forward hooks before or after the inference call
call the forward function of the class.
The __call__ function acts as a wrapper of forward.
So for this reason the forward function is expected to be overridden by the user-defined nn.Module. The only caveat of violating this design pattern is that it will effectively ignore any hooks applied on the nn.Module.
| https://stackoverflow.com/questions/69546535/ |
Doing inference using pytorch saved weights in .tar file using django | I am doing a machine learning project where I need to display the predictions on a webpage. The webpage is build using Django. I have predictions function and the weights of the model but how to integrate the predictions function, model, and weights in the Django code and do predictions.
My prediction code
def predicting(model, device, loader):
model.eval()
total_preds = torch.Tensor()
total_labels = torch.Tensor()
with torch.no_grad():
for solute_graphs, solvent_graphs, solute_lens, solvent_lens in loader:
outputs, i_map = model(
[solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device),
torch.tensor(solvent_lens).to(device)])
print(outputs)
total_preds = torch.cat((total_preds, outputs.cpu()), 0)
return total_preds.numpy().flatten()
I have saved the weights in .tar file so I need to run the model while loading the weights for prediction. I have no idea where to keep my PyTorch model and the weights to do inference using Django. please help.
| Deploy a PyTorch deep learning classifier at Heroku using Django in 30 minutes
https://www.youtube.com/watch?v=MLk2We1rJPs
Using PyTorch Inside a Django App:
https://stefanbschneider.github.io/blog/pytorch-django
I hope this will help you get started!!!
| https://stackoverflow.com/questions/69548517/ |
Deep learning with PyTorch:Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got 2-dimensional input of size [32, 1728] instead | I am using deep learning with PyTorch to do some image classification. Whenever I try to train my model, the function forward fails. Could somebody explain me what are the reasons why the input size is wrong and how to fix this, please?
This is the code for my model, as well as my training loss and my optimizer:
model.fc = nn.Sequential(
nn.Conv2d(1, 6, 9, padding=0), # 64040
nn.ReLU(), #
nn.AvgPool2d(2, stride=2), # max 62020
nn.Conv2d(6, 16, 11, padding=0), # 161010
nn.ReLU(), # 161010
nn.AvgPool2d(2, stride=2), # 1655 = 400
nn.Flatten(),
nn.Linear(400, 200),
nn.ReLU(),
nn.Linear(200, 100),
nn.ReLU(),
nn.Linear(100, 3),
nn.LogSoftmax(dim=1))
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.fc.parameters(), lr=0.003)
model.to(device)
This is the validation function:
def validation(model, val_dataloader, criterion):
val_loss = 0
accuracy = 0
for images, labels in iter(val_dataloader):
images, labels = images.to('cuda'), labels.to('cuda')
output = model.forward(images)
val_loss += criterion(output, labels).item()
probabilities = torch.exp(output)
equality = (labels.data == probabilities.max(dim=1)[1])
accuracy += equality.type(torch.FloatTensor).mean()
return val_loss, accuracy
Finally, this is my training function:
def train_classifier():
epochs = 10
steps = 0
print_every = 40
model.to('cuda')
for e in range(epochs):
model.train()
running_loss = 0
for images, labels in iter(train_dataloader):
images = images.view(images.shape[0], -1) #this flattens it?
steps += 1
images, labels = images.to('cuda'), labels.to('cuda')
optimizer.zero_grad()
# training
output = model.forward(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
model.eval()
# Turn off gradients for validation, saves memory and computations
with torch.no_grad():
validation_loss, accuracy = validation(model, validate_loader, criterion)
print("Epoch: {}/{}.. ".format(e+1, epochs),
"Training Loss: {:.3f}.. ".format(running_loss/print_every),
"Validation Loss: {:.3f}.. ".format(validation_loss/len(validate_loader)),
"Validation Accuracy: {:.3f}".format(accuracy/len(validate_loader)))
running_loss = 0
model.train()
train_classifier()
Error code:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-32-60a435d940e1> in <module>()
49 model.train()
50
---> 51 train_classifier()
5 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight, bias)
438 _pair(0), self.dilation, self.groups)
439 return F.conv2d(input, weight, bias, self.stride,
--> 440 self.padding, self.dilation, self.groups)
441
442 def forward(self, input: Tensor) -> Tensor:
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got 2-dimensional input of size [32, 1728] instead
Any help is appreciated! Thank you!
| Your network has both Conv2d layers as well as fully connected Linear layers - this is the source of the problem: Conv2d expects its inputs to be 4D: batch-channel-height-width. On the other hand, nn.Linear works of "flattened" features: batch-channel. Therefore, you need to "flatten" your data, but not before applying the network, but rather during its processing, where you have a Flattening layer.
| https://stackoverflow.com/questions/69549282/ |
How to convert the prediction of pytorch into normal text | I have a PyTorch model and i am doing prediction on it. After doing prediction i am getting the output as
tensor([[-3.4333]], grad_fn=<AddmmBackward>)
But i need it as normal integer -3.4333. How can i do it.
| Call .item on your tensor to convert it to a standard python number.
| https://stackoverflow.com/questions/69554229/ |
Initializing a differentiable param in pytorch | I'm trying to define a set of new parameters B in a pytorch model. I would like to initialize the new params with current weights of the model W.
Question: I want these params B to be differentiable, but autograd should not track their history to W (so B should have a new memory with no reference to W). What is the correct function to use?
I understand B = W.clone() will result in autograd tracking history of B to W while differentiating. Also I understand that B = W.detach().clone() will not be differentiable.
EDIT:
I believe B = nn.Parameter(W.detach().clone()) should be the correct function. Is this correct and if yes, is this the simplest function to use?
| There are several ways to do it and one of them is
B = W.clone().detach()
Another elegant one comes to my mind is
B = torch.new_tensor(x, requires_grad=True)
which is much more readable and the doc says they are equivalent.
If you want it as a parameter to nn.Module, of course wrap it with
self.B = nn.Parameter(...)
| https://stackoverflow.com/questions/69557333/ |
What is the correct way to maximize one loss and minimize another during NN training? | I have a simple NN:
import torch
import torch.nn as nn
import torch.optim as optim
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(1, 5)
self.fc2 = nn.Linear(5, 10)
self.fc3 = nn.Linear(10, 1)
def forward(self, x):
x = self.fc1(x)
x = torch.relu(x)
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Model()
opt = optim.Adam(net.parameters())
I also have some input features:
features = torch.rand((3,1))
I can train it normally with a simple loss function that will be minimized:
for i in range(10):
opt.zero_grad()
out = net(features)
loss = torch.mean(torch.square(torch.tensor(5) - torch.sum(out)))
print('loss:', loss)
loss.backward()
opt.step()
However, if I'll add another loss component to this that I'd want to maximize--loss2:
loss2s = []
for i in range(10000):
opt.zero_grad()
out = net(features)
loss1 = torch.mean(torch.square(torch.tensor(5) - torch.sum(out)))
loss2 = torch.sum(torch.tensor([torch.sum(w_arr) for w_arr in net.parameters()]))
loss2s.append(loss2)
loss = loss1 + loss2
loss.backward()
opt.step()
It becomes seemingly unstable as the 2 losses have different scales. Also, I'm not sure that this is the correct way because how would the loss know to maximize one part and minimize the other. Note that this is just an example, obviously there's no point in increasing the weights.
import matplotlib.pyplot as plt
plt.plot(loss2s, c='r')
plt.plot(loss1s, c='b')
And also I believe that minimizing functions is the common way to train in ML, so I wasn't sure if changing the maximization problem into minimization problem in some way will be better.
| The standard way to denote "minimization" and "maximization" is changing the sign. PyTorch always minimizes a loss if the following is done
loss.backward()
So, if another loss2 needs to be maximized, we add negative of it
overall_loss = loss + (- loss2)
overall_loss.backward()
since minimizing a negative quantity is equivalent to maximizing the original positive quantity.
With regard to "scale", yes scales do matter. Often the following is done in order to match scales
overall_loss = loss + alpha * (- loss2)
where alpha is a fraction denoting relative importance of one loss w.r.t to the other. Its a hyperparameter and needs to experimented with.
Keeping technicalities aside, whether the resulting loss will be stable depends a lot on the specific problem and loss functions involved. If the losses are contradicting, you may experience instability. The ways to deal them is itself a research problem and much beyond the scope of this question.
| https://stackoverflow.com/questions/69557643/ |
Torch: Nccl available but not used (?) | I use PyTorch 1.9.0 but get the following error when trying to run a distributed version of a model:
File "/home/ferdiko/fastmoe/examples/transformer-xl/train.py", line 315, in <module>
para_model = DistributedGroupedDataParallel(model).to(device)
File "/home/ferdiko/anaconda3/envs/fastmoe/lib/python3.9/site-packages/fastmoe-0.2.1-py3.9-linux-x86_64.egg/fmoe/distributed.py", line 45, in __init__
self.comms["dp"] = get_torch_default_comm()
File "/home/ferdiko/anaconda3/envs/fastmoe/lib/python3.9/site-packages/fastmoe-0.2.1-py3.9-linux-x86_64.egg/fmoe/utils.py", line 30, in get_torch_default_comm
raise RuntimeError("Unsupported PyTorch version")
if I run torch.cuda.nccl.version() I get 2708. The developers suggested to run:
x = torch.rand(10).cuda()
print(torch.cuda.nccl.is_available(x))
which gives me False. Does this actually mean that there's a problem with PyTorch and NCCL?
| torch.cuda.nccl.is_available takes a sequence of tensors, and if they are on different devices, there is hope that you'll get a True:
In [1]: import torch
In [2]: x = torch.rand(1024, 1024, device='cuda:0')
In [3]: y = torch.rand(1024, 1024, device='cuda:1')
In [4]: torch.cuda.nccl.is_available([x, y])
Out[4]: True
If you give it just one tensor, torch.cuda.nccl.is_available will iterate through it instead, but different parts of the same tensor are always on the same device, so you'll always get a False:
In [5]: torch.cuda.nccl.is_available(x)
Out[5]: False
In [6]: torch.cuda.nccl.is_available([x])
Out[6]: True
| https://stackoverflow.com/questions/69558803/ |
What is the predicted output label from a PyTorch model? | I am currently training a ResNet18 model with a custom optimizer in PyTorch.
I am using CrossEntropyLoss() and the ResNet18 model from PyTorch.
In tensorflow the outputs are of the desired shape, but in pytorch it is necessary to find the argmax of the predicted labels in order to find the accuracy.
If my batch size = 64 with the resnet model, why is the predicted label of shape [64, 1000]?
What do the 1000 values correspond to?
| The predicted quantity is not "label", it is the probability (soft score) of the input being one of 1000 classes.
The output of (64, 1000) contains a 1000 length vector for each input in a batch. If you want discrete labels (i.e. 0 to 999), perform an argmax over it
labels = torch.argmax(output, 1)
By argmax over each probability vector, we compute which class (among 1000) has the highest probability for the input.
| https://stackoverflow.com/questions/69559925/ |
Tensor Reshape Query | I have a image tensor of shape :-
N,C,H,W = 5,512,13,13
I need to take a mean across H and W dimensions so that the output is of shape :-
N,C,1,1
I am trying doing for loop but is there some better way to do so using reshape. .
| import torch
tz = torch.rand(5, 512, 13, 13)
tzm = tz.mean(dim=(2,3), keepdim=True)
tzm.shape
Output
torch.Size([5, 512, 1, 1])
| https://stackoverflow.com/questions/69568907/ |
How to sample data from the proximity of existing data? | I have data for xor as below -
x
y
z
x ^ y ^ z
0
0
1
1
0
1
0
1
1
0
0
1
1
1
1
1
Kept only the ones that make the xor of all three equal to 1.
I want to generate synthetic data around the already available data within some range uniformly at random. The above table can be thought of as seed data. An example of expected table will be as follows:
x
y
z
x ^ y ^ z
0.1
0.3
0.8
0.9
0.25
0.87
0.03
0.99
0.79
0.09
0.28
0.82
0.97
0.76
0.91
0.89
Above table is sampled with a range of 0 to 0.3 for 0 value and with range 0.7 to 1 for value 1.
I want to achieve this using pytorch.
| For a problem such as this, you are able to completely synthesise data without using a reference because it has a simple solution. For zero (0-0.3) you can use the torch.rand function to generate uniformly random data for 0-1 and scale it. For one (0.7-1) you can do the same and just offset it:
N = 5
p = 0.5 #change this to bias your outputs
x_is_1 = torch.rand(N)>p #decide if x is going to be 1 or 0
y_is_1 = torch.rand(N)>p #decide if y is going to be 1 or 0
not_all_0 = ~(x_is_1 & y_is_1) #get rid of the x ^ y ^ z = 0 elements
x_is_1,y_is_1 = x_is_1[not_all_0],y_is_1[not_all_0]
N = x_is_1.shape[0]
x = torch.rand(N) * 0.3
x = torch.where(x_is_1,x+0.7,x)
y = torch.rand(N) * 0.3
y = torch.where(y_is_1,y+0.7,y)
z = torch.logical_xor(x_is_1,y_is_1).float()
triple_xor = 1 - torch.rand(z.shape)*0.3
print(torch.stack([x,y,z,triple_xor]).T)
#x y z x^y^z
tensor([[0.2615, 0.7676, 1.0000, 0.8832],
[0.9895, 0.0370, 1.0000, 0.9796],
[0.1406, 0.9203, 1.0000, 0.9646],
[0.1799, 0.9722, 1.0000, 0.9327]])
Or, to treat your data as the basis (for more complex data), there is a preprocessing tool known as gaussian noise injection which seems to be what you're after. Or you can just define a function and call it a bunch of times.
def add_noise(x,y,z,triple_xor,range=0.3):
def proc(dat,range):
return torch.where(dat>0.5,torch.rand(dat.shape)*range+1-range,torch.rand(dat.shape)*range)
return proc(x,range),proc(y,range),proc(z,range),proc(triple_xor,range)
gen_new_data = torch.cat([torch.stack(add_noise(x,y,z,triple_xor)).T for _ in range(5)])
| https://stackoverflow.com/questions/69569803/ |
__init__() got an unexpected keyword argument 'chi1' | I am new in python. I am trying to import arguments into my class "inverse_model" . I call a function "get_models" to do that. But it gives me the error "init() got an unexpected keyword argument 'zz':
I appreciate help. Please see code below:
def get_models(args):
zz=torch.tensor(args.chi_Initialize)
inverse_net = inverse_model(in_channels=len(args.chi),zz=zz,resolution_ratio=args.resolution_ratio,nonlinearity=args.nonlinearity)
return inverse_net
class inverse_model(nn.Module):
def __init__(self, in_channels,zz,resolution_ratio=6,nonlinearity="tanh"):
super(inverse_model, self).__init__()
self.in_channels = in_channels
self.zz=zz
self.resolution_ratio = resolution_ratio #vertical scale mismtach between seismic and EI
self.activation = nn.ReLU() if nonlinearity=="relu" else nn.Tanh()
| After default argument, python does not allow to have non default argument.
Modify your constructor to
def __init__(self, in_channels,
chi1,chi2,chi3,chi4,chi5,chi6,chi7,chi8,chi9,
chi10,chi11,chi12, resolution_ratio=6,nonlinearity="tanh"):
Updated answer : Revision 1 (updated question)
import torch
from torch import nn
class inverse_model(nn.Module):
def __init__(self, in_channels, zz, resolution_ratio=6, nonlinearity="tanh"):
super(inverse_model, self).__init__()
self.in_channels = in_channels
self.zz = zz
self.resolution_ratio = resolution_ratio # vertical scale mismtach between seismic and EI
self.activation = nn.ReLU() if nonlinearity == "relu" else nn.Tanh()
def get_models(args):
zz = torch.tensor(args.chi_Initialize)
inverse_net = inverse_model(in_channels=len(args.chi), zz=zz, resolution_ratio=args.resolution_ratio,
nonlinearity=args.nonlinearity)
return inverse_net
It returns exit 0 as status.
| https://stackoverflow.com/questions/69574878/ |
Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same at summary() method call | I am trying to implement this program which is available on github to display the summary of models in Pytorch: :
import torch as th
from torch.autograd import Variable
from torch import nn
from collections import OrderedDict
def summary(input_size, model):
def register_hook(module):
def hook(module, input, output):
class_name = str(module.__class__).split('.')[-1].split("'")[0]
module_idx = len(summary)
m_key = '%s-%i' % (class_name, module_idx+1)
summary[m_key] = OrderedDict()
summary[m_key]['input_shape'] = list(input[0].size())
summary[m_key]['input_shape'][0] = -1
summary[m_key]['output_shape'] = list(output.size())
summary[m_key]['output_shape'][0] = -1
params = 0
if hasattr(module, 'weight'):
params += th.prod(th.LongTensor(list(module.weight.size())))
if module.weight.requires_grad:
summary[m_key]['trainable'] = True
else:
summary[m_key]['trainable'] = False
if hasattr(module, 'bias'):
params += th.prod(th.LongTensor(list(module.bias.size())))
summary[m_key]['nb_params'] = params
if not isinstance(module, nn.Sequential) and \
not isinstance(module, nn.ModuleList) and \
not (module == model):
hooks.append(module.register_forward_hook(hook))
dtype = th.cuda.FloatTensor
# check if there are multiple inputs to the network
if isinstance(input_size[0], (list, tuple)):
x = [Variable(th.rand(1,*in_size)).type(dtype) for in_size in input_size]
else:
x = Variable(th.rand(1,*input_size)).type(dtype)
print(x.shape)
print(type(x[0]))
# create properties
summary = OrderedDict()
hooks = []
# register hook
model.apply(register_hook)
# make a forward pass
model(x)
# remove these hooks
for h in hooks:
h.remove()
print('----------------------------------------------------------------')
line_new = '{:>20} {:>25} {:>15}'.format('Layer (type)', 'Output Shape', 'Param #')
print(line_new)
print('================================================================')
total_params = 0
trainable_params = 0
for layer in summary:
## input_shape, output_shape, trainable, nb_params
line_new = '{:>20} {:>25} {:>15}'.format(layer, str(summary[layer]['output_shape']), summary[layer]['nb_params'])
total_params += summary[layer]['nb_params']
if 'trainable' in summary[layer]:
if summary[layer]['trainable'] == True:
trainable_params += summary[layer]['nb_params']
print(line_new)
print('================================================================')
print('Total params: ' + str(total_params))
print('Trainable params: ' + str(trainable_params))
print('Non-trainable params: ' + str(total_params - trainable_params))
print('----------------------------------------------------------------')
return summary
Β To test it you can use a ready model from the library torchvision, like this (such as resnext50_32x4d)
import torchvision.models as models
resnext50_32x4d = models.resnext50_32x4d(pretrained=True)
Β But when calling the function
summary((3, 300, 300, resnext50_32x4d)
Β I get the following.
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same
| The error message you provided is quite clear about the issue.
Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) ..
Your input is on GPU but your weight (i.e. model) is not. So, just put your model on GPU
resnext50_32x4d = resnext50_32x4d.cuda()
| https://stackoverflow.com/questions/69576639/ |
Implementing custom learning rate scheduler in Pytorch? | I would like to implement this learning rate method as in the paper Attention is all you need. I have this code in Tensorflow, but I would like to implement it in Pytorch too. I know that Pytorch has modules for this (https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html), but how could I go about making a custom scheduler? Or perhaps one of the above lr_scheduler already fulfils the same function?
Tensorflow code:
class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, d_model, warmup_steps=4000):
super(CustomSchedule, self).__init__()
self.d_model = d_model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = warmup_steps
def __call__(self, step):
arg1 = tf.math.rsqrt(step)
arg2 = step * (self.warmup_steps ** -1.5)
return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)
learning_rate = CustomSchedule(d_model)
optimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98,
epsilon=1e-9)
Pytorch?
import torch
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.98), eps=1e-9)
scheduler =
| Since this is a scheduler used in a popular paper (Attention is all you need), reasonably good implementations already exist online.
You can grab a PyTorch implementation from this repository by @jadore801120.
Once you have it, then simply
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.98), eps=1e-9)
sched = ScheduledOptim(optimizer, d_model=..., n_warmup_steps=...)
also make sure to invoke the scheduler at the right time
for i, batch in enumerate(dataloader):
sched.zero_grad()
...
loss.backward()
sched.step_and_update_lr()
| https://stackoverflow.com/questions/69576720/ |
Model parallelism, CUDA out of memory in Pytorch | I am trying to build autoencoder model, where input/output is RGB images with size of 256 x 256. I tried to train model on 1 GPU with 12 GB of memory but I always caught CUDA OOM (I tried differen batchsizes and even batch size of 1 is failing). So I read about model parallelism in Pytorch and tried this:
class Autoencoder(nn.Module):
def __init__(self, input_output_size):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(input_output_size, 1024),
nn.ReLU(True),
nn.Linear(1024, 200),
nn.ReLU(True)
).cuda(0)
self.decoder = nn.Sequential(
nn.Linear(200, 1024),
nn.ReLU(True),
nn.Linear(1024, input_output_size),
nn.Sigmoid()).cuda(1)
print(self.encoder.get_device())
print(self.decoder.get_device())
def forward(self, x):
x = x.cuda(0)
x = self.encoder(x)
x = x.cuda(1)
x = self.decoder(x)
return x
So I have moved my encoder and decoder on different GPUs. But now I get this exception:
Expected tensor for 'out' to have the same device as tensor for argument #2 'mat1'; but device 0 does not equal 1 (while checking arguments for addmm)
It appear when I do x = x.cuda(1) in forward method.
Moreover, here is my "train" code, maye you can give me some advices about optimizations? Is images of 3 x 256 x 256 too large for training? (I cannot reduce them). Thank you in advance.
Training:
input_output_size = 3 * 256 * 256
model = Autoencoder(input_output_size).to(device)
optimizer = optim.Adam(model.parameters(), lr=1e-4)
criterion = nn.MSELoss()
for epoch in range(100):
epoch_loss = 0
for batch_idx, (images, _) in enumerate(dataloader):
images = torch.flatten(images, start_dim=1).to(device)
output_images = model(images).to(device)
train_loss = criterion(output_images, images)
train_loss.backward()
optimizer.step()
if batch_idx % 5 == 0:
with torch.no_grad():
model.eval()
pred = model(test_set).to(device)
model.train()
test_loss = criterion(pred, test_set)
wandb.log({"MSE train": train_loss})
wandb.log({"MSE test": test_loss})
del pred, test_loss
if batch_idx % 200 == 0:
# here I send testing images from output to W&B
with torch.no_grad():
model.eval()
pred = model(test_set).to(device)
model.train()
wandb.log({"PRED": [wandb.Image((pred[i].cpu().reshape((3, 256, 256)).permute(1, 2, 0) * 255).numpy().astype(np.uint8), caption=str(i)) for i in range(20)]})
del pred
gc.collect()
torch.cuda.empty_cache()
epoch_loss += train_loss.item()
del output_images, train_loss
epoch_loss = epoch_loss / len(dataloader)
wandb.log({"Epoch MSE train": epoch_loss})
del epoch_loss
| Three issues that I'm seeing:
model(test_set)
This is when you are sending the entirety of your test set (presumably huge) as a single batch through your model.
I don't know what wandb is, but another likely source of memory growth is these lines:
wandb.log({"MSE train": train_loss})
wandb.log({"MSE test": test_loss})
You seem to be saving train_loss and test_loss, but these contain not only the numbers themselves, but the computational graphs (living on the GPU) needed for backprop. Before saving them, you want to convert them into float or numpy.
Your model contains two 3*256*256 x 1024 weight blocks. When used in Adam, these will require 3*256*256 x 1024 * 3 * 4 bytes = 2.25GB of VRAM each (Possibly more, if it's inefficiently implemented) This looks like a poor architecture for other reasons also.
| https://stackoverflow.com/questions/69577629/ |
Using Pytorch model trained on RTX2080 on RTX3060 | I try to run my PyTorch model (trained on a Nvidia RTX2080) on the newer Nvidia RTX3060 with CUDA support. It is possible to load the model and to execute it. If I run it on the CPU with the --no_cuda flag it runs smootly and gives back the correct predictions, but if I want to run it with CUDA, it only returns wrong predictions which make no sense.
Does the different GPU-architecture of the cards affect the prediction?
| Ok it seemed that the problem was the different floating point of the two architectures. The flag torch.backends.cuda.matmul.allow_tf32 = false needs to be set, to provide a stable execution of the model of a different architecture.
| https://stackoverflow.com/questions/69582900/ |
How does grad() works in PyTorch? | I need some conceptual clarity with the inputs of the Pytorch grad() function.
Please see the following code:
import torch
a = torch.tensor([2., 3.], requires_grad=True)
b = torch.tensor([6., 4.], requires_grad=True)
Q = 1/3*a**3 - 1/2*b**2
Here, I have defined 3 tensors, I was trying to compute the derivative of Q w.r.t a.
The following line would simply compute the first and second derivatives.
Q_a = torch.autograd.grad(Q.sum(), a, create_graph=True)[0]
Q_aa = torch.autograd.grad(Q_a.sum(), a, create_graph=True)[0]
print('Q_a =',Q_a.detach().numpy())
print('Q_aa =',Q_aa.detach().numpy())
The output is:
Q_a = [4. 9.]
Q_aa = [4. 6.]
I am wondering that, why do I need to pass Q.sum() or Q_a.sum() which is just 1 value and the second argument a has two values.
>>> print(Q.sum())
>>> tensor(-14.3333, grad_fn=<SumBackward0>)
>>> print(a)
>>> tensor([2., 3.], requires_grad=True)
Can someone explain to me how does Q.sum() helps in computing the correct gradient. Is it possible to compute the derivatives with just Q not Q.sum()?
| Well, your question is based on wrong assumption. You said ..
I was trying to compute the derivative of Q w.r.t a
NO. you are not. In the code sample you provided, you are trying to compute the derivative of Q.sum() w.r.t a - they are different things.
"Derivative of Q w.r.t a" is matrix called Jacobian, whereas ..
"Derivative of Q.sum() w.r.t a" is a vector known as gradient.
Both can be computed and are used in different places for achieving different things. Its your decision which one you want.
| https://stackoverflow.com/questions/69591193/ |
Pytorch: using CUDA prevents optimization from working | I have a very simple optimization: a straight line. Here is the code:
use_gpu = torch.cuda.is_available()
learning_rate = 0.05
loss_function = nn.MSELoss()
train_inputs = torch.FloatTensor([1,2,3,4,5,6]).T.unsqueeze(0)
y_truth = torch.FloatTensor([10, 15, 20, 25, 30, 35]).unsqueeze(0)
W = torch.nn.Parameter(torch.rand(1), requires_grad=True)
b = torch.nn.Parameter(torch.rand(1), requires_grad=True)
optimizer = optim.Adam([b, W], lr=learning_rate)
# if use_gpu:
# y_truth = y_truth.cuda()
# W = W.cuda()
# b = b.cuda()
# train_inputs = train_inputs.cuda()
for epoch in range(1000):
optimizer.zero_grad()
y_preds = b + W * train_inputs
loss = loss_function(y_truth, y_preds)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print(loss.data, W.data, b.data)
That code works fine if I do not put the data on the GPU. If I uncomment the if use_gpu bloc, the code runs, but does not minimize anything and the variables do not update.
I would expect the code to work similarly on the GPU or not. Any idea what is happening?
Thanks!
|
Any idea what is happening?
Yes, the parameters you are training, W and b stayed on the host (CPU).
When you did
W = W.cuda()
b = b.cuda()
you just chose to ignore the actual parameters being optimized.
If you wish to use the GPU for this, you could try:
W = torch.nn.Parameter(torch.rand(1).cuda())
b = torch.nn.Parameter(torch.rand(1).cuda())
instead.
| https://stackoverflow.com/questions/69591391/ |
How to add a dropout layer in LSTM to avoid overfitting | While implementing a hybrid quantum LSTM model, the model is overfitting and thus giving low accuracy. I tried setting dropout = 1 in nn.LSTM but no improvement. I have used a single hidden layer. How do I add the dropout layer to reduce overfitting?
Model parameters:
input_dim = 16
hidden_dim = 100
layer_dim = 1
output_dim = 1
Model class:
class LSTMModel(nn.Module):
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
super(LSTMModel, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = layer_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, dropout=1, batch_first=True, )
self.fc = nn.Linear(hidden_dim, output_dim)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()
c0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()
x, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
x = self.fc(x[:, -1, :])
x = self.hybrid(x)
return T.cat((x, 1 - x), -1)
| Pytorch's LSTM layer takes the dropout parameter as the probability of the layer having its nodes zeroed out. When you pass 1, it will zero out the whole layer. I assume you meant to make it a conventional value such as 0.3 or 0.5.
As @ayandas says above, too, it applies dropout to each layer except the last (see the link above), so it won't work for a single-layer LSTM. You can always apply your own dropout using nn.dropout at the output of your LSTM layers if you wish.
| https://stackoverflow.com/questions/69594311/ |
add a nn.Parameter tensor to the optim | let's say I have a network with a parameter tensor:
self.inital_value = nn.Parameter(torch.randn(1,96,4,4))
and two layers:
self.rgb_layers = nn.ModuleList([nn.Conv2d(96, 3, 1, 1, 0)]*2)
so the forward function is as follows:
v = torch.clone(self.inital_value)
for i in range(2):
v = self.rgb_layers[i](v)
return v
now I define an optimiser. if I want to train only the first layer I can do:
opt = optim.RMSprop(model.rgb_layers[0].parameters(),lr = lr)
but if I want to train only the tensor self.inital_value and I do the same I get this error:
'Parameter' object has no attribute 'parameters'
how can I bypass this limitation?
| Well, it takes a sequence of Parameters. And you have one Parameter, called self.initial_value.
So how about [self.initial_value] ?
| https://stackoverflow.com/questions/69602362/ |
How to give single number parameter in PyTorch? | I want to use a single number as a parameter.
I tried to insert parameter as follows
self.p1 = nn.Parameter() in def __init__(self, ...)
and self.p1 = 1.0 in def _initialize(self):
But I am getting the error
raise TypeError("cannot assign '{}' as parameter '{}' "
TypeError: cannot assign 'float' as parameter 'p1' (torch.nn.Parameter or None expected)
How can I use a single number as a parameter in my model initialized with 1?
| The argument passed to nn.Parameter should be a torch.Tensor:
>>> self.p1 = nn.Parameter(torch.tensor([1.0]))
| https://stackoverflow.com/questions/69603399/ |
Pytorch equivalent of tensorflow keras StringLookup? | I'm working with pytorch now, and I'm missing a layer: tf.keras.layers.StringLookup that helped with the processing of ids. Is there any workaround to do something similar with pytorch?
An example of the functionality I'm looking for:
vocab = ["a", "b", "c", "d"]
data = tf.constant([["a", "c", "d"], ["d", "a", "b"]])
layer = tf.keras.layers.StringLookup(vocabulary=vocab)
layer(data)
Outputs:
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
array([[1, 3, 4],
[4, 1, 2]])>
| Package torchnlp,
pip install pytorch-nlp
from torchnlp.encoders import LabelEncoder
data = ["a", "c", "d", "e", "d"]
encoder = LabelEncoder(data, reserved_labels=['unknown'], unknown_index=0)
enl = encoder.batch_encode(data)
print(enl)
tensor([1, 2, 3, 4, 3])
| https://stackoverflow.com/questions/69606274/ |
Add two torch tensor list | I want to add two PyTorch tensors together, for example, let
a = tensor([[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.],
[1., 1., 2.]])
b = tensor([[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.],
[4., 5., 6., 7., 8., 9.]])
And I would like the resulting tensor c to be:
c = tensor([[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.],
[5., 6., 8., 8., 9., 11.]])
Note: b.shape[1] is always a multiple of a.shape[1].
is there any better way than the solution below solution?
fin = torch.Tensor()
for i in range(int(b.shape[1]/a.shape[1])):
target = b[:,batch*i:batch*(i+1)]
temp = torch.add(target, a)
fin = torch.cat([fin, temp], dim =1)
c = fin
| You can repeat the columns of a to match the shape of b with torch.Tensor.repeat, then add the resulting tensor to b:
>>> b + a.repeat(1, b.size(1)//a.size(1))
tensor([[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.],
[ 5., 6., 8., 8., 9., 11.]])
| https://stackoverflow.com/questions/69610920/ |
Generate individual H5 files for each and every video | My code is about to create an H5 file for Each and Every video in the folder, Extracting the feature from the video and stored into the H5 file.
in Below shown code extraction feature from multi videos and all the features are stored in the single H5 file
H5 file order:
video1:
- feature
video2:
- feature
issues:
How to create an H5 file for every video after a process is done
Code: Create_data.py
import argparse
from utils.generate_dataset import Generate_Dataset
parser = argparse.ArgumentParser(""Welcome you to fraction)
# Dataset options
parser.add_argument('--input', '--split', type=str, help="input video")
parser.add_argument('--output', type=str, default='', help="out data")
args = parser.parse_args()
if __name__ == "__main__":
gen = Generate_Dataset(args.input, args.output)
gen.generate_dataset()
gen.h5_file.close()
Code: Generate_Dataset.py :
import os
from networks.CNN import ResNet
from utils.KTS.cpd_auto import cpd_auto
from tqdm import tqdm
import math
import cv2
import numpy as np
import h5py
import numpy as np
class Generate_Dataset:
def __init__(self, video_path, save_path):
self.resnet = ResNet()
self.dataset = {}
self.video_list = []
self.video_path = ''
self.h5_file = h5py.File(save_path, 'w')
self._set_video_list(video_path)
def _set_video_list(self, video_path):
# import pdb;pdb.set_trace()
if os.path.isdir(video_path):
self.video_path = video_path
fileExt = r".mp4",".avi"
self.video_list = [_ for _ in os.listdir(video_path) if _.endswith(fileExt)]
self.video_list.sort()
else:
self.video_path = ''
self.video_list.append(video_path)
for idx, file_name in enumerate(self.video_list):
self.dataset['video_{}'.format(idx+1)] = {}
self.h5_file.create_group('video_{}'.format(idx+1))
def _extract_feature(self, frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame, (224, 224))
res_pool5 = self.resnet(frame)
frame_feat = res_pool5.cpu().data.numpy().flatten()
return frame_feat
def _get_change_points(self, video_feat, n_frame, fps):
n = n_frame / fps
m = int(math.ceil(n/2.0))
K = np.dot(video_feat, video_feat.T)
change_points, _ = cpd_auto(K, m, 1)
change_points = np.concatenate(([0], change_points, [n_frame-1]))
temp_change_points = []
for idx in range(len(change_points)-1):
segment = [change_points[idx], change_points[idx+1]-1]
if idx == len(change_points)-2:
segment = [change_points[idx], change_points[idx+1]]
temp_change_points.append(segment)
change_points = np.array(list(temp_change_points))
# temp_n_frame_per_seg = []
# for change_points_idx in range(len(change_points)):
# n_frame = change_points[change_points_idx][1] - change_points[change_points_idx][0]
# temp_n_frame_per_seg.append(n_frame)
# n_frame_per_seg = np.array(list(temp_n_frame_per_seg))
# print(change_points)
arr = change_points
list1 = arr.tolist()
list2 = list1[-1].pop(1) #pop [-1]value
print(list2)
print(list1)
print("****************") # [-1][-1] value find and divided by 15
cps_m = math.floor(arr[-1][1]/15)
list1[-1].append(cps_m) #append to list
print(list1)
print("****************") #list to nd array convertion
arr = np.asarray(list1)
print(arr)
arrmul = arr * 15
print(arrmul)
print("****************")
# print(type(change_points))
# print(n_frame_per_seg)
# print(type(n_frame_per_seg))
median_frame = []
for x in arrmul:
print(x)
med = np.mean(x)
print(med)
int_array = med.astype(int)
median_frame.append(int_array)
print(median_frame)
# print(type(int_array))
return arrmul
# TODO : save dataset
def _save_dataset(self):
pass
def generate_dataset(self):
print('[INFO] CNN processing')
for video_idx, video_filename in enumerate(self.video_list):
video_path = video_filename
if os.path.isdir(self.video_path):
video_path = os.path.join(self.video_path, video_filename)
video_basename = os.path.basename(video_path).split('.')[0]
video_capture = cv2.VideoCapture(video_path)
fps = video_capture.get(cv2.CAP_PROP_FPS)
n_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
frame_list = []
picks = []
video_feat = None
video_feat_for_train = None
for frame_idx in tqdm(range(n_frames-1)):
success, frame = video_capture.read()
if frame_idx % 15 == 0:
if success:
frame_feat = self._extract_feature(frame)
picks.append(frame_idx)
if video_feat_for_train is None:
video_feat_for_train = frame_feat
else:
video_feat_for_train = np.vstack((video_feat_for_train, frame_feat))
if video_feat is None:
video_feat = frame_feat
else:
video_feat = np.vstack((video_feat, frame_feat))
else:
break
video_capture.release()
arrmul = self._get_change_points(video_feat, n_frames, fps)
self.h5_file['video_{}'.format(video_idx+1)]['features'] = list(video_feat_for_train)
self.h5_file['video_{}'.format(video_idx+1)]['picks'] = np.array(list(picks))
self.h5_file['video_{}'.format(video_idx+1)]['n_frames'] = n_frames
self.h5_file['video_{}'.format(video_idx+1)]['fps'] = fps
self.h5_file['video_{}'.format(video_idx + 1)]['video_name'] = video_filename.split('.')[0]
self.h5_file['video_{}'.format(video_idx+1)]['change_points'] = arrmul
Expected results :
Folder: video
video_1:
video1.mp4
video2.mp4
Files are in this structure, now read video files and create separate H5 files after the process is over.
For more Code reference
| You need to :
remove self.h5_file = h5py.File(save_path, 'w') from __init__()
remove self.h5_file.create_group('video_{}'.format(idx+1)) from _set_video_list()
remove gen.h5_file.close() from main()
change last block of generate_dataset() into something like:
.
video_capture.release()
arrmul = self._get_change_points(video_feat, n_frames, fps)
h5_dir = os.path.dirname(video_path)
h5_full_path = os.path.join(h5_dir, 'video_{}'.format(video_idx+1))
with h5py.File(h5_full_path, 'w') as h5_file:
h5_file['features'] = list(video_feat_for_train)
h5_file['picks'] = np.array(list(picks))
h5_file['n_frames'] = n_frames
h5_file['fps'] = fps
h5_file['video_name'] = video_filename.split('.')[0]
h5_file['change_points'] = arrmul
Please note that your inner video file indices and actual video file name numbers may not match. So I suggest to change
h5_dir = os.path.dirname(video_path)
h5_full_path = os.path.join(h5_dir, 'video_{}'.format(video_idx+1))
from above into
h5_full_path = video_path.split('.')[0] + '.h5'
This will create features file with the name matched to the video file.
| https://stackoverflow.com/questions/69611677/ |
pytorch custom loss with regards to weights | I have a loss based on 2 things:
MSE loss
A custom loss term based on the network weights.
I have this code:
net = CustomNet()
mse_loss = torch.nn.MSELoss()
def custom_loss(output, target):
weights = net.linear_layer.weight.data
return mse_loss(output, target) + torch.linalg.norm(weights @ weights.T -
torch.eye(weights.shape[0]))
When I try to remove the MSE loss (so my loss is only based on the weights):
def custom_loss(output, target):
weights = net.linear_layer.weight.data
return torch.linalg.norm(weights @ weights.T -
torch.eye(weights.shape[0]))
I am getting the error:
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
I can notice that mse loss has grad_fn=<MseLossBackward object at 0x14908c450>
What am I doing wrong? Why can't I use only the second loss?
| You can't use the second term alone because it doesn't have a grad_fn function as the first term does. This means if you're having both terms it will only backpropagate on the first term (the MSE loss) and will not consider the second. Having no grad_fn means it is seen as a constant w.r.t. the input or parameter and has no effect on the gradient.
The tensors you use to compute the second term do not require a gradient. More specifically any tensor that you get using the data attribute won't require a gradient. In your case net.linear_layer.weight.data.
Instead you should access the tensor directly via:
>>> weights = net.linear_layer.weight
| https://stackoverflow.com/questions/69616825/ |
Custom conv2d filter results in error because of different input type tensors | I want to write a custom conv2d layer for my Pytorch model. Running the code below results in
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.DoubleTensor) should be the same
It somehow say "torch.cuda.FloatTensor" even if i don't send it to the GPU. Can somebody explain what causes this error, please?
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from torchsummary import summary
class exampleNet(nn.Module):
def filters(self):
w = np.ones([2,2])
w = torch.tensor(w)
w = w.view(1, 1, 2, 2)
return w
def __init__(self):
super(exampleNet, self).__init__()
def forward(self, x):
w = self.filters()
x = F.conv2d(x, w)
return x
model = exampleNet()
summary(model, (1,10,10))
| The summary() function of torchsummary has an argument named device=.. which is set to cuda:0 by default. Just change it to whichever device you want
summary(model, (1,10,10), device=torch.device('cpu'))
Edit (see comments below): Consider using torchinfo instead of torchsummary.
| https://stackoverflow.com/questions/69617047/ |
ValueError: Target size (torch.Size([1, 1])) must be the same as input size (torch.Size([1, 2])) | While trying to train my model with 2 targets, I get the errorβ¦βValueError: Target size (torch.Size([1, 1])) must be the same as input size (torch.Size([1, 2]))β. I have a data set with 2 targets. I tried a lot even by resizing the tensors but no use. Also if I make the output_dim = 1, it always predicts the same class out of two.
** Loading Training data
class SwelltrainDataset(T.utils.data.Dataset):
def __init__(self, Swelltrain):
sc = StandardScaler()
X_tr = sc.fit_transform(X_train)
Y_tr = y_train
self.X_tr = torch.tensor(X_tr, dtype = torch.float32)
self.Y_tr = torch.tensor(Y_tr, dtype = torch.float32)
def __len__(self):
return len(self.Y_tr)
def __getitem__(self, idx):
return self.X_tr[idx], self.Y_tr[idx]
train_ds = SwelltrainDataset(Swelltrain)
bat_size = 1
idx = np.append(np.where(train_ds.Y_tr == 0)[0],
np.where(train_ds.Y_tr == 1)[0],
)
train_ds.X_tr = train_ds.X_tr[idx]
train_ds.Y_tr = train_ds.Y_tr[idx]
train_ldr = T.utils.data.DataLoader(train_ds,
batch_size=bat_size, shuffle=True)
batch = next(iter(train_ldr))
I am using LSTM Model with dimensions: input_dim = 16, hidden_dim = 100, layer_dim = 1, output_dim = 2
class LSTMModel(nn.Module):
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
super(LSTMModel, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = layer_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, dropout=1, batch_first=True, )
self.fc = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()
c0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()
x, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
x = self.fc(x[:, -1, :])
return (x)
**Model Training
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.BCEWithLogitsLoss()
epochs = 2
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for X_tr, Y_tr in train_ldr:
X_tr = X_tr.unsqueeze(1)
Y_tr = Y_tr.type(torch.LongTensor)
Y_tr = Y_tr.unsqueeze(1)
optimizer.zero_grad()
output = model(X_tr.float())
pred = output.argmax(dim=1, keepdim=True)
loss = loss_func(output, Y_tr.float())
loss.backward()
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
ValueError Traceback (most recent call last)
<ipython-input-30-1ab26e6f45d7> in <module>
31
32 # print(Y_tr.size())
---> 33 loss = loss_func(output, Y_tr.float())
34
35 # Backward pass
~\anaconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
887 result = self._slow_forward(*input, **kwargs)
888 else:
--> 889 result = self.forward(*input, **kwargs)
890 for hook in itertools.chain(
891 _global_forward_hooks.values(),
~\anaconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
712 assert self.weight is None or isinstance(self.weight, Tensor)
713 assert self.pos_weight is None or isinstance(self.pos_weight, Tensor)
--> 714 return F.binary_cross_entropy_with_logits(input, target,
715 self.weight,
716 pos_weight=self.pos_weight,
~\anaconda3\lib\site-packages\torch\nn\functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
2825
2826 if not (target.size() == input.size()):
-> 2827 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
2828
2829 return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)
ValueError: Target size (torch.Size([1, 1])) must be the same as input size (torch.Size([1, 2]))
| Try converting your Y_tr variable into a 2 class one hot label:
one_hot_label = torch.nn.functional.one_hot(Y_tr.to(torch.int64), 2)
one_hot_label = one_hot_label.float()
This should have the shape of target torch.Size([1, 2])
| https://stackoverflow.com/questions/69617623/ |
How do I compute the weighted average of attention scores and encoder outputs in PyTorch? | I'm currently trying to implement an LSTM with attention in PyTorch, and as soon as it comes to dealing with batch sizes and multidimensional tensors I suddenly forget how linear algebra works. I have a tensor of attention scores of size [64, 19, 1], where 64 is the batch size and 19 is the max length of a source sentence. I also have a tensor of outputs of the encoder (hidden states); its shape is [64, 19, 256], where 256 is the dimension of the hidden state. What's a decent way to compute the context vector/the weighted average of attention scores and encoder hidden states? My brain is unfortunately unable to reason about these sorts of things when it comes to more than two dimensions/including the batch sizes.
| As simple as context = torch.sum(attention * encoder_hidden, dim=1).
| https://stackoverflow.com/questions/69620936/ |
Issue using ._parameters internal method in pytorch | I'm trying to access model parameters using the internal ._parameters method. When I define the model as below, I get model parameters without any issue
model = nn.Linear(10, 10)
print(model._parameters)
However, when I use this method to get parameters of a model defined as a class, I get an empty OrderedDict().
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc = nn.Linear(10, 10)
def forward(self, x):
return self.fc(x)
model = MyModel()
print(model._parameters)
Is there a solution to this using ._parameters?
NOTE: I understand that using internal methods are frowned upon.
| Each linear layer in the MyModel class is a module, and can be accessed using _modules. So you can access the parameters of your model using:
for module_key in model._modules.keys():
for param_key in model._modules[module_key]._parameters:
p = model._modules[module_key]._parameters[param_key]
| https://stackoverflow.com/questions/69621740/ |
PyTorch Training exitting after Caching Images | I have a dataset of around 12k Training Images and 500 Validation Images. I am using YOLOv5-PyTorch to train my model. When i start the training, and when it comes down to the Caching Images stage, it suddenly quits.
The code I'm using to run this is as follows:
!python train.py --img 800 --batch 32 --epochs 20 --data '/content/data.yaml' --cfg ./models/custom_yolov5s.yaml --weights yolov5s.pt --name yolov5s_results --cache
I am using Google Colab to train my model.
This is the command that executes before shutting down:
train: Caching Images (12.3GB ram): 99% 11880/12000 [00:47<00:00,
94.08it/s]
| So i solved the above problem. The problem is occuring because we are caching all the images fore-hand as to increase the speed during epochs. Now this may increase the speed but on the other hand, it also consumes memory. When you are using Google Colab, it provides you 12.69GB of RAM. When caching such huge data, all of the RAM was being consumed and there was nothing left to cache validation set hence, it shuts down immediately.
There are two basic methods to solve this issue:
Method 1:
I simply reduced the image size from 800 to 640 as my training images didn't contain any small object, so i actually did not need large sized images. It reduced my RAM consumption by 50%
--img 640
train: Caching Images (6.6GB ram): 100% 12000/12000 [00:30<00:00,
254.08it/s]
Method 2:
I had written an argument at the end of my command that I'm using to run this project :
--cache
This command caches the entire dataset in the first epoch so it may be reused again instantly instead of processing it again. If you are willing to compromise on training speed, then this method would work for you. Just simply remove this line and you will be good to go. Your new command to run will be:
!python train.py --img 800 --batch 32 --epochs 20 --data '/content/data.yaml' --cfg ./models/custom_yolov5s.yaml --weights yolov5s.pt --name yolov5s_results
| https://stackoverflow.com/questions/69626729/ |
How to get SHAP values for Huggingface Transformer Model Prediction [Zero-Shot Classification]? | Given a Zero-Shot Classification Task via Huggingface as follows:
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
example_text = "This is an example text about snowflakes in the summer"
labels = ["weather", "sports", "computer industry"]
output = classifier(example_text, labels, multi_label=True)
output
{'sequence': 'This is an example text about snowflakes in the summer',
'labels': ['weather', 'sports'],
'scores': [0.9780895709991455, 0.021910419687628746]}
I am trying to extract the SHAP values to generate a text-based explanation for the prediction result like shown here: SHAP for Transformers
I already tried the following based on the above url:
from transformers import AutoModelForSequenceClassification, AutoTokenizer, ZeroShotClassificationPipeline
model = AutoModelForSequenceClassification.from_pretrained('facebook/bart-large-mnli')
tokenizer = AutoTokenizer.from_pretrained('facebook/bart-large-mnli')
pipe = ZeroShotClassificationPipeline(model=model, tokenizer=tokenizer, return_all_scores=True)
def score_and_visualize(text):
prediction = pipe([text])
print(prediction[0])
explainer = shap.Explainer(pipe)
shap_values = explainer([text])
shap.plots.text(shap_values)
score_and_visualize(example_text)
Any suggestions? Thanks for your help in advance!
Alternatively to the above pipeline the following also works:
from transformers import AutoModelForSequenceClassification, AutoTokenizer, ZeroShotClassificationPipeline
model = AutoModelForSequenceClassification.from_pretrained('facebook/bart-large-mnli')
tokenizer = AutoTokenizer.from_pretrained('facebook/bart-large-mnli')
classifier = ZeroShotClassificationPipeline(model=model, tokenizer=tokenizer, return_all_scores=True)
example_text = "This is an example text about snowflakes in the summer"
labels = ["weather", "sports"]
output = classifier(example_text, labels)
output
{'sequence': 'This is an example text about snowflakes in the summer',
'labels': ['weather', 'sports'],
'scores': [0.9780895709991455, 0.021910419687628746]}
| The ZeroShotClassificationPipeline is currently not supported by shap, but you can use a workaround. The workaround is required because:
The shap Explainer forwards only one parameter to the model (a pipeline in this case), but the ZeroShotClassificationPipeline requires two parameters, namely text, and labels.
The shap Explainer will access the config of your model and use its label2id and id2label properties. They do not match the labels returned from the ZeroShotClassificationPipeline and will result in an error.
Below is a suggestion for one possible workaround. I recommend opening an issue at shap and requesting official support for huggingface's ZeroShotClassificationPipeline.
import shap
from transformers import AutoModelForSequenceClassification, AutoTokenizer, ZeroShotClassificationPipeline
from typing import Union, List
weights = "valhalla/distilbart-mnli-12-3"
model = AutoModelForSequenceClassification.from_pretrained(weights)
tokenizer = AutoTokenizer.from_pretrained(weights)
# Create your own pipeline that only requires the text parameter
# for the __call__ method and provides a method to set the labels
class MyZeroShotClassificationPipeline(ZeroShotClassificationPipeline):
# Overwrite the __call__ method
def __call__(self, *args):
o = super().__call__(args[0], self.workaround_labels)[0]
return [[{"label":x[0], "score": x[1]} for x in zip(o["labels"], o["scores"])]]
def set_labels_workaround(self, labels: Union[str,List[str]]):
self.workaround_labels = labels
example_text = "This is an example text about snowflakes in the summer"
labels = ["weather","sports"]
# In the following, we address issue 2.
model.config.label2id.update({v:k for k,v in enumerate(labels)})
model.config.id2label.update({k:v for k,v in enumerate(labels)})
pipe = MyZeroShotClassificationPipeline(model=model, tokenizer=tokenizer, return_all_scores=True)
pipe.set_labels_workaround(labels)
def score_and_visualize(text):
prediction = pipe([text])
print(prediction[0])
explainer = shap.Explainer(pipe)
shap_values = explainer([text])
shap.plots.text(shap_values)
score_and_visualize(example_text)
Output:
| https://stackoverflow.com/questions/69628487/ |
Convolutional Neural Network Model - Why do I get different results on the same image | I'm new to Neural Networks and I'm trying to train a CNN model on a custom dataset (cats and dogs images in a single directory). So I guess I do the very usual stuff here which is in the most tutorials, but just in case I will give here my full code.
First I generate .csv file to be processed:
import os
import torch
device = ("cuda" if torch.cuda.is_available() else "cpu")
train_df = pd.DataFrame(columns=["img_name","label"])
train_df["img_name"] = os.listdir("train/")
for idx, i in enumerate(os.listdir("train/")):
if "cat" in i:
train_df["label"][idx] = 0
if "dog" in i:
train_df["label"][idx] = 1
train_df.to_csv (r'train_csv.csv', index = False, header=True)
Then I prepare the dataset:
from torch.utils.data import Dataset
import pandas as pd
import os
from PIL import Image
import torch
class CatsAndDogsDataset(Dataset):
def __init__(self, root_dir, annotation_file, transform=None):
self.root_dir = root_dir
self.annotations = pd.read_csv(annotation_file)
self.transform = transform
def __len__(self):
return len(self.annotations)
def __getitem__(self, index):
img_id = self.annotations.iloc[index, 0]
img = Image.open(os.path.join(self.root_dir, img_id)).convert("RGB")
y_label = torch.tensor(float(self.annotations.iloc[index, 1]))
if self.transform is not None:
img = self.transform(img)
return (img, y_label)
This is my model:
import torch.nn as nn
import torchvision.models as models
class CNN(nn.Module):
def __init__(self, train_CNN=False, num_classes=1):
super(CNN, self).__init__()
self.train_CNN = train_CNN
self.inception = models.inception_v3(pretrained=True, aux_logits=False)
self.inception.fc = nn.Linear(self.inception.fc.in_features, num_classes)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(0.5)
self.sigmoid = nn.Sigmoid()
def forward(self, images):
features = self.inception(images)
return self.sigmoid(self.dropout(self.relu(features))).squeeze(1)
This is my hyper-params, transformations and dataloaders:
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
num_epochs = 10
learning_rate = 0.00001
train_CNN = False
batch_size = 32
shuffle = True
pin_memory = True
num_workers = 0
transform = transforms.Compose(
[
transforms.Resize((356, 356)),
transforms.RandomCrop((299, 299)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]
)
dataset = CatsAndDogsDataset("train","train_csv.csv",transform=transform)
print(len(dataset))
train_set, validation_set = torch.utils.data.random_split(dataset,[162,40])
train_loader = DataLoader(dataset=train_set, shuffle=shuffle, batch_size=batch_size,num_workers=num_workers,pin_memory=pin_memory)
validation_loader = DataLoader(dataset=validation_set, shuffle=shuffle, batch_size=batch_size,num_workers=num_workers, pin_memory=pin_memory)
model = CNN().to(device)
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for name, param in model.inception.named_parameters():
if "fc.weight" in name or "fc.bias" in name:
param.requires_grad = True
else:
param.requires_grad = train_CNN
and accuracy check:
def check_accuracy(loader, model):
if loader == train_loader:
print("Checking accuracy on training data")
else:
print("Checking accuracy on validation data")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device=device)
y = y.to(device=device)
scores = model(x)
predictions = torch.tensor([1.0 if i >= 0.5 else 0.0 for i in scores]).to(device)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(
f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}"
)
model.train()
return f"{float(num_correct)/float(num_samples)*100:.2f}"
And this is my training function:
from tqdm import tqdm
def train():
model.train()
for epoch in range(num_epochs):
loop = tqdm(train_loader, total = len(train_loader), leave = True)
if epoch % 2 == 0:
loop.set_postfix(val_acc = check_accuracy(validation_loader, model))
for imgs, labels in loop:
imgs = imgs.to(device)
labels = labels.to(device)
outputs = model(imgs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loop.set_description(f"Epoch [{epoch}/{num_epochs}]")
loop.set_postfix(loss = loss.item())
if __name__ == "__main__":
train()
0%| | 0/6 [00:00<?, ?it/s]Checking accuracy on validation data
0%| | 0/6 [01:13<?, ?it/s, val_acc=60.00]Got 24 / 40 with accuracy 60.00
Epoch [0/10]: 100%|ββββββββββ| 6/6 [06:02<00:00, 60.39s/it, loss=0.693]
Epoch [1/10]: 100%|ββββββββββ| 6/6 [04:49<00:00, 48.23s/it, loss=0.693]
...
Epoch [8/10]: 100%|ββββββββββ| 6/6 [06:07<00:00, 61.29s/it, loss=0.693]
Epoch [9/10]: 100%|ββββββββββ| 6/6 [04:55<00:00, 49.19s/it, loss=0.781]
The model gets trained fine but when I try to use it for prediction I get different results each time I run this last piece in my Jupyter Notebooks:
model.eval()
img = Image.open('train/cat.22.png').convert("RGB")
img_t = transform(img)
batch_t = torch.unsqueeze(img_t, 0)
out = model(batch_t)
print(out)
tensor([0.5276], grad_fn=)
tensor([0.5000], grad_fn=)
tensor([0.5064], grad_fn=)
etc. Each time different result for the same image. Is this normal? Why this is happening?
| I don't see you loading your trained model. This means every time you initialize the CNN module, the inception.fc layer will get initialized with random weights, this is most probably the reason why you are getting different results on each inference.
Edit: You have a random transform in your transformation pipeline, namely RandomCrop.
| https://stackoverflow.com/questions/69632867/ |
''Boolean value of Tensor with more than one value is ambiguous'' when broadcasting torch Tensor | My objective is to extract the dimensions of a pytorch Tensor, whose indices are not in a given list. I want to use broadcasting to do that like follows:
Sim = torch.rand((5, 5))
samples_idx = [0] # the index of dim that I don't want to extract
a = torch.arange(Sim.size(0)) not in samples_idx
result = Sim[a]
I assume a would be a Tensor with True/Flase with the dimension of 5.But I get the error RuntimeError: Boolean value of Tensor with more than one value is ambiguous. Anyone can help me to point out where it goes wrong? Thanks.
| There is a misunderstanding between the concept of "dimension" and "indices". What you want is to filter Sim and keep only rows (the 0th dimension) which indices match a given rule.
Here is how you could do that:
Sim = torch.rand((5, 5))
samples_idx = [0] # the index of dim that I don't want to extract
a = [v for v in range(Sim.size(0)) if v not in samples_idx]
result = Sim[a]
a is not a boolean Tensor but a list of indices to keep. You then use it to index Sim on the 0th dimension (the rows).
not in is not an operation that can be broadcasted, you should use a regular Python comprehension list for it.
| https://stackoverflow.com/questions/69641790/ |
pyTorch mat1 and mat2 cannot be multiplied | I am getting the following error:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x33856 and 640000x256)
I don't understand how do I need to change the parameters of my net. I took the net created in this paper and tried to modify the parameters to meet my needs.This is the code, I changed the parameters of the first convolution but still get the error:
class ChordClassificationNetwork(nn.Module):
def __init__(self, train_model=False):
super(ChordClassificationNetwork, self).__init__()
self.train_model = train_model
self.flatten = nn.Flatten()
self.firstConv = nn.Conv2d(3, 64, (3, 3))
self.secondConv = nn.Conv2d(64, 64, (3, 3))
self.pool = nn.MaxPool2d(2)
self.drop = nn.Dropout(0.25)
self.fc1 = nn.Linear(100*100*64, 256)
self.fc2 = nn.Linear(256, 256)
self.outLayer = nn.Linear(256, 7)
def forward(self, x):
x = self.firstConv(x)
x = F.relu(x)
x = self.pool(x)
x = self.secondConv(x)
x = F.relu(x)
x = self.pool(x)
x = self.drop(x)
x = self.flatten(x)
x = self.fc1(x)
x = F.relu(x)
x = self.drop(x)
x = self.fc2(x)
x = F.relu(x)
x = self.drop(x)
x = self.outLayer(x)
output = F.softmax(x, dim=1)
return output
and this is the training file:
device = ("cuda" if torch.cuda.is_available() else "cpu")
transformations = transforms.Compose([
transforms.Resize((100, 100))
])
num_epochs = 10
learning_rate = 0.001
train_CNN = False
batch_size = 32
shuffle = True
pin_memory = True
num_workers = 1
dataset = GuitarDataset("../chords_data/cropped_images/train", transform=transformations)
train_set, validation_set = torch.utils.data.random_split(dataset, [int(0.8 * len(dataset)), len(dataset) - int(0.8*len(dataset))])
train_loader = DataLoader(dataset=train_set, shuffle=shuffle, batch_size=batch_size, num_workers=num_workers,
pin_memory=pin_memory)
validation_loader = DataLoader(dataset=validation_set, shuffle=shuffle, batch_size=batch_size, num_workers=num_workers,
pin_memory=pin_memory)
model = ChordClassificationNetwork().to(device)
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
def check_accuracy(loader, model):
if loader == train_loader:
print("Checking accuracy on training data")
else:
print("Checking accuracy on validation data")
num_correct = 0
num_samples = 0
model.eval()
with torch.no_grad():
for x, y in loader:
x = x.to(device=device)
y = y.to(device=device)
scores = model(x)
predictions = torch.tensor([1.0 if i >= 0.5 else 0.0 for i in scores]).to(device)
num_correct += (predictions == y).sum()
num_samples += predictions.size(0)
print(
f"Got {num_correct} / {num_samples} with accuracy {float(num_correct) / float(num_samples) * 100:.2f}"
)
return f"{float(num_correct) / float(num_samples) * 100:.2f}"
def train():
model.train()
for epoch in range(num_epochs):
loop = tqdm(train_loader, total=len(train_loader), leave=True)
if epoch % 2 == 0:
loop.set_postfix(val_acc=check_accuracy(validation_loader, model))
for imgs, labels in loop:
imgs = imgs.to(device)
labels = labels.to(device)
outputs = model(imgs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loop.set_description(f"Epoch [{epoch}/{num_epochs}]")
loop.set_postfix(loss=loss.item())
if __name__ == "__main__":
train()
What am I doing wrong?
| Look at the error message, the issue comes from the fc1 layer which doesn't have the required number of neurons. It is receiving a tensor of shape (batch_size, 33856) but expects (batch_size, 640000). The reduction in dimensionality is caused by the different layers you have applied to your input tensor before fc1.
You can fix this by defining fc1 with:
self.fc1 = nn.Linear(33856, 256)
Alternatively, you can use nn.LazyLinear which will initialize its weights with the appropriate number of neurons at runtime depending on the input it receives. But that's lazy:
self.fc1 = nn.LazyLinear(256)
| https://stackoverflow.com/questions/69652625/ |
Convert tensor of size 768 to 128 | I want to make a projection to the tensor of shape [197, 1, 768] to [197,1,128] in pytorch using nn.Conv()
| You could use a kernel size and stride of 6, as thatβs the factor between the input and output temporal size:
x = torch.randn(197, 1, 768)
conv = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=6, stride=6)
out = conv(x)
print(out.shape)
> torch.Size([197, 1, 128])
Solution Source
| https://stackoverflow.com/questions/69652882/ |
Understanding parameters of nn.NLLLoss function in this example | I am following an example in a book. The example defines the nn.NLLLoss() function whose input is confusing me.
My model has the final step as the nn.LogSoftmax which gives me the below tensor output(I'm trying the example on a single image):
tensor([[-0.7909, -0.6041]], grad_fn=<LogSoftmaxBackward>)
The tensor has probabilities of whether the image is a bird or an airplane. The example defines 0 for a bird and 1 for an airplane.
Now while defining the loss function the example passes the above-mentioned tensor and the correct label for the image as input likewise:
loss = nn.NLLLoss()
loss( out, torch.tensor([0])) #0 as the image is of a bird
I am unable to understand why are we passing the label of the image. My guess would be that the label specifies to the model which index of the probality to consider while calculating the loss. However, if that is the case why do we need to pass the label as a Tensor, we could just pass the label as an index to the out Tensor likewise:
loss( out[0, 0] ) # [0, 0] since out is a 2d Tensor
| This is precisely what nn.NLLLoss does... actually it's the only thing it does! Its purpose is to index the prediction tensor using the ground-truth label, and return minus that quantity.
Let y_hat be the prediction tensor and y the target tensor, then nn.NLLLoss performs:
>>> -y_hat[torch.arange(len(y_hat)), y]
In your example, it comes down to -y_hat[0, 0] since the label for that particular instance is 0.
You can read related posts on the nn.NLLLoss:
Is nn.NLLLoss is just a normal negative function?
Understanding of nn.NLLLoss
| https://stackoverflow.com/questions/69653302/ |
How to specify which pytorch to import, if I have two different versions installed? | The PyTorch previously installed in the remote Linux system is problematic (version 1.8.0). It is in the system folders so I don't have privilege to uninstall or upgrade it because I am not a super user. As a result, I installed another PyTorch in my user space using command
pip3 install --user --ignore-installed torch
There are some dependency conflict errors but in the end I was told "Successfully installed torch-1.9.1 typing-extensions-3.10.0.2". As shown in the output, the version installed in my user space is 1.9.1. Now, I have two versions of PyTorch installed.
But if I type
import torch
in python3 command line, which version does python3 try to import, the system-wide 1.8.0 version or the version 1.9.1 I newly installed in my user space? How do I specify which version to import? I know I can check the __version__ property, but import crashes in the first place. Thank you.
The environment:
A remote Linux with kernel 5.8.0. I am not a super user
Python 3.8.6
pip 21.2.4
| if you have more than one version of a package installed you can use package resources as follows
import pkg_resources
pkg_resources.require("torch==1.7.1") # The version you want to import
import torch
reference
| https://stackoverflow.com/questions/69656862/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.