instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
ESRGAN Issue — "Torch not compiled with CUDA enabled" | Need help! Trying to run a python script with a pre-trained model (ESRGAN), but every time I face this error message. What could be the problem?
Before that I've installed the following dependencies:
pip install pytorch cuda
pip install opencv-python glob2
| Fixed the problem by tweaking a code a bit, changing a device type from 'cuda' to 'cpu'.
device = torch.device('cpu')
| https://stackoverflow.com/questions/71816990/ |
PyTorch computes gradients as None | class Parent(nn.Module):
def __init__(self,in_features,z_dim, img_dim):
super().__init__()
self.my_child1 = Child1 (z_dim, img_dim)
self.my_child2 = Child2 (in_features)
def forward(self,input):
input=self.my_child1(input)
input=self.my_child2(input)
return input
def forward1(self,input):
input=self.my_child1(input)
return input
def forward2(self,input):
input=self.my_child2(input)
return input
class Child2(nn.Module):
def __init__(self, in_features):
super().__init__()
self.child2 = nn.Sequential(
nn.Linear(in_features, 128),
nn.LeakyReLU(0.01),
nn.Linear(128, 1),
nn.Sigmoid(),
)
def forward(self, x):
return self.child2(x)
class Child1(nn.Module):
def __init__(self, z_dim, img_dim):
super().__init__()
self.child1 = nn.Sequential(
nn.Linear(z_dim, 256),
nn.LeakyReLU(0.01),
nn.Linear(256, img_dim),
nn.Tanh(),
)
def forward(self, x):
return self.child1(x)
criterion=nn.BCELoss()
noise = torch.randn(batch_size, z_dim).to(device)
model=Parent(in_features,z_dim, img_dim)
output1=model(noise)
loss1=criterion(output1,torch.ones_like(output1))
loss2=criterion(output1,torch.zeroes_like(output1))
loss3=(loss1+loss2)/2
model.zero_grad()
loss3.backward(retain_graph=True)
print(loss3.grad)
I have not used any optimizer here because updating the parameters are done using a seperate formula which I will employ only after I get the gradients. The formula requires the gradients to be stored in a matrix. However, the gradient always prints “None”.
| You can get the computed gradient for every parameter in your model with:
gradient = [el.grad for el in model.parameters()]
print(gradient)
| https://stackoverflow.com/questions/71825789/ |
Convolutional neural network throws ErrorTypeError: __init__() takes 1 positional argument but 2 were given | I am passing a batch of 256 images x_s with the following dimensions [256, 3, 560, 448]. However I whenever i try to feed my images to the CNN i get the following error:
ErrorTypeError: __init__() takes 1 positional argument but 2 were given'
Not sure what it means here by '1 positional argument'. I am passing in the images using an iterator which I created. Below is my code for the training loop up until the point where it breaks:
for e in range(num_epochs):
print(f'Epoch{e+1:04d}/ {num_epochs:04d}', end='\n================\n')
dl_source_iter = iter(dl_source)
dl_target_iter = iter(dl_target)
for batch in range(max_batches):
optimizer.zero_grad()
p = float(batch + e * max_batches) / (num_epochs *max_batches)
grl_lambda = 2. / (1. + np.exp(-10 * p)) - 1
x_s, y_s = next(dl_source_iter)
y_s_domain = torch.zeros(256, dtype=torch.long)
class_pred, domain_pred = Cnn(x_s, grl_lambda) #This is the line which throws an error
Here is my convolutional neural network:
class Cnn(nn.Module):
def __init__(self):
super(Cnn, self).__init__()
self.feature_extract= nn.Sequential(
nn.Conv2d(3, 64, 5, 1, 1),
nn.BatchNorm2d(64),
nn.MaxPool2d(2),
nn.ReLU(True),
nn.Conv2d(64, 50, 5, 1, 1),
nn.BatchNorm2d(50),
nn.MaxPool2d(2),
nn.ReLU(True),
nn.Dropout2d(),
)
self.num_cnn_features = 50*5*5
self.class_classifier = nn.Sequential(
nn.Linear(self.num_cnn_features, 200),
nn.BatchNorm1d(200),
nn.Dropout2d(),
nn.ReLU(True),
nn.Linear(200, 200),
nn.BatchNorm1d(200),
nn.ReLU(True),
nn.Linear(200, 182),
nn.LogSoftmax(dim = 1),
)
self.DomainClassifier = nn.Sequential(
nn.Linear(self.num_cnn_features, 100),
nn.BatchNorm1d(100),
nn.ReLU(True),
nn.Linear(100, 2),
nn.LogSoftmax(dim=1)
)
def forward(self, x, grl_lambda=1.0):
features = self.feature_extract(x)
features = features.view(-1, self.num_cnn_features)
features_grl = GradientReversalFn(features, grl_lambda)
class_pred = self.class_classifier(features)
domain_pred = self.DomainClassifier(features_grl)
return class_pred, domain_pred
Does anyone have any guesses as to why this might be happening? I can't seem to figure out what is going wrong. Any help would be greatly appreciated.
| You need to create a Cnn object before you can pass data to it. You are calling the Cnn class constructor __init__, which expects no arguments, rather than the forward method for an instance of the Cnn class, which is what you actually want to do.
# outside of loop
model = Cnn()
# inside loop
class_pred, domain_pred = model(x_s, grl_lambda)
| https://stackoverflow.com/questions/71832588/ |
Pytorch dot product across rows from different arrays | I am trying to code up something similar to the positional encoding in the transformers paper.
In order to do so I need to do the following:
For the following three matrices, I want to concatenate them at row level (i.e. the first row from each one stacked together, the second rows together, etc.), and then apply dot product between each matrix and its transpose, and finally, flatten them and stack them together. I'll clarify this in the following example:
x = torch.tensor([[1,1,1,1],
[2,2,2,2],
[3,3,3,3]])
y = torch.tensor([[0,0,0,0],
[0,0,0,0],
[0,0,0,0]])
z = torch.tensor([[4,4,4,4],
[5,5,5,5],
[6,6,6,6]])
concat = torch.cat([x, y, z], dim=-1).view(-1, x.shape[-1])
print(concat)
tensor([[1, 1, 1, 1],
[0, 0, 0, 0],
[4, 4, 4, 4],
[2, 2, 2, 2],
[0, 0, 0, 0],
[5, 5, 5, 5],
[3, 3, 3, 3],
[0, 0, 0, 0],
[6, 6, 6, 6]])
# Here I get each three rows together, and then apply dot product, flatten, and stack them.
concat = torch.stack([
torch.flatten(
torch.matmul(
concat[i:i+3, :], # 3 is the number of tensors (x,y,z)
torch.transpose(concat[i:i+3, :], 0, 1))
)
for i in range(0, concat.shape[0], 3)
])
print(concat)
tensor([[ 4, 0, 16, 0, 0, 0, 16, 0, 64],
[ 16, 0, 40, 0, 0, 0, 40, 0, 100],
[ 36, 0, 72, 0, 0, 0, 72, 0, 144]])
Finally, I was able to get the final matrix that I want. My question is, is there a way to achieve this without using a loop as I did in the final step? I want everything to be in tensors.
| The loop you introduce only needs to be there to get a "list of slices" of the data, which is practically the same as reshaping it. You are basically introducing a additional dimension, in which there are 3 entries. Basically from shape [n, k] to [n, 3, k].
For working directly with tensors, you can just call .reshape to get to the same shape. After that, the rest of the code you use also works almost the exact same. The transpose has to be changed slightly, due to the change in dimensions.
All in all, what you want can be achieved with:
concat2 = concat.reshape((-1, 3, concat.shape[1]))
torch.flatten(
torch.matmul(
concat2,
concat2.transpose(1,2)
),
start_dim=1,
)
| https://stackoverflow.com/questions/71846576/ |
conda does not install old version of pytorch | I'm trying to install Pytorch 1.7 on a remote cluster using anaconda.
I have cloned the base environment from the anaconda module installed on remote:
module load anaconda
conda activate
conda create --clone base --name myenv
I have then done:
conda install pytorch==1.7.1 cudatoolkit=11.0 -c pytorch
as recommended in the Pytorch documentation. I get an error message,
PackagesNotFoundError: The following packages are not available from current channels:
- pytorch==1.7.1
On my personal laptop I can install pytorch 1.7 without issues using conda. I have conda 4.11.0 on my laptop and 4.9.2 on remote; the version of anaconda is the same. I cannot upgrade conda to 4.11 on remote as there are inconsistencies.
I have also tried to install my own version of anaconda from https://repo.anaconda.com/archive/Anaconda3-2021.05-Linux-ppc64le.sh**, with matched version of anaconda and conda to those of my laptop. Still no success at installing pytorch 1.7 with the command above.
Do you have any suggestions?
Thanks!
**the ppc64le extension is apparently the correct one, any x86 version refuses to install, although it's unclear to me why that is so..
| ppc64le is the issue here. Your laptop has (most likely) an amd64 based CPU while your remote computer has ppc64le as their CPU architecture. This means that pytorch packages compatible with your laptop will not be compatible with your remote computer. You can find out which pytorch versions are available for that CPU architecture by running conda search:
conda search --subdir='linux-ppc64le' -c pytorch pytorch
Loading channels: done
# Name Version Build Channel
pytorch 1.10.2 cpu_py310hef0c51e_0 pkgs/main
pytorch 1.10.2 cpu_py37h6f0ae12_0 pkgs/main
pytorch 1.10.2 cpu_py38h6f0ae12_0 pkgs/main
pytorch 1.10.2 cpu_py39h6f0ae12_0 pkgs/main
Note, only 1.10.2 seems to be available.
If you need a specific version of pytorch other than that, you will probably need to download and install from source.
| https://stackoverflow.com/questions/71846982/ |
The parameters of the model with custom loss function doesn’t upgraded thorough its learning over epochs | Thank you for reading my post.
I’m currently developing the peak detection algorithm using CNN to determine the ideal convolution kernel which is representable as the ideal mother wavelet function that will maximize the peak detection accuracy.
To begin with, I created my own IoU loss function and the simple model and tried to run the learning. The execution itself worked without any errors, but somehow it failed.
The parameters of the model with custom loss function doesn't upgraded thorough its learning over epochs
My own loss function is described as below.
def IoU(inputs: torch.Tensor, labels: torch.Tensor,
smooth: float=0.1, threshold: float = 0.5, alpha: float = 1.0):
'''
- alpha: a parameter that sharpen the thresholding.
if alpha = 1 -> thresholded input is the same as raw input.
'''
thresholded_inputs = inputs**alpha / (inputs**alpha + (1 - inputs)**alpha)
inputs = torch.where(thresholded_inputs < threshold, 0, 1)
batch_size = inputs.shape[0]
intersect_tensor = (inputs * labels).view(batch_size, -1)
intersect = intersect_tensor.sum(-1)
union_tensor = torch.max(inputs, labels).view(batch_size, -1)
union = union_tensor.sum(-1)
iou = (intersect + smooth) / (union + smooth) # We smooth our devision to avoid 0/0
iou_score = iou.mean()
return 1- iou_score
and my training model is,
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Conv1d(1, 1, kernel_size=32, stride=1, padding=16),
nn.Linear(257, 256),
nn.LogSoftmax(1)
)
def forward(self, x):
return self.net(x)
model = MLP()
opt = optim.Adadelta(model.parameters())
# initialization of the kernel of Conv1d
def init_kernel(m):
if type(m) == nn.Conv1d:
nn.init.kaiming_normal_(m.weight)
print(m.weight)
plt.plot(m.weight[0][0].detach().numpy())
model.apply(init_kernel)
def step(x, y, is_train=True):
opt.zero_grad()
y_pred = model(x)
y_pred = y_pred.reshape(-1, 256)
loss = IoU(y_pred, y)
loss.requires_grad = True
loss.retain_grad = True
if is_train:
loss.backward()
opt.step()
return loss, y_pred
and lastly, the execution code is,
from torch.autograd.grad_mode import F
train_loss_arr, val_loss_arr = [], []
valbose = 10
epochs = 200
for e in range(epochs):
train_loss, val_loss, acc = 0., 0., 0.,
for x, y in train_set.as_numpy_iterator():
x = torch.from_numpy(x)
y = torch.from_numpy(y)
model.train()
loss, y_pred = step(x, y, is_train=True)
train_loss += loss.item()
train_loss /= len(train_set)
for x, y ,in val_set.as_numpy_iterator():
x = torch.from_numpy(x)
y = torch.from_numpy(y)
model.eval()
with torch.no_grad():
loss, y_pred = step(x, y, is_train=False)
val_loss += loss.item()
val_loss /= len(val_set)
train_loss_arr.append(train_loss)
val_loss_arr.append(val_loss)
# visualize current kernel to check whether the learning is on progress safely.
if e % valbose == 0:
print(f"Epoch[{e}]({(e*100/epochs):0.2f}%): train_loss: {train_loss:0.4f}, val_loss: {val_loss:0.4f}")
fig, axs = plt.subplots(1, 4, figsize=(12, 4))
print(y_pred[0], y_pred[0].shape)
axs[0].plot(x[0][0])
axs[0].set_title("spectra")
axs[1].plot(y_pred[0])
axs[1].set_title("y pred")
axs[2].plot(y[0])
axs[2].set_title("y true")
axs[3].plot(model.state_dict()["net.0.weight"][0][0].numpy())
axs[3].set_title("kernel1")
plt.show()
with these programs, I tried to evaluate this simple model, however, model parameters didn't change at all over epochs.
Visualization of the results at epoch 0 and 30.
epoch 0:
prediction and kernel at epoch0
epoch 30:
prediction and kernel at epoch30
As you can see, the kernel has not be modified through its learning over epochs.
I took a survey to figure out what causes this problem for hours but I'm still not sure how to fix my loss function and model into trainable ones.
Thank you.
| Try printing the gradient after loss.backward() with:
y_pred.grad()
I suspect what you'll find is that after a backward pass, the gradient of y_pred is zero. This means that either a.) gradient is not enabled for one or more of the variables at which the computation graph has a node, or b.) (more likely) you are using an operation which is not differentiable.
In your case, at a minimum torch.where is non-differentiable, so you'll need to replace that. Thersholding operations are non-differentiable and are generally replaced with "soft" thresholding operations (see Softmax instead of max function for classification) so that gradient computation still works. Try replacing this with a soft threshold or no threshold at all.
| https://stackoverflow.com/questions/71855440/ |
.float() in pytorch changes the value of an int | import torch
torch.set_printoptions(precision=1, sci_mode=False)
numeric_seq_id = 2021080918959999952
t = torch.tensor(numeric_seq_id)
tt = torch.tensor(numeric_seq_id).float() # !!!
print(t, tt)
output is
tensor(2021080918959999952) tensor(2021080905052848128.)
We could see that tt's value is changed after .float() transform.
Why is here such a difference on the value?
ps. pytorch's version = 1.10.1
python's version = 3.8
| This is not pytorch specific, but an artifact of how floats (or doubles) are represented in memory (see this question for more details), which we can also see in numpy:
import numpy as np
np_int = np.int64(2021080918959999952)
np_float = np.float32(2021080918959999952)
np_double = np.float64(2021080918959999952)
print(np_int, int(np_float), int(np_double))
Output:
2021080918959999952 2021080905052848128 2021080918960000000
| https://stackoverflow.com/questions/71856490/ |
Splitting pytorch dataloader into numpy arrays | In principle I'd like to do the opposite of what was done here https://datascience.stackexchange.com/questions/45916/loading-own-train-data-and-labels-in-dataloader-using-pytorch.
I have a Pytorch dataloader train_dataloader with shape (2000,3). I want to store the 3 dataloader columns in 3 separate numpy arrays. (The first column of the dataloader contains the data, the second column contains the labels.)
I managed to do it for the last batch of the train_dataloader (see below), but unfortunately couldn't make it work for the whole train_dataloader.
for X, y, ind in train_dataloader:
pass
train_X = np.asarray(X, dtype=np.float32)
train_y = np.asarray(y, dtype=np.float32)
Any help would be very much appreciated!
| You can collect all the data:
all_X = []
all_y = []
for X, y, ind in train_dataloader:
all_X.append(X)
all_y.append(y)
train_X = torch.cat(all_X, dim=0).numpy()
train_y = torch.cat(all_y, dim=0).numpy()
| https://stackoverflow.com/questions/71869006/ |
Pytorch DataLoader shuffle=False? | I used Pytorch DataLoader to create My "batch-data" loder,but I got some problem.
As the definition of the pytorch DataLoader Shuffer.
shuffle (bool, optional) – set to True to have the data reshuffled at every epoch (default: False)
the data will be reshuffled after every epoch.
But,though I set shuffle to False,I will probably also get the completely different batch every iteration in the same epoch which I expect .
testData = torchvision.datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor()
)
CurrentFoldTestDataLoader = data.DataLoader(testData, batch_size=32, shuffle=False)
for i in range(1000):
test_features, test_labels = next(iter(CurrentFoldTestDataLoader))
print(i,test_labels)
Here I got the same batch in every iteration.
0 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
1 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
2 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
3 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
4 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
5 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
6 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
7 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
8 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
9 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
10 tensor([9, 2, 1, 1, 6, 1, 4, 6, 5, 7, 4, 5, 7, 3, 4, 1, 2, 4, 8, 0, 2, 5, 7, 9,
1, 4, 6, 0, 9, 3, 8, 8])
Why is this? Is my understanding of the definition of shuffle inaccurate?
| The problem with your code is that you are re-instantiating the same iterator for each step in the for cycle. With shuffle=False the iterator generates the same first batch of images. Try to instantiate the loader outside the cycle instead:
loader = data.DataLoader(testData, batch_size=32, shuffle=False)
for i, data in enumerate(loader):
test_features, test_labels = data
print(i, test_labels)
| https://stackoverflow.com/questions/71871260/ |
Partially stacking Tensors | I have some output from a convolutional layer in PyTorch of the shape [b,c,h] where b is my batches, c is my channels, and h is the features. I want to stack these to feed into a fully-connected layer without changing the batches, so that they are in the shape [b, c*h]. How can I do this?
| Seems like a simple reshape or view should work:
input.shape # [b,c,h]
reshaped = input.view(input.shape[0],-1) # [b,c*h]
| https://stackoverflow.com/questions/71875549/ |
Cross layer in pytorch | How can I add a cross layer in pytorch (https://arxiv.org/abs/1708.05123). I would like to add such a cross layer into my neural network that comes before the deep layers as a way to better combine my features that are coming from a range of sources.
Thanks!
| There is a PyTorch implementation of the DCN architecture from paper you linked in the DeepCTR-Torch library. You can see the implementation here: https://github.com/shenweichen/DeepCTR-Torch/blob/master/deepctr_torch/models/dcn.py
If you pip install deepctr-torch then you can just use the CrossNet layer as a torch.Module:
from deepctr_torch.layers.interaction import CrossNet
crossnet = CrossNet(in_features=512)
| https://stackoverflow.com/questions/71877020/ |
Pytorch's autograd issue with joblib | There seems to be a problem mixing pytorch's autograd with joblib. I need to get gradient in parallel for a lot of samples. Joblib works fine with other aspects of pytorch, however, when mixing with autograd it gives errors. I made a very small example which shows serial version works fine but the parallel version crashes.
from joblib import Parallel, delayed
import numpy as np
torch.autograd.set_detect_anomaly(True)
tt = lambda x, grad=True: torch.tensor(x, requires_grad=grad)
def Grad(X, Out):
return autograd.grad(Out, X, create_graph=True, allow_unused=False)[0]
xs, ys = [], []
for i in range(10):
xi = tt(np.random.rand()).float()
yi = xi * xi
xs += [xi]
ys += [yi]
Grads_serial = [Grad(x, y) for x, y in zip(xs, ys)]
print("Grads_serial", Grads_serial)
Grads_parallel = Parallel(n_jobs=2)([delayed(Grad)(x, y) for x, y in zip(xs, ys)])
print("Grads_parallel", Grads_parallel)
The error message is not very helpful as well:
RuntimeError: One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.
| Joblib is not copying the graph associated with the operations to the different process. One way to work around it is to perform the computation inside the job.
import torch
from torch import autograd
from joblib import Parallel, delayed
import numpy as np
torch.autograd.set_detect_anomaly(False)
tt = lambda x, grad=True: torch.tensor(x, requires_grad=grad)
def Grad(X, Out):
# This will compute yi in the job, and thus will
# create the graph here
yi = Out[0](*Out[1])
# now the differentiation works
return autograd.grad(yi, X, create_graph=True, allow_unused=False)[0]
torch.set_num_threads(1)
xs, ys = [], []
for i in range(10):
xi = tt(np.random.rand()).float()
yi = lambda xi: xi * xi, [xi]
xs += [xi]
ys += [yi]
Grads_serial = [Grad(x, y) for x, y in zip(xs, ys)]
print("Grads_serial", Grads_serial)
Grads_parallel = Parallel(n_jobs=2)([delayed(Grad)(x, y) for x, y in zip(xs, ys)])
print("Grads_parallel", Grads_parallel)
Edit
More philosophical questions are
(1) does it make sense to use joblib parallelism, if you can simply vectorize your operations and let torch to use intraoperator parallelism?
(2) mak14 mentioned using threading backend, it is good that it fixes your example. But multiple threads will use only one CPU, it makes sense for IO bounded jobs, like making HTTP requests, but not for CPU bounded operations.
Edit #2
The existence of torch.multiprocessing suggests that gradients require some special treatment, you could attempt to write a backend to joblib using torch.multiprocessing instead of multiprocessing or threading.
Here you find an overview to how graphs are constructed in both frameworks
https://www.tensorflow.org/guide/intro_to_graphs
https://pytorch.org/blog/computational-graphs-constructed-in-pytorch/
But I fear that to give a definite answer as to why one works and not the other will have to look into the implementation.
| https://stackoverflow.com/questions/71879164/ |
How to change an image which has dimensions (512, 512, 3) to a tensor of size ([1, 3, 224, 224]) | I was trying to implement a paper where the input dimensions are meant to be a tensor of size ([1, 3, 224, 224]). My current image size is (512, 512, 3).
How do I resize and convert in order to input to the model?
| Assuming image already converted to torch.Tensor and has shape (512, 512, 3), one of possible ways:
from torchvision.transforms import Resize
image = image.permute((2, 0, 1)) # convert to (C, H, W) format
image = image.unsqueeze(0) # add fake batch dimension
resize = Resize((224, 224))
new_image = resize(image)
Now new_image.shape equals to (1, 3, 224, 224)
| https://stackoverflow.com/questions/71880540/ |
Pytorch tensor - randomly replace values that meet condition | I have a Pytorch tensor mask of dimensions,
torch.Size([8, 24, 24])
with unique values,
> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2093, 1054, 1461]))
I wish to randomly replace the number of 2s to 0s, such that the unique values and counts in the tensor become,
> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2500, 1054, 1054]))
I have tried using torch.where to no success. How can this be achieved?
| One of the possible solutions is through flattening via view and numpy.random.choice:
from numpy.random import choice
idx = torch.where(mask.view(-1) == 2)[0] # get all indicies of 2 in flat tensor
num_to_change = 2500 - 2093 # as follows from example abow
idx_to_change = choice(idx, size=num_to_change, replace=False)
mask.view(-1)[idx_to_change] = 0
| https://stackoverflow.com/questions/71885228/ |
Customizing optimizer in pytorch lightning | Here I have implemented a custom optimizer in normal pytorch. I am trying to do the same thing in pytorch lightning but don't know how to.
def run_epoch(data_iter, model, loss_compute, model_opt):
"Standard Training and Logging Function"
start = time.time()
total_tokens = 0
total_loss = 0
tokens = 0
sofar = 0
for i, batch in enumerate(data_iter):
sofar = sofar + len(batch.src)
output = model.forward(batch.src, batch.trg,
batch.src_mask, batch.trg_mask)
loss = loss_compute(output, batch.trg_y, batch.ntokens)
loss.backward()
if model_opt is not None:
model_opt.step()
model_opt.optimizer.zero_grad()
total_loss += loss
total_tokens += batch.ntokens
tokens += batch.ntokens
tokens = 0
return total_loss / total_tokens
class CustomOptimizer:
def __init__(self, model_size, factor, warmup, optimizer):
self.optimizer = optimizer
self._step = 0
self.warmup = warmup
self.factor = factor
self.model_size = model_size
self._rate = 0
def step(self):
self._step += 1
rate = self.rate()
for p in self.optimizer.param_groups:
p['lr'] = rate
self._rate = rate
self.optimizer.step()
def rate(self, step=None):
"Implement `lrate` above"
if step is None:
step = self._step
return self.factor * (self.model_size ** (-0.5) * min(step ** (-0.5), step *
self.warmup ** (-1.5)))
if __name__ == "__main__":
model = create_model(V, V, N=2)
customOptimizer = CustomOptimizer(model.src_embed[0].d_model,
1, 400,
torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98),
eps=1e-9))
for epoch in range(10):
model.train()
run_epoch(data, model,
LossCompute(model.generator, LabelSmoothing),
customOptimizer)
I tried my best to follow the pytorch lightning official documentation and the code below is my attempt. The code does run smoothly without error. But the losses in each epoch goes down very slowly. So I use the debugger in pycharm and find out that the learning rate of customOptimizer at line customOptimizer.step() always stays as the same value "5.52471728019903e-06". Whereas in the implmentation in normal pytorch shown above does successfully change the learning rate as the training goes on.
class Model(pl.LightningModule)
def __init__(self, ....)
self.automatic_optimization = False
:
:
:
:
:
:
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9)
def training_step(self, batch, batch_idx):
optimizer = self.optimizers()
customOptimizer =
CustomOptimizer(self.src_embed[0].d_model, 1, 400,
optimizer.optimizer)
batch = Batch(batch[0], batch[1])
out = self(batch.src, batch.trg, batch.src_mask, batch.trg_mask)
out = self.generator(out)
labelSmoothing = LabelSmoothing(size=tgt_vocab, padding_idx=1, smoothing=0.1)
loss = labelSmoothing(out.contiguous().view(-1, out.size(-1)),
batch.trg_y.contiguous().view(-1)) / batch.ntokens
loss.backward()
customOptimizer.step()
customOptimizer.optimizer.zero_grad()
log = {'train_loss': loss}
return {'loss': loss, 'log': log}
if __name__ == '__main__':
if True:
model = model(......)
trainer = pl.Trainer(max_epochs=5)
trainer.fit(model, train_dataloaders=trainLoader)
| Thank you it works.
class Model(pl.LightningModule)
def __init__(self, ....)
self.automatic_optimization = False
self.customOptimizer = None
:
:
:
:
:
:
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9)
def training_step(self, batch, batch_idx):
if self.customOptimizer = None:
optimizer = self.optimizers()
self.customOptimizer =
CustomOptimizer(self.src_embed[0].d_model, 1, 400,
optimizer.optimizer)
batch = Batch(batch[0], batch[1])
out = self(batch.src, batch.trg, batch.src_mask, batch.trg_mask)
out = self.generator(out)
labelSmoothing = LabelSmoothing(size=tgt_vocab, padding_idx=1, smoothing=0.1)
loss = labelSmoothing(out.contiguous().view(-1, out.size(-1)),
batch.trg_y.contiguous().view(-1)) / batch.ntokens
loss.backward()
self.customOptimizer.step()
self.customOptimizer.optimizer.zero_grad()
log = {'train_loss': loss}
return {'loss': loss, 'log': log}
if __name__ == '__main__':
if True:
model = model(......)
trainer = pl.Trainer(max_epochs=5)
trainer.fit(model, train_dataloaders=trainLoader)```
| https://stackoverflow.com/questions/71888793/ |
network quantization——Why do we need "zero_point"? Why symmetric quantization doesn't need "zero point"? | I have Googled all the days, but can't still find the answer I need. There must be some misunderstandings in my brain. Could you please help me out?
1. Why do we need "zero_point"?
quantization:q=round(r/scale)+zero_point
I think that the zero_point (as an offset) shifts the scaled data to a proper position, for examle, in the figure below for unsigned 2 bits quantization, the zero point shifts [-1,2] to {0,1,2,3}
Am I right about this?
If I am wrong, please help correct me;
If I am right, then zero point is neceesary here (symmetric quantization), and why Jacob in IAO, Section 2.1 said zero-point is for zero-padding? It seems to me that this is just an outcome, not the root reason ?
2. Why doesn't symmetric quantization need "zero point"?
In Goolge White paper and some blogs, it it said that symmetric quantization dose not need zero point (since zero_point=0):
I can understand it in signed quantization, since both the floating range and the quantized range are symmetric, making zero_point=0.
However, how can we ignore zero_point in unsigned quantization where the quantized range [0,2^b-1] is not symmetric? Under this situation, it seems to me that we must have a positive zero point to shift the scaled data to the range [0, 2^b-1] as the figure below:
| I haven't found or got definitive answe yet.
But I convince myself as follow:
1.Why do we need "zero_point"?
The zero_point is definitely an offset or bias, shifting the scaled data to a proper position. There should be no doubts about it.
But what "the motivation" that Jocab methioned is that "Z is of the same tye as quantized q", instead of "having a zero point". The former makes sure the real "0" is quantized without error, thus when inferring in the quantized manner, it is the zero point (the same type as q) that is padded (instead of the value "0") in zero_padding (wihout error).
Why doesn't symmetric quantization need "zero point"?
I think the "if signed" and "if un-signed" in the formulas (7)-(9) of white paper are talking about the signs of x, i.e., the real, unquantized, floating-point values, instead of the quantized one. This means, signed floating-point values are quantized to signed fixed-point integer, with zero-point=0; and unsigned floating-point to unsigned fixed-point interger, with zero-point=0 as well.
| https://stackoverflow.com/questions/71891888/ |
Electra sequence classification with pytorch lightning issues with 'pooler_output' | I'm working on a sentence classification task with multiple binary labels attached to each sentence. I'm using Electra and pytorch lightning to do the job, but I've run into a problem. When I'm running the trainer.fit(model, data) I get the following error:
AttributeError: 'tuple' object has no attribute 'pooler_output'
The error is referring to line 13 in the section where I'm defining pl.LightningModule:
class CrowdCodedTagger(pl.LightningModule):
def __init__(self, n_classes: int, n_training_steps=None, n_warmup_steps=None):
super().__init__()
self.electra = ElectraModel.from_pretrained(ELECTRA_MODEL_NAME, return_dict=False) #changed ElectraModel to ElectraForSequenceClassification
self.classifier = nn.Linear(self.electra.config.hidden_size, n_classes)
self.n_training_steps = n_training_steps
self.n_warmup_steps = n_warmup_steps
self.criterion = nn.BCELoss()
def forward(self, input_ids, attention_mask, labels=None):
output = self.electra(input_ids, attention_mask=attention_mask)
output = self.classifier(output.pooler_output) # <---- this is the line the error is referring to.
output = torch.sigmoid(output)
loss = 0
if labels is not None:
loss = self.criterion(output, labels)
return loss, output
def training_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("train_loss", loss, prog_bar=True, logger=True)
return {"loss": loss, "predictions": outputs, "labels": labels}
def validation_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("val_loss", loss, prog_bar=True, logger=True)
return loss
def test_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("test_loss", loss, prog_bar=True, logger=True)
return loss
def training_epoch_end(self, outputs):
labels = []
predictions = []
for output in outputs:
for out_labels in output["labels"].detach().cpu():
labels.append(out_labels)
for out_predictions in output["predictions"].detach().cpu():
predictions.append(out_predictions)
labels = torch.stack(labels).int()
predictions = torch.stack(predictions)
for i, name in enumerate(LABEL_COLUMNS):
class_roc_auc = auroc(predictions[:, i], labels[:, i])
self.logger.experiment.add_scalar(f"{name}_roc_auc/Train", class_roc_auc, self.current_epoch)
def configure_optimizers(self):
optimizer = AdamW(self.parameters(), lr=2e-5)
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=self.n_warmup_steps,
num_training_steps=self.n_training_steps
)
return dict(
optimizer=optimizer,
lr_scheduler=dict(
scheduler=scheduler,
interval='step'
)
)
Can anyone point me in a direction to fix the error?
EXAMPLE OF DATA STRUCTURE (in CSV):
sentence label_1 label_2 label_3
Lorem ipsum dolor sit amet 1 0 1
consectetur adipiscing elit 0 0 0
sed do eiusmod tempor 0 1 1
incididunt ut labore et 1 0 0
Lorem ipsum dolor sit amet 1 0 1
| ELECTRA has no pooler layer like BERT (compare the return section for further information).
In case you only want to use the [CLS] token for your sequence classification, you can simply take the first element of the last_hidden_state (initialize electra without return_dict=False):
output = self.classifier(output.last_hidden_state[:, 0])
| https://stackoverflow.com/questions/71892648/ |
Pytorch RuntimeError: expected scalar type Double but found Float | I just started learning Pytorch and created my first LSTM. The dataset is time series data. Below is the training code.
Using .double() does not fix the error.
It is running in a Windows 11 environment.
import torch
import torch.nn as nn
from torch.optim import SGD
import math
import numpy as np
class Predictor(nn.Module):
def __init__(self, inputDim, hiddenDim, outputDim):
super(Predictor, self).__init__()
self.rnn = nn.LSTM(input_size = inputDim,
hidden_size = hiddenDim,
batch_first = True)
self.output_layer = nn.Linear(hiddenDim, outputDim)
def forward(self, inputs, hidden0=None):
output, (hidden, cell) = self.rnn(inputs, hidden0)
output = self.output_layer(output[:, -1, :])
return output
def mkDataSet(train_x, train_y=None):
t_train_x = []
t_train_y = []
sequence_length = 50
data_length = train_x.shape[0]
for offset in range(data_length-sequence_length):
t_train_x.append([train_x.iloc[offset + i] for i in range(sequence_length)])
try:
t_train_y.append([train_y.iloc[offset + i] for i in range(sequence_length)])
except:
pass
return t_train_x, t_train_y
def mkRandomBatch(train_x, train_t, batch_size=10):
batch_x = []
batch_t = []
for _ in range(batch_size):
idx = np.random.randint(0, len(train_x) - 1)
batch_x.append(train_x[idx])
try:
batch_t.append(train_t[idx])
except:
pass
return torch.tensor(batch_x), torch.tensor(batch_t)
def main(train_x=train_x, train_y=train_y, test_x=test_x):
training_size = 10000
test_size = 1000
epochs_num = 1000
hidden_size = 5
batch_size = 100
train_x_origin, train_y_origin, test_x_origin = train_x.copy(), train_y.copy(), test_x.copy()
train_x, train_t = mkDataSet(train_x, train_y)
test_x = mkDataSet(test_x)
model = Predictor(train_x_origin.shape[1], hidden_size, 1)
criterion = nn.MSELoss()
optimizer = SGD(model.parameters(), lr=0.01)
for epoch in range(epochs_num):
# training
running_loss = 0.0
training_accuracy = 0.0
for i in range(int(training_size / batch_size)):
optimizer.zero_grad()
data, label = mkRandomBatch(train_x, train_t, batch_size)
output = model(data)
loss = criterion(output, label)
loss.backward()
optimizer.step()
running_loss += loss.data[0]
training_accuracy += np.sum(np.abs((output.data - label.data).numpy()) < 0.1)
#test
test_accuracy = 0.0
for i in range(int(test_size / batch_size)):
offset = i * batch_size
data, label = torch.tensor(test_x[offset:offset+batch_size])
output = model(data, None)
training_accuracy /= training_size
print('%d loss: %.3f, training_accuracy: %.5f, test_accuracy: %.5f' % (
epoch + 1, running_loss, training_accuracy))
if __name__ == '__main__':
main(train_x, train_y, test_x)
Then I have this error:
RuntimeError Traceback (most recent call last)
.ipynb Cell 26' in <cell line: 113>()
109 print('%d loss: %.3f, training_accuracy: %.5f, test_accuracy: %.5f' % (
110 epoch + 1, running_loss, training_accuracy))
113 if __name__ == '__main__':
--> 114 main(train_x, train_y, test_x)
.ipynb Cell 26' in main(train_x, train_y, test_x)
87 optimizer.zero_grad()
89 data, label = mkRandomBatch(train_x, train_t, batch_size)
---> 91 output = model(data)
93 loss = criterion(output, label)
94 loss.backward()
File ~\Documents\lib\site-packages\torch\nn\modules\module.py:1110, in Module._call_impl(self, *input, **kwargs)
1106 # If we don't have any hooks, we want to skip the rest of the logic in
1107 # this function, and just call forward.
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
.ipynb Cell 26' in Predictor.forward(self, inputs, hidden0)
16 def forward(self, inputs, hidden0=None):
---> 17 output, (hidden, cell) = self.rnn(inputs, hidden0)
18 output = self.output_layer(output[:, -1, :])
20 return output
File ~\Documents\lib\site-packages\torch\nn\modules\module.py:1110, in Module._call_impl(self, *input, **kwargs)
1106 # If we don't have any hooks, we want to skip the rest of the logic in
1107 # this function, and just call forward.
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
File ~\Documents\lib\site-packages\torch\nn\modules\rnn.py:761, in LSTM.forward(self, input, hx)
759 self.check_forward_args(input, hx, batch_sizes)
760 if batch_sizes is None:
--> 761 result = _VF.lstm(input, hx, self._flat_weights, self.bias, self.num_layers,
762 self.dropout, self.training, self.bidirectional, self.batch_first)
763 else:
764 result = _VF.lstm(input, batch_sizes, hx, self._flat_weights, self.bias,
765 self.num_layers, self.dropout, self.training, self.bidirectional)
RuntimeError: expected scalar type Double but found Float
I think there is something wrong with 'data' and I print its type by print(type(data)):
torch.Tensor
which is float instead of double. Do you know what`s wrong? Thanks for your help!
| Your input data to the model is tensor of type Double, while the model expects a float tensor. Do this in the last line of mkRandomBatch() function:
return torch.tensor(batch_x).float(), torch.tensor(batch_t)
You may or may not get a similar error for label tensor as well during loss calculation, in that case try converting label tensor to float as well.
| https://stackoverflow.com/questions/71895263/ |
The DQN model cannot correctly come out the expected scores | I am working on a DQN training model of the game "CartPole-v1". In this model, the system did not remind any error information in the terminal. However, The result evaluation got worse.This is the output data:
episode: 85 score: 18 avarage score: 20.21 epsilon: 0.66
episode: 86 score: 10 avarage score: 20.09 epsilon: 0.66
episode: 87 score: 9 avarage score: 19.97 epsilon: 0.66
episode: 88 score: 14 avarage score: 19.90 epsilon: 0.65
episode: 89 score: 9 avarage score: 19.78 epsilon: 0.65
episode: 90 score: 10 avarage score: 19.67 epsilon: 0.65
episode: 91 score: 14 avarage score: 19.60 epsilon: 0.64
episode: 92 score: 13 avarage score: 19.53 epsilon: 0.64
episode: 93 score: 17 avarage score: 19.51 epsilon: 0.64
episode: 94 score: 10 avarage score: 19.40 epsilon: 0.63
episode: 95 score: 16 avarage score: 19.37 epsilon: 0.63
episode: 96 score: 16 avarage score: 19.33 epsilon: 0.63
episode: 97 score: 10 avarage score: 19.24 epsilon: 0.62
episode: 98 score: 13 avarage score: 19.17 epsilon: 0.62
episode: 99 score: 12 avarage score: 19.10 epsilon: 0.62
episode: 100 score: 11 avarage score: 19.02 epsilon: 0.61
episode: 101 score: 17 avarage score: 19.00 epsilon: 0.61
episode: 102 score: 11 avarage score: 18.92 epsilon: 0.61
episode: 103 score: 9 avarage score: 18.83 epsilon: 0.61
I'll show my code here. Firstly I constructed a neuron network:
import random
from torch.autograd import Variable
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import gym
from collections import deque
# construct a neuron network (prepare for step1, step3.2 and 3.3)
class DQN(nn.Module):
def __init__(self, s_space, a_space) -> None:
# inherit from DQN class in pytorch
super(DQN, self).__init__()
self.fc1 = nn.Linear(s_space, 360)
self.fc2 = nn.Linear(360, 360)
self.fc3 = nn.Linear(360, a_space)
# DNN operation architecture
def forward(self, input):
out = self.fc1(input)
out = F.relu(out)
out = self.fc2(out)
out = F.relu(out)
out = self.fc3(out)
return out
Instead of newing an agent class, I directly created the select function, which is used for select the corresponding action according to epsilon, and the back propagation function by gradient globally:
# define the action selection according to epsilon using neuron network (prepare for step3.2)
def select(net, epsilon, env, state):
# randomly select an action if not greedy
if(np.random.rand() <= epsilon):
action = env.action_space.sample()
return action
# select the maximum reward action by NN and the given state if greedy
else:
actions = net(Variable(th.Tensor(state))).detach().numpy()
action = np.argmax(actions[0])
return action
This is the back propagation function and the decreasing of epsilon:
# using loss function to improve neuron network (prepare for step3.3)
def backprbgt(net, store, batch_size, gamma, learning_rate):
# step1: create loss function and Adam optimizer
loss_F = nn.MSELoss()
opt = th.optim.Adam(net.parameters(),lr=learning_rate)
# step2: extract the sample in memory
materials = random.sample(store, batch_size)
# step3: Calculate arguments of loss function:
for t in materials:
Q_value = net(Variable(th.Tensor(t[0])))
# step3.1 Calculate tgt_Q_value in terms of greedy:
reward = t[3]
if(t[4] == True):
tgt = reward
else:
tgt = reward + gamma * np.amax(net(Variable(th.Tensor(t[2]))).detach().numpy()[0])
# print(tgt)
# tgt_Q_value = Variable(th.Tensor([[float(tgt)]]), requires_grad=True)
# print("Q_value:",Q_value)
Q_value[0][t[1]] = tgt
tgt_Q_value = Variable(th.Tensor(Q_value))
# print("tgt:",tgt_Q_value)
# step3.2 Calculate evlt_Q_value
# index = th.tensor([[t[1]]])
# evlt_Q_value = Q_value.gather(1,index) # gather tgt into the corresponding action
evlt_Q_value = net(Variable(th.Tensor(t[0])))
# print("evlt:",evlt_Q_value)
# step4: backward and optimization
loss = loss_F(evlt_Q_value, tgt_Q_value)
# print(loss)
opt.zero_grad()
loss.backward()
opt.step()
# step5: decrease epsilon for exploitation
def decrease(epsilon, min_epsilon, decrease_rate):
if(epsilon > min_epsilon):
epsilon *= decrease_rate
After that, the parameters and training progress are like this:
# training process
# step 1: set parameters and NN
episode = 1500
epsilon = 1.0
min_epsilon = 0.01
dr = 0.995
gamma = 0.9
lr = 0.001
batch_size = 40
memory_store = deque(maxlen=1500)
# step 2: define game category and associated states and actions
env = gym.make("CartPole-v1")
s_space = env.observation_space.shape[0]
a_space = env.action_space.n
net = DQN(s_space, a_space)
score = 0
# step 3: trainning
for e in range(0, episode):
# step3.1: at the start of each episode, the current result should be refreshed
# set initial state matrix
s = env.reset().reshape(-1, s_space)
# step3.2: iterate the state and action
for run in range(500):
# select action and get the next state according to current state "s"
a = select(net, epsilon, env, s)
obs, reward, done, info = env.step(a)
next_s = obs.reshape(-1,s_space)
s = next_s
score += 1
if(done == True):
reward = -10.0
memory_store.append((s,a,next_s,reward,done))
avs = score / (e+1)
print("episode:", e+1, "score:", run+1, "avarage score: {:.2f}".format(avs), "epsilon: {:.2}".format(epsilon))
break
# safe sample data
memory_store.append((s, a, next_s, reward, done))
if(run == 499):
print("episode:", e+1, "score:", run+1, "avarage score:", avs)
# step3.3 whenever the episode reach the integer time of batch size,
# we should backward to implore the NN
if(len(memory_store) > batch_size):
backprbgt(net, memory_store, batch_size, gamma, lr) # here we need a backprbgt function to backward
if(epsilon > min_epsilon):
epsilon = epsilon * dr
In the entire progress of training, there was no error or exception reminds. However, instead of the score increasing, the model performed lower score in the later steps. I think the theory of this model is correct but cannot find where the error appears although I tried lots of methods improving my code, including rechecking the input arguments of network, modifing the data structure of two arguments of loss function, etc. I paste my code here and hope to get some help on how to fix it. Thanks!
| Check out the code. For most parts it's the same as in snippet above, but there is some changes:
for step in replay buffer (which is called in code memory_store) namedtuple is used, and in update it's much easier to read t.reward, than looking what every index doing in step t
class DQN has method update, it's better to keep optimizer as attribute of class, than create it every time when calling function backprbgt
usage of torch.autograd.Variable here is unnecessary, so it's also was taken away
update in backprbgt taken per batch
decrease size of hidden layer from 360 to 32, while increase batch size from 40 to 128
updating network once in 10 episodes, but on 10 batches in replay buffer
average score prints out every 50 episodes based on 10 last episodes
add seeds
Also for RL it's take a long time to learn anything, so hoping that after 100 episodes it'll be close to even 100 points is somewhat optimistic. For the code in link averaging on 5 runs results in following dynamics
X axis -- number of episodes (yeah, 70 K, but it's like 20 minutes of real time)
Y axis -- number of steps in episode
As can be seen after 70K episodes algorithm achieves reward comparable to highest possible in this environment (highest -- 500). By tweaking hyperparameters faster rate can be achieved, but also remember it's DQN without any modification.
| https://stackoverflow.com/questions/71897010/ |
Speeding up pytorch operations for custom message dropout | I am trying to implement message dropout in my custom MessagePassing convolution in PyTorch Geometric. Message dropout consists of randomly ignoring p% of the edges in the graph. My idea was to randomly remove p% of them from the input edge_index in forward().
The edge_index is a tensor of shape (2, num_edges) where the 1st dimension is the "from" node ID and the 2nd is the "to" node ID". So what I thought I could do is select a random sample of range(N) and then use it to mask out the rest of the indices:
def forward(self, x, edge_index, edge_attr=None):
if self.message_dropout is not None:
# TODO: this is way too slow (4-5 times slower than without it)
# message dropout -> randomly ignore p % of edges in the graph i.e. keep only (1-p) % of them
random_keep_inx = random.sample(range(edge_index.shape[1]), int((1.0 - self.message_dropout) * edge_index.shape[1]))
edge_index_to_use = edge_index[:, random_keep_inx]
edge_attr_to_use = edge_attr[random_keep_inx] if edge_attr is not None else None
else:
edge_index_to_use = edge_index
edge_attr_to_use = edge_attr
...
However, it is way too slow, it makes an epoch go for 5' instead of 1' without (5 times slower). Is there a faster way to do this in PyTorch?
Edit: The bottleneck seems to be the random.sample() call, not the masking. So I guess what I should be asking is for faster alternatives to that.
| I managed to create a boolean mask using PyTorch's Dropout from Functional which is much faster. Now an epoch takes ~1' again. Better than other solutions with permutations that I found elsewhere.
def forward(self, x, edge_index, edge_attr=None):
if self.message_dropout is not None:
# message dropout -> randomly ignore p % of edges in the graph
mask = F.dropout(torch.ones(edge_index.shape[1]), self.message_dropout, self.training) > 0
edge_index_to_use = edge_index[:, mask]
edge_attr_to_use = edge_attr[mask] if edge_attr is not None else None
else:
edge_index_to_use = edge_index
edge_attr_to_use = edge_attr
...
| https://stackoverflow.com/questions/71900767/ |
How to turn 'Detections' object into string | I have this code which uses YOLOV5 and the weights of my trained model for inferencing images to detect and recognize the Egyptian currency. The object 'results' is of datatype 'Detections'. Is there someway to convert it into a string object as I need the label output for some purpose? I tried the str() function but it didn't work.
import torch
import os
import cv2
# Model
model = torch.hub.load(r'C:\Users\HAYA\PycharmProjects\curency_recognition\yolov5-master\yolov5-master', 'custom', path=r'C:\Users\HAYA\PycharmProjects\curency_recognition\_best.pt', source='local')
# Image
im = [r'E:\_currency.jpg']
# Inference
results = model(im)
# results
results.print()
results.save() # or .show()
results.show()
results.xyxy[0] # img1 predictions (tensor)
results.pandas().xyxy[0]
| The following function is kind of "buggy" but it can give you the required results
def results_parser(results):
s = ""
if results.pred[0].shape[0]:
for c in results.pred[0][:, -1].unique():
n = (results.pred[0][:, -1] == c).sum() # detections per class
s += f"{n} {results.names[int(c)]}{'s' * (n > 1)}, " # add to string
return s
I run the default yolov5s on Zidane image from the original repository, after getting results object I did the following:
# Model
model = torch.hub.load(r'/content/yolov5//', 'custom', path=r'/content/yolov5/yolov5s.pt', source='local')
# Image
im = [r'runs/detect/exp/zidane.jpg']
# Inference
results = model(im)
print(results_parser(results))
and the output is:
2 persons, 2 ties,
I wish you find this answer helpful, have a good day)
| https://stackoverflow.com/questions/71905867/ |
PyTorch autoencoder produces only one image | I'm new to PyTorch, and am having trouble with a basic autoencoder for a MNIST dataset. An autoencoder is a neural network that trains so that the output recovers the input through narrower layers in between, so that it learns a lower-dimensional representation of a high-dimensional input space.
The error is that all of my trained examples are outputting the same output. I'm not sure where the error is; I modified an online tutorial for this, and I believe all the different images aren't supposed to be outputted into one output. Could anyone help me find out if there is any simple bug or a wrong setting that I didn't spot?
Here is a code snippet that reproduces my problem.
# AE one-block
import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import torch
import torchvision
from torch import nn
from torchvision import transforms
from torchvision.transforms import ToTensor
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.optim.lr_scheduler import ExponentialLR
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
from torchvision import datasets
class AE(torch.nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.encoder = torch.nn.Sequential(
torch.nn.Linear(28 * 28, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 64),
torch.nn.ReLU(),
torch.nn.Linear(64, 36),
torch.nn.ReLU(),
torch.nn.Linear(36, 18),
torch.nn.ReLU(),
torch.nn.Linear(18, 9)
)
self.decoder = torch.nn.Sequential(
torch.nn.Linear(9, 18),
torch.nn.ReLU(),
torch.nn.Linear(18, 36),
torch.nn.ReLU(),
torch.nn.Linear(36, 64),
torch.nn.ReLU(),
torch.nn.Linear(64, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 28 * 28),
torch.nn.Sigmoid()
)
def forward(self, x):
x = self.flatten(x)
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
# Model initialization
model = AE()
loss_function = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr = 1e-1, weight_decay = 1e-8)
tensor_transform = transforms.ToTensor()
dataset = datasets.MNIST(root = "./data",
train = True,
download = True,
transform = tensor_transform)
loader = torch.utils.data.DataLoader(dataset = dataset,
batch_size = 32,
shuffle = True)
# Train
epochs = 5
outputs = []
losses = []
for epoch in range(epochs):
tic = time.monotonic()
print(f'Epoch = {epoch}')
for (image, _) in loader:
image = image.reshape(-1, 28*28)
reconstructed = model(image)
loss = loss_function(reconstructed, image)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss)
outputs.append((epochs, image, reconstructed))
toc = time.monotonic()
print(f'Time taken = {round(toc - tic, 2)}')
# Calculate difference between image outputs
im_batches = [image_batch for (image_batch, _) in loader]
only_image = model(im_batches[0]).detach().numpy()[0]
diff_total = 0
for i in range(len(im_batches)):
im_out = model(im_batches[i]).detach().numpy()
diff = np.linalg.norm(im_out - only_image)
print(f'Difference between outputs = {diff_total}')
# Show image outputs
im_out1 = model(im_batches[0]).detach().numpy()
im_out2 = model(im_batches[1]).detach().numpy()
for i in range(3):
plt.imshow(im_out1[i].reshape(28, 28))
plt.show()
for i in range(3):
plt.imshow(im_out2[i].reshape(28, 28))
plt.show()
My Python computation prints that the "difference between outputs" is zero, indicating that all output images from first 10 batches have the same output. A visual examination through directly looking at the first few images also reveals that outputs look like a strange amalgamation of all MNIST digit images.
| Decrease learning rate of optimizer from 1e-1 (which is really big) down to 1e-4 (which is somewhat standard) and increase number of epochs from 5 to 10, outputs will no longer be same. When printing "difference between outputs" variable diff_total is used and it does not changed, in cycle variable diff is computed and there is no interaction with diff_total. So even when epochs == 0 and model outputs are random, "difference between outputs" will also be equal to 0. Also it's better for memory consumption to do losses.append(loss.item()).
| https://stackoverflow.com/questions/71905964/ |
MultiHeadAttention giving very different values between versions (Pytorch/Tensorflow | I'm trying to recreate a transformer that was written in Pytorch and make it Tensorflow. Everything was going pretty well until each version of MultiHeadAttention started giving extremely different outputs. Both methods are an implementation of multi-headed attention as described in the paper "Attention is all you Need", so they should be able to achieve the same output.
I'm converting
self_attn = nn.MultiheadAttention(dModel, nheads, dropout=dropout)
to
self_attn = MultiHeadAttention(num_heads=nheads, key_dim=dModel, dropout=dropout)
For my tests, dropout is 0.
I'm calling them with:
self_attn(x,x,x)
where x is a tensor with shape=(10, 128, 50)
As expected from the documentation, the Pytorch version returns a tuple, (the target sequence length, embedding dimension), both with dimensions [10, 128, 50].
I'm having trouble getting the TensorFlow version to do the same thing. With Tensorflow I only get one tensor back, (size [10, 128, 50]) and it looks like neither the target sequence length or embedding dimension tensor from pytorch.
Based on the Tensorflow documentation I should be getting something comparable.
How can I get them to operate the same way? I'm guessing I'm doing something wrong with Tensorflow but I can't figure out what.
| nn.MultiheadAttention outputs by default tuple with two tensors:
attn_output -- result of self-attention operation
attn_output_weights -- attention weights averaged(!) over heads
At the same time tf.keras.layers.MultiHeadAttention outputs by default only one tensor attention_output (which corresponds to attn_output of pytorch). Attention weights of all heads also will be returned if parameter return_attention_scores is set to True, like:
output, scores = self_attn(x, x, x, return_attention_scores=True)
Tensor scores also should be averaged to achieve full correspondence with pytorch:
scores = tf.math.reduce_mean(scores, 1)
While rewriting keep in mind that by default (as in snippet in question) nn.MultiheadAttention expects input in form (seq_length, batch_size, embed_dim), but tf.keras.layers.MultiHeadAttention expects it in form (batch_size, seq_length, embed_dim).
| https://stackoverflow.com/questions/71906629/ |
Why do I get the error: ZeroDivisionError: 0.0 cannot be raised to a negative power error when loading deit model from Timm | I am trying to make inference on the DeiT small variant from timm.
from timm.models import create_model
model = create_model('deit_small_patch16_224', pretrained=True)
But I get the error:
self.scale = head_dim ** -0.5
ZeroDivisionError: 0.0 cannot be raised to a negative power.
However, creating a different model with model = create_model('deit_tiny_patch16_224', pretrained=True), I can make inference successfully and it works pretty fine. I understand this error is as a result of a zero being divided by a non-zero value or when being raised to the power of non-zero. But I don't quite get why this model is flagging an error from timm even before loading any data.
| It was an error with my version of timm. Upgrading timm: pip install --upgrade timm solved the problem.
| https://stackoverflow.com/questions/71910237/ |
Given groups=1, weight of size [10, 1, 5, 5], expected input[2, 3, 28, 28] to have 1 channels, but got 3 channels instead | I am trying to run CNN with train MNIST, but test on my own written digits. To do that I wrote the following code but I getting an error in title of this questions:
I am trying to run CNN with train MNIST, but test on my own written digits. To do that I wrote the following code but I getting an error in title of this questions:
batch_size = 64
train_dataset = datasets.MNIST(root='./data/',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = ImageFolder('my_digit_images/', transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
#print(self.conv1.weight.shape)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv3 = nn.Conv2d(20, 20, kernel_size=3)
#print(self.conv2.weight.shape)
self.mp = nn.MaxPool2d(2)
self.fc = nn.Linear(320, 10)
def forward(self, x):
in_size = x.size(0)
x = F.relu(self.conv1(x))
#print(x.shape)
x = F.relu(self.mp(self.conv2(x)))
x = F.relu(self.mp(self.conv3(x)))
#print("2.", x.shape)
# x = F.relu(self.mp(self.conv3(x)))
x = x.view(in_size, -1) # flatten the tensor
#print("3.", x.shape)
x = self.fc(x)
return F.log_softmax(x)
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
def train(epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test():
model.eval()
test_loss = 0
correct = 0
for data, target in test_loader:
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.nll_loss(output, target, size_average=False).data
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
| MNIST dataset contains black and white 1-channel images, while yours are 3-channeled RGB probably. Either recode your images or preprocess it like
img = img[:,0:1,:,:]
You can do it with custom transform, adding it after transforms.ToTensor()
| https://stackoverflow.com/questions/71913378/ |
LibTorch with OpenCV: version GOMP_5.0 not found | I'm trying to use OpenCV and LibTorch in the same project. Libtorch is installed in /usr/include/libtorch, downloaded from the PyTorch website. I'm using the cxx11 ABI version for CUDA 11.3.
Here's my CMakeLists.txt file:
cmake_minimum_required(VERSION 3.23 FATAL_ERROR)
project(chess-rl VERSION 1.0)
find_package( OpenCV REQUIRED )
set(CMAKE_PREFIX_PATH /usr/include/libtorch/share/cmake/)
find_package(Torch REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
include_directories(${OpenCV_LIBS})
include_directories(${TORCH_INCLUDE_DIRS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
file (GLOB SOURCE_FILES
${PROJECT_SOURCE_DIR}/src/*.cc
${PROJECT_SOURCE_DIR}/src/chess/*.cc
)
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS} "${TORCH_LIBRARIES}" )
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
The program has a #include <opencv2/opencv.hpp> line at the top.
Compilation works fine, but running the executable gives me this error:
/usr/include/libtorch/lib/libgomp-52f2fd74.so.1: version `GOMP_5.0' not found (required by /usr/lib/libvtkCommonCore.so.1)
I believe libtorch is trying to use a library that is incompatible with OpenCV.
If I run the program with LD_PRELOAD=/usr/lib/libgomp.so ./build/my-program, it runs fine.
How can I fix this error without having to use that environment variable? Is there a way to link that particular library in CMake?
| I faced the same problem, and your thread contributed to one solution.
You need to add a shared library in your CMakelists.txt file.
add_library(libName SHARED IMPORTED)
set_property(TARGET libName PROPERTY IMPORTED_LOCATION "/usr/lib/libgomp.so")
target_link_libraries(PROJECT_NAME
libName)
I hope I could help you
With kind regards
| https://stackoverflow.com/questions/71915342/ |
How to add multiple layers to an RNN module for sentiment analysis? Pytorch | I am trying to create a sentiment analysis model with Pytorch (newbie)
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim, dropout):
super().__init__() #to call the functions in the superclass
self.embedding = nn.Embedding(input_dim, embedding_dim) #Embedding layer to create dense vector instead of sparse matrix
self.rnn = nn.RNN(embedding_dim, hidden_dim)
self.fc = nn.Linear(hidden_dim, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, text):
embedded = self.embedding(text)
output, hidden = self.rnn(embedded)
hidden = self.dropout(hidden[-1,:,:])
nn.Sigmoid()
return self.fc(hidden)
However, the accuracy is below 50% and I would like to add an extra layer, maybe another linear before feeding it to the last linear to get the prediction. What kind of layers can I add after the RNN and before the last Linear? and also what should I feed it with?
I have tried simply adding another
output, hidden= self.fc(hidden)
but I get
ValueError: too many values to unpack (expected 2)
Which I believe is because the output of the previous layer with activation and dropout is different. The help is greatly appreciated.
Thanks
| You were very close, just change your forward call to:
import torch.nn.functional as F
class model_RNN(nn.Module):
def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim, dropout):
super().__init__() #to call the functions in the superclass
self.embedding = nn.Embedding(input_dim, embedding_dim) #Embedding layer to create dense vector instead of sparse matrix
self.rnn = nn.RNN(embedding_dim, hidden_dim)
self.hidden_fc = nn.Linear(hidden_dim,hidden_dim)
self.out_fc = nn.Linear(hidden_dim, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, text):
embedded = self.embedding(text)
output, hidden = self.rnn(embedded)
hidden = self.dropout(hidden[-1,:,:])
hidden = F.relu(torch.self.hidden_fc(hidden))
return self.out_fc(hidden)
Just a note, calling nn.Sigmoid() won't do anything to your model output because it will just create a sigmoid layer but won't call it on your data. What you want is probably torch.sigmoid(self.fc(hidden)). Although I would say it's not recommended to use an output activation because some common loss functions require the raw logits. Make sure you apply the sigmoid after the model call in eval mode though!
| https://stackoverflow.com/questions/71916899/ |
Trying to achieve same result with Pytorch and Tensorflow MultiheadAttention | I'm trying to recreate a transformer written in Pytorch and implement it in Tensorflow. The problem is that despite both the documentation for the Pytorch version and Tensorflow version, they still come out pretty differently.
I wrote a little code snippet to show the issue:
import torch
import tensorflow as tf
import numpy as np
class TransformerLayer(tf.Module):
def __init__(self, d_model, nhead, dropout=0):
super(TransformerLayer, self).__init__()
self.self_attn = torch.nn.MultiheadAttention(d_model, nhead, dropout=dropout)
batch_size = 2
seq_length = 5
d_model = 10
src = np.random.uniform(size=(batch_size, seq_length, d_model))
srcTF = tf.convert_to_tensor(src)
srcPT = torch.Tensor(src.reshape((seq_length, batch_size, d_model)))
self_attnTF = tf.keras.layers.MultiHeadAttention(key_dim=10, num_heads=5, dropout=0)
transformer_encoder = TransformerLayer(d_model=10, nhead=5, dropout=0.0)
output, scores = self_attnTF(srcTF, srcTF, srcTF, return_attention_scores=True)
print("Tensorflow Attendtion outputs:", output)
print("Tensorflow (averaged) weights:", tf.math.reduce_mean(scores, 1))
print("Torch Attendtion outputs:", transformer_encoder.self_attn(srcPT,srcPT,srcPT)[0])
print("Torch attention output weights:", transformer_encoder.self_attn(srcPT,srcPT,srcPT)[1])
and the result is:
Tensorflow Attendtion outputs: tf.Tensor(
[[[ 0.02602757 -0.14134401 0.00855263 0.4735083 -0.01851891
-0.20382246 -0.18152176 -0.21076852 0.08623976 -0.33548725]
[ 0.02607442 -0.1403394 0.00814065 0.47415024 -0.01882939
-0.20353754 -0.18291879 -0.21234266 0.08595885 -0.33613583]
[ 0.02524654 -0.14096384 0.00870436 0.47411725 -0.01800703
-0.20486829 -0.18163288 -0.21082559 0.08571021 -0.3362339 ]
[ 0.02518575 -0.14039244 0.0090138 0.47431853 -0.01775141
-0.20391947 -0.18138805 -0.2118245 0.08432849 -0.33521986]
[ 0.02556361 -0.14039293 0.00876258 0.4746476 -0.01891363
-0.20398234 -0.18229616 -0.21147579 0.08555281 -0.33639923]]
[[ 0.07844199 -0.1614371 0.01649148 0.5287745 0.05126739
-0.13851154 -0.09829871 -0.1621251 0.01922669 -0.2428589 ]
[ 0.07844222 -0.16024739 0.01805423 0.52941847 0.04975721
-0.13537636 -0.09829231 -0.16129729 0.01979005 -0.24491176]
[ 0.07800542 -0.160701 0.01677295 0.52902794 0.05082911
-0.13843337 -0.09805533 -0.16165744 0.01928401 -0.24327613]
[ 0.07815789 -0.1600025 0.01757433 0.5291927 0.05032986
-0.1368022 -0.09849522 -0.16172451 0.01929555 -0.24438493]
[ 0.0781548 -0.16028519 0.01764914 0.52846324 0.04941286
-0.13746066 -0.09787872 -0.16141161 0.01994199 -0.2440269 ]]], shape=(2, 5, 10), dtype=float32)
Tensorflow (averaged) weights: tf.Tensor(
[[[0.199085 0.20275716 0.20086522 0.19873264 0.19856 ]
[0.2015336 0.19960018 0.20218948 0.19891861 0.19775811]
[0.19906266 0.20318432 0.20190334 0.19812575 0.19772394]
[0.20074987 0.20104568 0.20269363 0.19744729 0.19806348]
[0.19953248 0.20176074 0.20314851 0.19782843 0.19772986]]
[[0.2010009 0.20053487 0.20004745 0.20092985 0.19748697]
[0.20034568 0.20035927 0.19955876 0.20062163 0.19911464]
[0.19967113 0.2006859 0.20012529 0.20047483 0.19904283]
[0.20132652 0.19996871 0.20019794 0.20008174 0.19842513]
[0.2006393 0.20000939 0.19938737 0.20054278 0.19942114]]], shape=(2, 5, 5), dtype=float32)
Torch Attendtion outputs: tensor([[[ 0.1097, -0.4467, -0.0719, -0.1779, -0.0766, -0.1247, 0.1557,
0.0051, -0.3932, -0.1323],
[ 0.1264, -0.3822, 0.0759, -0.0335, -0.1084, -0.1539, 0.1475,
-0.0272, -0.4235, -0.1744]],
[[ 0.1122, -0.4502, -0.0747, -0.1796, -0.0756, -0.1271, 0.1581,
0.0049, -0.3964, -0.1340],
[ 0.1274, -0.3823, 0.0754, -0.0356, -0.1091, -0.1547, 0.1477,
-0.0272, -0.4252, -0.1752]],
[[ 0.1089, -0.4427, -0.0728, -0.1746, -0.0756, -0.1202, 0.1501,
0.0031, -0.3894, -0.1242],
[ 0.1263, -0.3820, 0.0718, -0.0374, -0.1063, -0.1562, 0.1485,
-0.0271, -0.4233, -0.1761]],
[[ 0.1061, -0.4369, -0.0685, -0.1696, -0.0772, -0.1173, 0.1454,
0.0012, -0.3860, -0.1201],
[ 0.1265, -0.3820, 0.0762, -0.0325, -0.1082, -0.1560, 0.1501,
-0.0271, -0.4249, -0.1779]],
[[ 0.1043, -0.4402, -0.0705, -0.1719, -0.0791, -0.1205, 0.1508,
0.0018, -0.3895, -0.1262],
[ 0.1260, -0.3805, 0.0775, -0.0298, -0.1083, -0.1547, 0.1494,
-0.0276, -0.4242, -0.1768]]], grad_fn=<AddBackward0>)
Torch attention output weights: tensor([[[0.2082, 0.2054, 0.1877, 0.1956, 0.2031],
[0.2100, 0.2079, 0.1841, 0.1943, 0.2037],
[0.2007, 0.1995, 0.1929, 0.1999, 0.2070],
[0.1995, 0.1950, 0.1976, 0.2002, 0.2077],
[0.1989, 0.1969, 0.1970, 0.2024, 0.2048]],
[[0.2095, 0.1902, 0.1987, 0.2027, 0.1989],
[0.2090, 0.1956, 0.1997, 0.2004, 0.1952],
[0.2047, 0.1869, 0.2006, 0.2121, 0.1957],
[0.2073, 0.1953, 0.1982, 0.2014, 0.1978],
[0.2089, 0.2003, 0.1953, 0.1957, 0.1998]]], grad_fn=<DivBackward0>)
The output weights look similar but the base attention outputs are way off. Is there any way to make the Tensorflow model come out more like the Pytorch one? Any help would be greatly appreciated!
| In MultiHeadAttention there is also a projection layer, like
Q = W_q @ input_query + b_q
K = W_k @ input_keys + b_k
V = W_v @ input_values + b_v
Matrices W_q, W_k and W_v and biases b_q, b_k, b_v are initialized randomly, so difference in outputs should be expected (even between outputs of two distinct layers in pytorch on same input). After self-attention operation there is one more projection and it's also initialized randomly. Weights can be set manually in tensorflow by calling method set_weights of self_attnTF.
Correspondence between weights in tf.keras.layers.MultiHeadAttention and nn.MultiheadAttention not so clear, as an example: torch shares weights between heads, while tf keeps them unique. So if you are using weights of pretrained model from pytorch and try to put them in tensorflow model (for whatever reason) it'll certainly take more than five minutes.
Results should be the same if after initializing pytorch model and tensorflow model you step through their parameters and assign them identical values.
| https://stackoverflow.com/questions/71919267/ |
TypeError: setup() got an unexpected keyword argument 'stage' | I am trying to train my q&a model through pytorch_lightning. However while running the command trainer.fit(model,data_module) I am getting the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-72-b9cdaa88efa7> in <module>()
----> 1 trainer.fit(model,data_module)
4 frames
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _call_setup_hook(self)
1488
1489 if self.datamodule is not None:
-> 1490 self.datamodule.setup(stage=fn)
1491 self._call_callback_hooks("setup", stage=fn)
1492 self._call_lightning_module_hook("setup", stage=fn)
TypeError: setup() got an unexpected keyword argument 'stage'
I have installed and imported pytorch_lightning.
Also I have defined data_module = BioQADataModule(train_df, val_df, tokenizer, batch_size = BATCH_SIZE) where BATCH_SIZE = 2, N_EPOCHS = 6.
The model I have used is as follows:-
model = T5ForConditionalGeneration.from_pretrained(MODEL_NAME, return_dict=True)
Also, I have defined the class for the model as follows:-
class BioQAModel(pl.LightningModule):
def __init__(self):
super().__init__()
self.model = T5ForConditionalGeneration.from_pretrained(MODEL_NAME, return_dict=True)
def forward(self, input_ids, attention_mask, labels=None):
output = self.model(
input_ids = encoding["input_ids"],
attention_mask = encoding["attention_mask"],
labels=labels
)
return output.loss, output.logits
def training_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("train_loss", loss, prog_bar=True, logger=True)
return loss
def validation_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("val_loss", loss, prog_bar=True, logger=True)
return loss
def test_step(self, batch, batch_idx):
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]
labels = batch["labels"]
loss, outputs = self(input_ids, attention_mask, labels)
self.log("test_loss", loss, prog_bar=True, logger=True)
return loss
def configure_optimizers(self):
return AdamW(self.parameters(), lr=0.0001)
For any additional information required, please specify.
Edit 1: Adding BioQADataModule:
class BioQADataModule(pl.LightningDataModule):
def __init__(
self,
train_df: pd.DataFrame,
test_df: pd.DataFrame,
tokenizer: T5Tokenizer,
batch_size: int = 8,
source_max_token_len = 396,
target_max_token_len = 32
):
super().__init__()
self.batch_size = batch_size
self.train_df = train_df
self.test_df = test_df
self.tokenizer = tokenizer
self.source_max_token_len = source_max_token_len
self.target_max_token_len = target_max_token_len
def setup(self):
self.train_dataset = BioQADataset(
self.train_df,
self.tokenizer,
self.source_max_token_len,
self.target_max_token_len
)
self.test_dataset = BioQADataset(
self.test_df,
self.tokenizer,
self.source_max_token_len,
self.target_max_token_len
)
def train_dataloader(self):
return DataLoader(
self.train_dataset,
batch_size = self.batch_size,
shuffle = True,
num_workers = 4
)
def val_dataloader(self):
return DataLoader(
self.train_dataset,
batch_size = 1,
shuffle = True,
num_workers = 4
)
def test_dataloader(self):
return DataLoader(
self.train_dataset,
batch_size = 1,
shuffle = True,
num_workers = 4
)
| You need to add an extra argument stage=None to your setup method:
def setup(self, stage=None):
self.train_dataset = BioQADataset(
self.train_df,
self.tokenizer,
self.source_max_token_len,
self.target_max_token_len
)
self.test_dataset = BioQADataset(
self.test_df,
self.tokenizer,
self.source_max_token_len,
self.target_max_token_len
)
I've played with Pytorch Lightning myself for multi-GPU training here. Although some of the code is a bit outdated (metrics are a standalone module now), you might find it useful.
| https://stackoverflow.com/questions/71922261/ |
Using Dice metric in pytorch "torchmetrics" : dice_score() missing 2 required positional arguments: 'preds' and 'target' | I'm trying to use Dice metric from pytorch "torchmetrics". I found an example for using accuracy metric. like below :
from torchmetrics.classification import Accuracy
train_accuracy = Accuracy()
valid_accuracy = Accuracy()
for epoch in range(epochs):
for x, y in train_data:
y_hat = model(x)
# training step accuracy
batch_acc = train_accuracy(y_hat, y)
print(f"Accuracy of batch{i} is {batch_acc}")
for x, y in valid_data:
y_hat = model(x)
valid_accuracy.update(y_hat, y)
# total accuracy over all training batches
total_train_accuracy = train_accuracy.compute()
# total accuracy over all validation batches
total_valid_accuracy = valid_accuracy.compute()
print(f"Training acc for epoch {epoch}: {total_train_accuracy}")
print(f"Validation acc for epoch {epoch}: {total_valid_accuracy}")
# Reset metric states after each epoch
train_accuracy.reset()
valid_accuracy.reset()
However, when I replaced "Accuracy()" with "Dice_score()". like below:
from torchmetrics.functional import dice_score
train_accuracy =dice_score()
valid_accuracy =dice_score()
I got below error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-726045592283> in <module>
3 from torchmetrics.functional import dice_score
4
----> 5 train_accuracy_2 =dice_score()# Accuracy()
6 valid_accuracy_2 =dice_score()# Accuracy()
7
TypeError: dice_score() missing 2 required positional arguments: 'preds' and 'target'
Is there an example of using "Dice" metric from "torchmetrics"
| torchmetrics.classification.dice_score is the functional interface to the Dice score. That means it is a stateless function that expects the ground truth and predictions. There doesn't seem to be a module interface to the Dice score, like there is with accuracy.
torchmetrics.classification.Accuracy is a class that maintains state. Under the hood, it uses the functional interface, which is torchmetrics.functional.accuracy.
This is not enforced in any way, but typically classes are named with CamelCase and functions are named with snake_case.
| https://stackoverflow.com/questions/71931060/ |
Distributed sequential windowed data in pytorch | At every epoch of my training, I need to split my dataset in n batches of t consecutive samples. For example, if my data is [1,2,3,4,5,6,7,8,9,10], n = 2 and t = 3 then valid batches would be
[1-2-3, 4-5-6] and [7-8-9, 10-1-2]
[2-3-4, 8-9-10] and [5-6-7, 1-2-3]
My old version is the following, but it samples every point in the data, meaning that I would parse the whole dataset t times per epoch.
train_dataset = list(range(n))
train_sampler = None
if distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=bsize, shuffle=(train_sampler is None),
pin_memory=True, sampler=train_sampler)
for epoch in range(epochs):
if distributed:
train_sampler.set_epoch(epoch)
for starting_i in train_loader:
batch = np.array([np.mod(np.arange(i, i + t), n) for i in starting_i])
I have now implemented my own sampling function that splits the data into random batches where each sample is far from the two closest exactly t. In the non-distributed scenario, I can do
for epoch in range(epochs):
pad = np.random.randint(n)
train_loader = np.mod(np.arange(pad, n + pad, t), n)
np.random.shuffle(train_loader)
train_loader = np.array_split(train_loader,
np.ceil(len(train_loader) / bsize))
for starting_i in train_loader:
batch = np.array([np.mod(np.arange(i, i + t), n) for i in starting_i])
How do I make this version distributed? Do I need to make a custom torch.nn.parallel.DistributedDataParallel or torch.utils.data.DataLoader?
I have checked the DistributedSampler class
and my guess is that I have to override the __iter__ method. Am I right?
How does DistributedSampler split the dataset? Is it sequentially among num_replicas?
Say num_replicas = 2. Would my dataset be split into [1,2,3,4,5] and [6,7,8,9,10] between the 2 workers? Or is it random? Like [1,4,7,3,10] and [2,9,5,8,6]? First case would be ok for me because keeps samples sequential, but second would not.
| I ended up making my own Dataset where the data is [t, t + window, ... t + n * window]. Every time it is called it randomizes the starting indices of the window. Then the sampler does the shuffling as usual. For reproducibility, it has a set_seed method similar to set_epoch of samplers.
class SequentialWindowedDataset(Dataset):
def __init__(self, size, window):
self.size = size
self.window = window
self.seed = 0
self.data = np.arange(0, self.size, self.window)
def __getitem__(self, index):
rng = np.random.default_rng(self.seed)
pad = rng.integers(0, self.size)
data = (self.data + pad) % self.size
return data[index]
def __len__(self):
return len(self.data)
def set_seed(self, seed):
self.seed = seed
The following version randomizes the data outside the call and it is much much faster.
class SequentialWindowedDataset(Dataset):
def __init__(self, size, window):
self.size = size
self.window = window
self.data = np.arange(0, self.size, self.window)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
def randomize(self, seed):
rng = np.random.default_rng(seed)
pad = rng.integers(0, self.size)
self.data = (self.data + pad) % self.size
| https://stackoverflow.com/questions/71935107/ |
Is this a correct way to training U-Net using different GPUs | U-Net code:
class UNet(nn.Module):
def __init__(self):
super(UNet, self).__init__()
self.c1 = convBlock(1, 64).to('cuda:0')
self.d1 = downSample(64).to('cuda:0')
self.c2 = convBlock(64, 128).to('cuda:0')
self.d2 = downSample(128).to('cuda:0')
self.c3 = convBlock(128, 256).to('cuda:0')
self.d3 = downSample(256).to('cuda:1')
self.c4 = convBlock(256, 512).to('cuda:1')
self.d4 = downSample(512).to('cuda:1')
self.c5 = convBlock(512, 1024).to('cuda:1')
self.u1 = upSample(1024).to('cuda:1')
self.c6 = convBlock(1024, 512).to('cuda:1')
self.u2 = upSample(512).to('cuda:1')
self.c7 = convBlock(512, 256).to('cuda:1')
self.u3 = upSample(256).to('cuda:1')
self.c8 = convBlock(256, 128).to('cuda:1')
self.u4 = upSample(128).to('cuda:0')
self.c9 = convBlock(128, 64).to('cuda:0')
self.out = nn.Conv3d(64, 1, 3, 1, 1).to('cuda:0')
self.th = nn.Sigmoid().to('cuda:0')
def forward(self, x):
L1 = self.c1(x.to('cuda:0'))
L2 = self.c2(self.d1(L1.to('cuda:0')).to('cuda:0'))
L3 = self.c3(self.d2(L2.to('cuda:0')).to('cuda:0'))
L4 = self.c4(self.d3(L3.to('cuda:1')).to('cuda:1'))
L5 = self.c5(self.d4(L4.to('cuda:1')).to('cuda:1'))
R4 = self.c6(self.u1(L5.to('cuda:1'), L4.to('cuda:1')).to('cuda:1'))
R3 = self.c7(self.u2(R4.to('cuda:1'), L3.to('cuda:1')).to('cuda:1'))
R2 = self.c8(self.u3(R3.to('cuda:1'), L2.to('cuda:1')).to('cuda:1'))
R1 = self.c9(self.u4(R2.to('cuda:0'), L1.to('cuda:0')).to('cuda:0'))
return self.th(self.out(R1.to('cuda:0')).to('cuda:0'))
convBlock, downSample, upSample is layer in my own code.
I want to train 3DU-Net, but the GPU memory is not enough, so I want to use multiple GPUs to train this model.
I assign different U-net layers to different GPUs.
I want to ask if this is the correct way to use different GPUs to train models? And what's the best way to run multiple GPU training python scripts using the PyTorch module in the Linux server?
| Your code should work, but I'd suggest using some sort of variable to transfer submodel/tensor to different gpus. Something like this is what I've been using:
class MyModel(nn.Module):
def __init__(self, split_bool: bool = False):
self.submodule1 = ...
self.submodule2 = ...
self.split_bool = split_bool
if split_bool:
self.submodule1.cuda(0)
self.submodule2.cuda(1)
def forward(self, x):
x = self.submodule1(x)
if self.split_bool:
x = x.cuda(1) # Transfer tensor to second GPU
return self.submodule2(x)
For multiple training it really depends on your server. Are you using tensorboard/tensorboardX to plot results? You can launch multiple training script with different parameters with tmux, or even write your own bash script.
| https://stackoverflow.com/questions/71936047/ |
How to split data into training and testing set only using numpy not pandas | I'm doing CNN and trying split my data into training and testing datasets. After splitting, I want to use sklearn.preprocessing.StandardScaler to scale my testing data with the parameters of training data.
So before scaling, I need to split the data. I'm gonna use sklearn.model_selection.train_test_split, but to use that method I have to convert my data into a pandas.DataFrame. Since my data are for CNN, their lengths don't meet the requirements of a DataFrame
print(x.shape, delta.shape, z.shape, y.shape, non_spatial_data.shape, p.shape, g.shape)
# (15000, 175) (15000, 175) (15000, 175) (15000, 1225) (15000, 264) (15000, 175) (15000, 175)
The above are the sizes of my data after being flattened. 15000 is the sample size.
You can see the lengths of different data are different, which makes me unable to convert them into DataFrame. So how can I do the splitting only using numpy? Or is there any other method to do the whole splitting and scaling process?
PS: The data I am using for CNN are not really images. They are some data with spatial properties.
| Here's working example:
import pandas as pd
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
b = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
c = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
n = 0.2
spl = None
for arr in [a, b, c]:
if spl is None:
rand_ind = np.random.choice(range(len(arr)), len(arr))
spl, remaining = np.split(rand_ind, [int(n * len(rand_ind))])
print([arr[i] for i in spl])
| https://stackoverflow.com/questions/71938990/ |
Get character out of image with python | I want to detect the characters in a image like this with python:
In this case the code should return the result '6010001'.
How can I get the result out of this image? What do I need?
For your information, if the solution is a AI-solution, there are about 20.000 labeled images.
Thank you in forward :)
| Question: Are all the pictures of similar nature?
Meaning the Numbers are stamped into a similar material, or are they random pictures with numbers with different techniques (e.g. pen drawn, stamped etc.)?
If they are all quite similar (nice contrast as in sample pic), I would recommend to write your "own" AI, otherwise use an existing neural network / library (as I assume you may want to avoid the pain of creating your own neural network - and tag a lot of pictures).
If they pics are quite "similar", following suggested approach:
greyscale Image with increase contrast
define box (greater than a digit), scan over image and count 0s, define by trial valid range to detect a digit, avoid overlaps
each hit take area, split it in sectors, e.g. 6x4, count 0s
build a little knowledge base (csv file) of counts per sector for each number from 0-9 (e.g. a string); you will end up in the database with multiple valid strings per each number, just ensure they are unique (otherwise redefine steps 1-3)
In addition I recommend to make yourself a smart knowledge database, meaning: if the digit could not be identified, save digit picture and result. Then make yourself a little review program where it shows you the undefined digits and the result string, you can then manually add them to your knowledge database for the respective number.
Hope it helps. I used the same approach read a lot of different data from screen pictures and store them in a database. Works like a charm.
#better do it yourself than using a standard neural network :)
| https://stackoverflow.com/questions/71940073/ |
error: Dimension out of range (expected to be in range of [-1, 0], but got 1) when training to train a CNN model | I am trying to follow a code snippet which uses resnet18 to train a binary classification model since I am supposed to train a multi-classification model, I modified the code a bit by changing the loss function, activation function
import torchmetrics
class CheastCancer(pl.LightningModule):
def __init__(self,init_weights=True):
super().__init__()
self.model = torchvision.models.resnet18()
self.model.conv1 = torch.nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.model.fc = torch.nn.Linear(in_features=512, out_features=3, bias=True)
self.optimizer = torch.optim.Adam(self.model.parameters(), lr = 1e-4)
self.loss_fn = torch.nn.CrossEntropyLoss()
self.train_acc = torchmetrics.Accuracy()
self.val_acc = torchmetrics.Accuracy()
def forward(self, data):
pred = self.model(data)
return pred
def training_step(self, batch, batch_idx):
img, label = batch
label = label.float()
pred = self(img)[:,0]
loss = self.loss_fn(pred,label)
self.log("Train Loss", loss)
self.log("Step Train ACC", self.train_acc(torch.softmax(pred), label.int()))
return loss
def training_epoch_end(self, outs):
self.log("Train ACC", self.train_acc.compute())
def validation_step(self, batch, batch_idx):
img, label = batch
label = label.float()
pred = self(img)[:,0]
loss = self.loss_fn(pred,label)
self.log("Train Loss", loss)
self.log("Step Train ACC", self.val_acc(torch.poisson(pred), label.int()))
return loss
def training_epoch_end(self, outs):
self.log("Train ACC", self.val_acc.compute())
def configure_optimizers(self):
return [self.optimizer]
However, I received the following error message:
LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]
| Name | Type | Params
-----------------------------------------------
0 | model | ResNet | 11.2 M
1 | loss_fn | CrossEntropyLoss | 0
2 | train_acc | Accuracy | 0
3 | val_acc | Accuracy | 0
-----------------------------------------------
11.2 M Trainable params
0 Non-trainable params
11.2 M Total params
44.687 Total estimated model params size (MB)
Sanity Checking:
0/? [00:00<?, ?it/s]
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/connectors/data_connector.py:245: PossibleUserWarning: The dataloader, val_dataloader 0, does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` (try 8 which is the number of cpus on this machine) in the `DataLoader` init to improve performance.
category=PossibleUserWarning,
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-132-5af489ac4112> in <module>()
----> 1 trainer.fit(model, train_loader, val_loader)
17 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
2844 if size_average is not None or reduce is not None:
2845 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2846 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
2847
2848
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
from what I have search so far, this error usually emerges when the dimension of the label is not the same as the prediction. But I am not sure how can I fix it? Could somebody help please.
| If you see the docs you'll see that the targets input into CrossEntropyLoss are the class indices. I'm going to guess that maybe you've got it in one-hot format, so what you'll need to do is:
y = torch.Tensor([[0,0,1],[0,1,0]])
y = y.argmax(dim=1)
Other than that, see what the shape of your output is and see if it matches your expected shape of your labels.
| https://stackoverflow.com/questions/71947002/ |
Get the right tensor size | I want to have the right tensor size, because I get the following error in line of loss = criterion(out,target):
Expected input batch_size (4200) to match target batch_size (64).
How can I solve the challenge?
My output tensor has the size ([4200, 2]) and my target tensor ([64,2]).
The usecase is an image classification. There are two classes. My batch size is 64 and the images has a size of 180 x 115px in grayscale.
Please don't confiuse: There are some 'break' to test the code in the early state of development.
I load four batches, so 256 images.
With this method i will load my images:
def dataPrep(list_of_data, data_path, category, quantity):
global train_data
target_list = []
train_data_list = []
transform = transforms.Compose([
transforms.ToTensor(),
])
len_data = len(train_data)
print('Len_data: ', len_data)
for item in list_of_data:
f = random.choice(list_of_data)
list_of_data.remove(f)
print(data_path + f)
try:
img = Image.open(data_path +f)
except:
continue
img_crop = img.crop((310,60,425,240))
img_tensor = transform(img_crop)
print(img_tensor.size())
train_data_list.append(img_tensor)
isPseudo = 0
isTrue = 1
if category == True:
target = [isPseudo,isTrue]
else:
isPseudo =1
isTrue = 0
target = [isPseudo, isTrue]
target_list.append(target)
if len(train_data_list) >=64:
train_data.append((torch.stack(train_data_list), target_list))
train_data_list = []
target_list = []
if (len_data*64 + quantity) <= len(train_data)*64:
break
print(len(train_data) *64)
return list_of_data
After I loaded the images, I create my model and optimizer.
model = net.Netz()
optimizer = optim.SGD(model.parameters(), lr= 0.1, momentum = 0.8)
My class 'Netz' looks like this:
class Netz(nn.Module):
def __init__(self):
super(Netz, self).__init__()
self.conv1 = nn.Conv2d(1,10, kernel_size=5)
self.conv2 = nn.Conv2d(10,20, kernel_size = 5)
self.conv_dropout = nn.Dropout2d()
self.fc1 = nn.Linear(320,60)
self.fc2 = nn.Linear(60,2)
def forward(self,x):
x = self.conv1(x)
x = F.max_pool2d(x, 2)
x = F.relu(x)
x = self.conv2(x)
x = self.conv_dropout(x)
x = F.max_pool2d(x,2)
x = F.relu(x)
x = x.view(-1,320)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, -1)
At the end I will train my CNN:
def trainM(epoch):
model.train()
batch_id = 0
for batch_id, (data, target) in enumerate(net.train_data):
#data = data.cuda()
#target = target.cuda()
target = torch.Tensor(target[64*batch_id:64*(batch_id+1)])
data = Variable(data)
target = Variable(target)
optimizer.zero_grad()
out = model(data)
criterion = F.nll_loss
print('Size of out:', out.size())
print('Size of target:', target.size())
loss = criterion(out,target)
loss.backward()
optimizer.step()
print('Tain Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch,batch_id*len(data), len(net.train_data.dataset), 100*batch_id/len(net.train_data), loss.item()))
batch_id += 1
break
for item in range(0,10):
trainM(item)
break
| The main problem is at Netz x = x.view(-1,320) you have 64 batches 20 channels 42 x 25 width and height if you reshape it to -1, 320 would get 4200 by 320.
I can suggest 3 possible options to preserve the batchsize;
(what is generally done) pad the input to become square, update convolution part so that its output before FC layers have high number of channels and small number of height and width. for instance obtain x.shape = (batchsize, 128,2,2) then make the fc1 = Linear(512, 60) and before that do x = x.reshape(x.shape[0], -1). (here before applying fc1 you may do a 1x1 convolution).
make the number of channels at the end of convolutions 1 i.e. get something like x.shape = (batchsize,1,42,25) then adopt fc1 accordingly.
dox=reshape(*x.shape[:2], -1) in other words preserve both chanel and batchsize. Add another FC layer fc_e = Linear(20,1) to to compress your channels.
class Netz(nn.Module):
def __init__(self):
super(Netz, self).__init__()
self.conv1 = nn.Conv2d(1,10, kernel_size=5)
self.conv2 = nn.Conv2d(10,20, kernel_size = 5)
self.conv_dropout = nn.Dropout2d()
self.fc1 = nn.Linear(1050,60)
self.fc2 = nn.Linear(60,2)
self.fce = nn.Linear(20,1)
def forward(self,x):
x = self.conv1(x)
x = F.max_pool2d(x, 2)
x = F.relu(x)
x = self.conv2(x)
x = self.conv_dropout(x)
x = F.max_pool2d(x,2)
x = F.relu(x)
x = x.reshape(x.shape[0],x.shape[1], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.fce(x.permute(0,2,1)).squeeze(-1)
return F.log_softmax(x, -1)
keep in mind that you have a trade off between the amount of information you want to be represented (should be high) and the number of inputs of Linear layer (not that high). At the end its a matter of how you chose to tackle the issue. The third one is the closest to your solution but I recommend figuring out a model complying with the first approach
| https://stackoverflow.com/questions/71950692/ |
Select tensor slice along a dimension based on index | I have a PyTorch tensor of the following shape: (100, 5, 100). I need to convert it into a tensor of shape (100, 100) by selecting from each row only one item in the second dimension, meaning that of those 5 elements I only need one, with its corresponding 100 elements.
To do this operation I have a second tensor of shape (100,) with the indices that specify which of those 5 items should be selected in each row.
Is there a simple way to perform this selection without having to mess with the dimensions too much?
| Suppose tensor with indicies called idx and have shape (100,). Tensor with values called source. Then to select:
result = source[torch.arange(100), idx]
| https://stackoverflow.com/questions/71950956/ |
Learnable scalar weight in PyTorch and guarantee the sum of scalars is 1 | I have code like this:
class MyModule(nn.Module):
def __init__(self, channel, reduction=16, n_segment=8):
super(MyModule, self).__init__()
self.channel = channel
self.reduction = reduction
self.n_segment = n_segment
self.conv1 = nn.Conv2d(in_channels=self.channel, out_channels=self.channel//self.reduction, kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(in_channels=self.channel, out_channels=self.channel//self.reduction, kernel_size=1, bias=False)
self.conv3 = nn.Conv2d(in_channels=self.channel, out_channels=self.channel//self.reduction, kernel_size=1, bias=False)
#whatever
# learnable weight
self.W_1 = nn.Parameter(torch.randn(1), requires_grad=True)
self.W_2 = nn.Parameter(torch.randn(1), requires_grad=True)
self.W_3 = nn.Parameter(torch.randn(1), requires_grad=True)
def forward(self, x):
# whatever
## branch1
bottleneck_1 = self.conv1(x)
## branch2
bottleneck_2 = self.conv2(x)
## branch3
bottleneck_3 = self.conv3(x)
## summation
output = self.avg_pool(self.W_1*bottleneck_1 +
self.W_2*bottleneck_2 +
self.W_3*bottleneck_3)
return output
As you see, 3 learnable scalars (W_1, W_2, and W_3) are used for weighting purpose. But, this approach will not guarantee that the sum of those scalars is 1. How to make the summation of my learnable scalars equals to 1 in Pytorch? Thanks
| Keep it simple:
## summation
WSum = self.W_1 + self.W_2 + self.W_3
output = self.avg_pool( self.W_1/WSum *bottleneck_1 +
self.W_2/WSum *bottleneck_2 +
self.W_3/WSum *bottleneck_3)
Also, one can use distributivity law:
output = self.avg_pool(self.W_1*bottleneck_1 +
self.W_2*bottleneck_2 +
self.W_3*bottleneck_3) /WSum
| https://stackoverflow.com/questions/71952139/ |
How to import TensorMetric in pytorch lighting? | I want to import TensorMetric :
from pytorch_lightning.metrics.metric import TensorMetric
The program throws an exception:
ModuleNotFoundError: No module named 'pytorch_lightning.metrics'
My environment is:
Python 3.8.13
tokenizers==0.9.2
torch==1.5.1
transformers==3.4.0
pytorch-lightning==0.9.0
tensorboard==2.2.0
| 0.9 is a very old version of Lightning and a lot has changed/improved since then. I would recommend you to use the latest version of PyTorch Lightning (1.6).
Also, we have metrics as a separate library now TorchMetrics.
| https://stackoverflow.com/questions/71952252/ |
how to use is_valid_file of torchvision.datasets.ImageFolder | I am trying to load some images to train a small model. However, I couldn't use is_valid_file to distinguish my train and test images. For example my file is like that :
vegetables/tomato/gallery.jpg
for train set and
vegetables/tomato/probe.jpg
for test set. Basically every file like tomato and other selected vegetables has 2 images both test and train image.
Question: How can I use is_valid_file to distinguish them. I checked the documentation but I didn't understand.
This is my code
trainset = torchvision.datasets.ImageFolder(
root = "vegetables",
transform=imagenet_transform
)
testset = torchvision.datasets.ImageFolder(
root = "vegetables",
transform=imagenet_transform
)
| I had the problem too!!! Only not to the vegetable problem, but to the cat-fish problem. You can find the datasets here on this page (https://www.kaggle.com/datasets/zuraiz/fish-vs-cats-imagenet-subdataset). The downloaded datasets have to be saved in the same folder where you saved your .ipynb file.
I use Google Colab (makes things a bit easier), which means I have an .ipynb file.
import torchvision
from PIL import Image, ImageFile
from torchvision import transforms
from torchvision.datasets import ImageFolder
from google.colab import drive
drive.mount('/content/drive')
ImageFile.LOAD_TRUNCATED_IMAGES = False
def check_Image(path):
try:
im = Image.open(path)
return True
except:
return False
# train_data_path = "/.train/"
in order to get your path you have to go (in my case) - drive -> MyDrive -> Pytorch Projects -> 02 Chapter -> Fish-vs-Cats -> train -> 3 points on the right -> copy path
train_data_path = "/content/drive/MyDrive/Pytorch Projects/02 Chapter/Fish-vs-Cats/train"
img_transform = transforms.Compose([
transforms.Resize((64,64)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
train_data = ImageFolder(root=train_data_path,
transform=img_transform,
is_valid_file=check_Image)
| https://stackoverflow.com/questions/71955988/ |
UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed | I am creating Logistic Regression in Pytorch from scratch. But I am facing an issue when I am updating trainable parameters Weights & biases. This is my implementation,
class LogisticRegression():
def __init__(self, n_iter, lr):
self.n_iter = n_iter
self.lr = lr
def fit(self, dataset):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
n = next(iter(dataset))[0].shape[1]
self.w = torch.zeros(n, requires_grad=True).to(device)
self.b = torch.tensor(0., requires_grad=True).to(device)
for i in range(self.n_iter):
with tqdm(total=len(dataset)) as pbar:
for x, y in dataset:
x = x.to(device)
y = y.to(device)
y_pred = self.predict(x.float())
loss = self.loss(y, y_pred)
loss.backward()
with torch.no_grad():
print(self.w, self.b)
self.w -= self.w.grad * self.lr
self.b -= self.b.grad * self.lr
self.w.grad.zero_()
self.b.grad.zero_()
pbar.update(1)
print(f'Epoch: {i} | Loss: {loss}')
def loss(self, y, y_pred):
y_pred = torch.clip(y_pred, 1e-7, 1 - 1e-7)
return -torch.mean(
y * torch.log(y_pred + 1e-7) +
(1 - y) * torch.log(1 - y_pred + 1e-7),
axis=0)
def predict(self, x):
return self.sigmoid(torch.matmul(x, self.w) + self.b)
def sigmoid(self, x):
return 1/(1 + torch.exp(-x))
As you can see when I am fitting the model with a dataset I am initializing Weights and biases with zeroes and set requires_grad=True so I can access gradients later. I used the sklearn breast cancer dataset,
X, y = load_breast_cancer(return_X_y=True) # load dataset
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # train test split
# convert all numpy arrays to torch tensor
x_train = torch.tensor(x_train)
x_test = torch.tensor(x_test)
y_train = torch.tensor(y_train)
y_test = torch.tensor(y_test)
# Making it a Torch dataset then into DataLoader
train_dataset = torch.utils.data.TensorDataset(x_train, y_train)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32)
test_dataset = torch.utils.data.TensorDataset(x_test, y_test)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32)
log = LogisticRegression(n_iter=10, lr=0.001)
log.fit(train_loader)
As soon as I fit the dataset into Logistic Regression it gives me this error (I have also added one print statement in Logistic regression just before gradient update in which it is clear that it has grad_fn parameter),
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], device='cuda:0', grad_fn=<ToCopyBackward0>) tensor(0., device='cuda:0', grad_fn=<ToCopyBackward0>)
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
At the start of this Error, it gives this User warning
UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations.
I need help to solve the error so the gradient update and the model trains successfully!
| Breast cancer dataset features have big range of possible values, from 0.001 to 1000, and big variances too, so it influence gradients (when gradients become too big it leads to instability and later to NaNs). To overcome such dependence it's common practice to normalize data after splitting, for example:
from sklearn import preprocessing
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True) # load dataset
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # train test split
scaler = preprocessing.StandardScaler().fit(x_train) # computing mean and variance of train data
x_train = scaler.transform(x_train) # normalizing train data
x_test = scaler.transform(x_test) # normalizing test data based on statistics of train
So after that everything should be fine.
| https://stackoverflow.com/questions/71958197/ |
apply ResNet on CIFAR10 after resizing (pyTorch) | Given a pre-trained ResNet152, in trying to calculate predictions bench-marks using some common datasets (using PyTorch), and the first RGB dataset that came to mind was CIFAR10. The thing is that CIFAR10 data is 3x32x32 and ResNet expects 3x224x224. I've resized the data using the known approach of transforms:
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
train = datasets.CIFAR10(root='./data', train=True, download=True, transform=preprocess)
test = datasets.CIFAR10(root='./data', train=False, download=True, transform=preprocess)
train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size)
test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size)
but this results in blurry samples and bad predictions. I was wondering what are the best approaches in those cases, as I see many papers using those datasets given advanced models like ResNes and VGG, and I'm not sure how this technical issue could be resolved.
thank you for your response!
| Yes, you need to resize input images to the size 3x224x224. By doing so, after a normal training procedure, you should achieve outstanding results on CIFAR-10 (like 96% on the test-set).
I guess the main problem is that you're using a network that is pre-trained on higher resolution images (resnet152 comes pre-trained on imageNet), without any other training you can't expect good results changing the dataset drastically.
| https://stackoverflow.com/questions/71959838/ |
Pytorch lightning resuming from checkpoint with new data | I'm wanting to continue the training process for a model using new data.
I understand that you can continue training a Pytorch Lightning model e.g.
pl.Trainer(max_epochs=10, resume_from_checkpoint='./checkpoints/blahblah.ckpt') for example, if you last checkpoint is saved at epoch 5. But is there a way to continue training by adding different data?
| Yes, when you resume from a checkpoint you can provide the new DataLoader or DataModule during the training and your training will resume from the last epoch with the new data.
trainer = pl.Trainer(max_epochs=10, resume_from_checkpoint='./checkpoints/blahblah.ckpt')
trainer.fit(model, new_train_dataloader)
| https://stackoverflow.com/questions/71961436/ |
On batch size, epochs, and learning rate of DistributedDataParallel | I have read these threads [1] [2] [3] [4], and this article.
I think I got how batch size and epochs works with DDP, but I am not sure about the learning rate.
Let's say I have a dataset of 100 * 8 images. In a non-distributed scenario, I set the batch size to 8, so each epoch will do 100 gradient steps.
Now I am in a multi-node multi-gpu scenario, with 2 nodes and 4 GPUs (so world size is 8).
I understand that I need to pass batches of 8 / 8 = 1, because each update will aggregate the gradients from the 8 GPUs. In each worker, the data loader will load still 100 batches, but each of 1 sample. So the whole dataset is parsed exactly once per epoch.
I checked and everything seems like that.
But what about the learning rate?
According to the official doc
When a model is trained on M nodes with batch=N, the gradient will be
M times smaller when compared to the same model trained on a single
node with batch=M*N if the loss is summed (NOT averaged as usual)
across instances in a batch (because the gradients between different
nodes are averaged). [...] But in most cases, you can just treat a
DistributedDataParallel wrapped model, a DataParallel wrapped model
and an ordinary model on a single GPU as the same (E.g. using the same
learning rate for equivalent batch size).
I understand that the gradients are averaged, so if the loss is averaged over samples nothing changes, while if it is summer we need to account for that. But does 'nodes' refer to the total number of GPUs across all cluster nodes (world size) or just cluster nodes? In my example, would M be 2 or 8? Some posts in the threads I linked say that the gradient is divided 'by the number of GPUs'. How exactly is the gradient aggregated?
| Please refer to the following discussion:
https://github.com/PyTorchLightning/pytorch-lightning/discussions/3706
"As far as I know, learning rate is scaled with the batch size so that the sample variance of the gradients is kept approx. constant.
Since DDP averages the gradients from all the devices, I think the LR should be scaled in proportion to the effective batch size, namely, batch_size * num_accumulated_batches * num_gpus * num_nodes
In this case, assuming batch_size=512, num_accumulated_batches=1, num_gpus=2 and num_noeds=1 the effective batch size is 1024, thus the LR should be scaled by sqrt(2), compared to a single gpus with effective batch size 512."
| https://stackoverflow.com/questions/71962572/ |
How can I speed up max pooling clusters of different sizes and shapes of an image? | I have clustered the pixels of an image into clusters of different sizes and shapes. I want to max pool each cluster as fast as possible because the max pooling happens in one layer of my CNN.
To clarify:
Input is a batch of images with the following shape [batch_size, height of image, width of image, number of channels]. I have clustered each image before I start training my CNN. So for each image I have a ndarray of labels with shape [height of image, width of image].
How can I max pool over all pixels of an image that have the same label for all labels? I understand how to do it with a of for loop but that is painstakingly slow. I am searching for a fast solution that ideally can max pool over every cluster of each image in less than a second.
For implementation, I use Python3.7 and PyTorch.
| I figured it out. torch_scatter. scatter_max(img, cluster_labels) outputs the max element from each cluster and removes the for loop from my code.
| https://stackoverflow.com/questions/71967972/ |
pytorch loading pretrained weights from json file | I downloaded a json file of word-embeddings. The file contents look like this:
{
"in":[0.052956,0.065460,0.066195,0.047072,0.052221,-0.082009,-0.061415,-0.116210,0.015629,0.099293,-0.085686,-0.028133,0.052221,0.058840,-0.077596,-0.073550,0.033282,0.077228,-0.045785,-0.027214,-0.034201,0.035672,-0.090835,-0.048175,0.001701,0.027949,-0.002195,0.088628,0.046521,0.048175,0.061047,-0.051853,-0.016089,0.041556,-0.064357,0.051853,-0.096351,-0.025007,0.074286,0.132391,0.083480,-0.026110,-0.035488,-0.006390,0.027030,0.077596,0.020318,-0.021605,-0.003861,0.080170,0.045050,0.070976,0.025375,-0.020410,-0.070976,0.000776,-0.036407,0.025926,0.061047,-0.085318,-0.066931,0.027030,-0.109590,-0.183876,-0.046337,0.039901,0.042843,0.135333,0.045969,0.065460,0.093409,-0.030340,0.017009,0.133862,-0.022341,-0.022341,0.088260,0.023444,-0.072447,0.050014,0.003540,-0.060311,0.047440,-0.015538,-0.041188,-0.102235,-0.047808,0.062886,-0.048175,0.016181,0.058105,-0.027949,-0.025375,-0.138275,-0.054795,0.011952,0.070241,-0.046337,-0.010711,-0.002597,0.008366,-0.119152,-0.012871,0.004666,-0.006574,-0.060679,-0.011492,-0.066195,0.002620,-0.012136,-0.009286,0.073550,-0.105177,-0.064724,-0.020226,0.040637,0.100028,0.084951,0.091202,0.064357,-0.005355,0.033649,-0.109590,-0.002413,-0.088628,-0.049279,0.053692,-0.070976,-0.022801,0.090467,0.060311,-0.071344,-0.122094,-0.058473,0.015997,-0.061415,0.002965,-0.118416,-0.073918,0.029972,0.029604,-0.006849,0.077596,0.051117,-0.032178,0.047808,-0.036959,0.015721,-0.125771,0.070241,0.070608,0.005172,0.040453,0.039533,-0.018388,-0.024455,-0.046337,-0.004183,0.072447,0.028501,0.009194,-0.033098,-0.005631,0.079434,0.015354,0.109590,0.061782,0.004344,0.003448,-0.069873,-0.104441,-0.043211,-0.038798,-0.098557,-0.105177,-0.015446,-0.020410,0.024639,0.079067,-0.001758,-0.017009,0.000379,-0.083480,0.063989,-0.097822,-0.013147,-0.000270,0.081273,0.066931,0.033649,0.018939,0.017928,0.061047,0.017836,-0.082744,0.004045,-0.013331,-0.025559,-0.024823,-0.123565,0.072079,-0.013791,0.003999,-0.025926,-0.033282,-0.050014,-0.013515,-0.022341,-0.005723,-0.038614,-0.040820,0.067299,-0.054059,0.011492,-0.062150,-0.023904,0.026846,-0.015997,-0.044682,-0.009837,0.035304,0.017376,0.015813,-0.059208,-0.006068,0.014710,-0.004183,0.031259,0.020962,0.010251,0.026110,-0.137539,0.090467,0.055898,-0.030891,-0.007493,0.032362,-0.005493,0.092673,0.043395,-0.040269,-0.024272,-0.006849,-0.035120,0.033098,-0.038246,0.051853,0.002252,-0.003149,-0.033282,0.055530,-0.009608,0.050750,0.004735,0.056634,-0.028501,0.003678,0.033649,-0.050750,0.007309,0.003563,0.015446,0.053692,0.128713,0.130920,0.041924,0.068770,-0.028133,0.037511,-0.029604,0.033282,0.047072,0.036591,-0.040085,0.036775,-0.098557,-0.021789,-0.027214,-0.045785,-0.043211,0.092673,-0.062150,-0.008964,0.094144,0.001023,0.048175,-0.080170,-0.108119,-0.031811,0.018112,-0.127242,-0.066931,-0.060679,0.048911,0.046153,-0.035672,-0.044314,-0.035856,0.010895,-0.047072],
"for":[-0.008512,-0.034224,0.032284,0.045868,-0.013143,-0.046221,-0.000948,-0.052219,0.046574,0.062451,-0.122785,-0.028756,0.051513,-0.018700,0.013143,0.098792,0.104438,-0.024345,-0.070566,-0.086796,-0.057511,0.045162,-0.048338,0.053630,0.016407,0.024169,-0.130547,0.037576,0.010012,0.067038,0.002536,-0.006571,-0.070213,0.049043,-0.006351,0.031931,-0.096675,-0.071977,0.023992,0.020200,0.112200,-0.012790,0.010320,-0.079387,-0.061745,-0.052924,-0.017818,0.124902,0.044633,0.064568,-0.017553,0.102321,-0.023816,0.019847,-0.112200,0.005689,-0.051160,0.031578,0.004344,-0.040399,-0.106555,0.020552,-0.095970,-0.127724,-0.065979,-0.036694,-0.018788,-0.107260,-0.058217,0.108672,-0.031402,0.057158,0.023992,0.065274,0.016407,-0.045162,0.118551,0.062098,-0.008953,0.141838,-0.044986,0.016230,-0.021787,0.015348,0.002404,-0.040046,-0.052924,0.021523,0.035989,0.012614,0.075506,0.028050,0.061392,-0.179238,0.050102,-0.107966,0.042163,0.069155,-0.024169,0.045515,0.015436,-0.105143,0.038811,-0.065626,-0.018347,0.032813,0.003837,-0.083621,-0.014113,0.087502,0.023287,0.068449,-0.046574,0.016407,0.087149,0.043574,0.087149,0.035283,0.067391,0.048338,0.021170,-0.024698,-0.080445,0.038635,-0.018524,0.012878,0.044986,-0.018700,0.105143,0.045162,0.077975,-0.117845,-0.070566,-0.076564,-0.061745,-0.064215,0.073036,-0.057511,0.006086,0.017377,0.094558,0.037047,0.058923,0.067743,-0.042340,-0.069860,-0.020464,-0.105143,-0.106555,0.105143,-0.012702,0.023816,-0.061745,-0.007939,-0.026815,-0.009879,0.025933,-0.005954,0.036341,-0.068449,0.034577,0.014995,0.022140,0.093853,0.038106,0.013584,-0.012702,0.025227,0.013231,-0.007145,-0.133370,-0.064921,-0.020993,-0.043927,-0.037047,-0.001709,0.047985,-0.059628,-0.028932,0.069507,-0.111494,-0.110789,0.020464,0.009482,0.021611,-0.008777,-0.069860,0.017906,0.139721,0.009394,0.017465,-0.025933,0.071272,-0.069860,-0.144660,-0.009967,0.062098,-0.057864,-0.127724,-0.126313,0.003705,-0.025227,-0.039517,0.067743,-0.067391,-0.008644,-0.000408,0.070566,0.017906,-0.028756,0.007057,0.085385,0.018612,0.088913,0.046574,0.051160,0.021170,-0.035812,-0.056453,0.020905,0.032990,-0.031049,0.018700,-0.037400,0.101615,0.003087,-0.027344,0.019847,0.043398,0.020464,0.020288,-0.026462,0.094558,-0.000070,-0.050102,-0.015966,0.049043,-0.016848,-0.011070,-0.042163,0.044104,0.000466,0.002889,-0.051513,0.066332,0.018965,0.014466,0.025580,-0.041810,-0.021434,0.019758,0.018171,0.043574,0.095264,-0.003153,0.001974,0.043222,0.071272,-0.066332,-0.033166,-0.012614,0.027697,-0.013849,0.033519,0.034577,0.070919,-0.029108,0.068096,-0.025051,-0.030520,0.050807,-0.009879,0.076917,0.011908,0.095264,-0.001224,-0.006130,-0.103026,-0.033695,-0.079387,0.059275,-0.029638,-0.013672,0.063509,-0.002029,0.172181,-0.034048,-0.016583,0.029461,0.021170,-0.016318,0.002690,-0.059628,0.058923,0.005733,0.000345,0.013319,0.051513,-0.025227,0.017465],
"that":[-0.012361,-0.022230,0.065540,0.039477,-0.086620,0.024913,-0.011163,-0.070522,0.092369,0.092752,-0.056341,-0.060557,-0.054042,0.060557,-0.108850,0.005102,0.008624,-0.011881,-0.000755,-0.023763,-0.000124,0.030087,-0.018972,-0.036028,0.074355,-0.043310,-0.050975,0.004791,0.000671,0.048676,-0.042735,0.011067,0.017439,-0.035261,0.087386,-0.030279,0.040244,0.019739,0.013319,0.049442,0.108083,0.106550,0.051359,-0.050592,-0.018876,-0.010492,-0.029129,0.003378,-0.012361,0.014948,0.085087,0.035070,-0.035261,-0.074738,0.068223,0.064390,0.005366,-0.103484,0.002144,-0.059407,0.017631,0.134912,-0.038136,0.030087,-0.069373,-0.013510,0.017152,0.105017,0.008384,0.039094,0.029895,-0.004120,0.048101,-0.039286,-0.083170,0.043693,0.121115,0.134146,0.037752,0.099651,0.064007,-0.079721,0.034495,-0.010636,-0.105017,-0.123414,0.019068,0.164041,-0.080104,-0.073589,0.038136,0.059024,0.002767,-0.096968,-0.018972,-0.001036,0.030087,0.005965,0.013894,0.034303,-0.077038,-0.045610,0.011067,0.032195,-0.027787,-0.018014,-0.102717,-0.113449,0.022709,-0.096202,-0.055958,-0.005605,-0.075888,0.045993,0.081637,0.020697,0.005941,0.028362,0.031620,0.041394,-0.160208,-0.026254,-0.022805,0.024913,-0.096968,-0.052892,0.012456,-0.067839,0.009821,-0.049442,-0.094669,0.018397,-0.103484,-0.092752,-0.009534,-0.086237,0.074738,-0.032962,0.014373,0.040627,0.011738,-0.124947,-0.017056,-0.004024,0.028171,-0.002383,-0.061324,-0.040244,-0.005821,0.068606,-0.018780,0.034686,-0.089303,0.016864,-0.003006,-0.034111,-0.081637,-0.145644,-0.035261,0.035261,-0.034878,0.014948,-0.016481,0.010588,0.011977,-0.023859,0.036603,0.080487,-0.010875,0.006468,-0.041394,0.015427,-0.059791,-0.070522,0.034495,0.006228,0.009917,-0.085087,-0.014564,-0.082021,-0.119581,-0.062090,-0.022613,-0.014660,0.076271,-0.006564,-0.027787,0.005917,0.045610,0.064390,0.022613,0.040052,0.002491,-0.014564,0.011738,-0.057108,-0.026829,0.034495,-0.038327,-0.126480,0.020122,0.028746,-0.000121,-0.000988,-0.031237,-0.025296,-0.012361,0.047718,0.076271,-0.011786,-0.026446,-0.012025,0.003665,0.025871,-0.064390,0.083554,0.121115,0.006899,-0.094285,0.048101,0.045993,0.030470,-0.012552,-0.034495,0.094285,-0.059024,0.098118,0.027596,0.057108,0.068606,0.016577,-0.057874,0.027021,-0.073972,0.009103,-0.044843,-0.061707,0.012552,0.059407,0.023955,0.003617,-0.114216,-0.019451,-0.084704,0.054042,0.045610,0.098118,-0.051359,0.004144,0.009294,0.054808,0.099651,0.051359,-0.013606,0.093519,-0.025488,0.113449,0.060174,-0.025296,-0.051742,0.049442,-0.049059,-0.075505,0.083554,-0.031237,0.091219,-0.007618,-0.027787,-0.051359,0.046184,0.127247,0.040244,0.124947,0.074738,0.059791,-0.072055,0.019739,-0.061707,0.070139,-0.045993,-0.031428,0.036028,0.024338,0.030662,0.027979,-0.083170,-0.029129,-0.126480,0.016768,0.000958,-0.008863,-0.012265,-0.026254,-0.016193,-0.015235,0.050209,0.015810,0.005390,0.047909,-0.116515],
...
I found this function to load pre-trained embeddings into pytorch:
self.embeds = torch.nn.Embedding.from_pretrained(weights)
My question is, how to load the .json file into the above function? I don't find the documentation helpful. From the docs:
CLASSMETHOD from_pretrained(
embeddings, freeze=True, padding_idx=None, max_norm=None, norm_type=2.0,
scale_grad_by_freq=False, sparse=False
)
embeddings (Tensor) – FloatTensor containing weights for the Embedding.
First dimension is being passed to Embedding as num_embeddings, second as embedding_dim.
How do I convert this json file to a "FloatTensor" in the proper format for this function?
Thanks!
| weights = torch.stack([torch.Tensor(value) for _, value in in_json.items()], dim=0)
| https://stackoverflow.com/questions/71969499/ |
Is there an equivalent of torch.distributions.Normal in LibTorch, the C++ API for PyTorch? | I am implementing a policy gradient algorithm with stochastic policies and since "ancillary" non-PyTorch operations are slow in Python, I want to implement the algorithm in C++. Is there a way to implement a normal distribution in the PyTorch C++ API?
| The Python implementation actually calls the C++ back-end in the at:: namespace (CPU, CUDA, where I found this). Until the PyTorch team and/or contributors implement a front-end in LibTorch, you can work around it with something like this (I only implemented rsample() and log_prob() because it's what I need for this use case):
constexpr double lz = log(sqrt(2 * M_PI));
class Normal {
torch::Tensor mean, stddev, var, log_std;
public:
Normal(const torch::Tensor &mean, const torch::Tensor &std) : mean(mean), stddev(std), var(std * std), log_std(std.log()) {}
torch::Tensor rsample() {
auto device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU;
auto eps = torch::randn(1).to(device);
return this->mean + eps * this->stddev;
}
torch::Tensor log_prob(const torch::Tensor &value) {
// log [exp(-(x-mu)^2/(2 sigma^2)) / (sqrt(2 pi) * sigma)] =
// = log [exp(-(x-mu)^2/(2 sigma^2))] - log [sqrt(2 pi) * sigma] =
// = -(x - mu)^2 / (2 sigma^2) - log(sigma) - log(sqrt(2 pi))
return -(value - this->mean)*(value - this->mean) / (2 * this->var) - this->log_std - lz;
}
};
| https://stackoverflow.com/questions/71970806/ |
ImportError: cannot import name 'x' from 'y' | (ldm) C:\WBC\latent-diffusion-main>python scripts/txt2img.py --prompt "a sunset behind a mountain range, vector image" --ddim_eta 1.0 --n_samples 1 --n_iter 1 --H 384 --W 1024 --scale 5.0
Loading model from models/ldm/text2img-large/model.ckpt
Traceback (most recent call last):
File "scripts/txt2img.py", line 108, in <module>
model = load_model_from_config(config, "models/ldm/text2img-large/model.ckpt") # TODO: check path
File "scripts/txt2img.py", line 19, in load_model_from_config
model = instantiate_from_config(config.model)
File "c:\wbc\latent-diffusion-main\ldm\util.py", line 78, in instantiate_from_config
return get_obj_from_str(config["target"])(**config.get("params", dict()))
File "c:\wbc\latent-diffusion-main\ldm\util.py", line 86, in get_obj_from_str
return getattr(importlib.import_module(module, package=None), cls)
File "C:\ProgramData\Anaconda3\envs\ldm\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "c:\wbc\latent-diffusion-main\ldm\models\diffusion\ddpm.py", line 12, in <module>
import pytorch_lightning as pl
File "C:\ProgramData\Anaconda3\envs\ldm\lib\site-packages\pytorch_lightning\__init__.py", line 20, in <module>
from pytorch_lightning import metrics # noqa: E402
File "C:\ProgramData\Anaconda3\envs\ldm\lib\site-packages\pytorch_lightning\metrics\__init__.py", line 15, in <module>
from pytorch_lightning.metrics.classification import ( # noqa: F401
File "C:\ProgramData\Anaconda3\envs\ldm\lib\site-packages\pytorch_lightning\metrics\classification\__init__.py", line 14, in <module>
from pytorch_lightning.metrics.classification.accuracy import Accuracy # noqa: F401
File "C:\ProgramData\Anaconda3\envs\ldm\lib\site-packages\pytorch_lightning\metrics\classification\accuracy.py", line 18, in <module>
from pytorch_lightning.metrics.utils import deprecated_metrics, void
File "C:\ProgramData\Anaconda3\envs\ldm\lib\site-packages\pytorch_lightning\metrics\utils.py", line 22, in <module>
from torchmetrics.utilities.data import get_num_classes as _get_num_classes
ImportError: cannot import name 'get_num_classes' from 'torchmetrics.utilities.data' (C:\ProgramData\Anaconda3\envs\ldm\lib\site-packages\torchmetrics\utilities\data.py)
I can't run a latent diffusion neural network. I'm using anaconda and the environment that comes with the neural network. I think I'm doing everything right, but something goes wrong. If you know how to solve this problem, I would be extremely grateful.
| Looking at your error, it appears get_num_classes doesn't exist anymore. I verified this by looking that their github and docs.
It was removed after this commit.
| https://stackoverflow.com/questions/71971105/ |
pytorch equivalent of Conv2D in tenserflow with stride of 2 and padding of (1,1) | I have conv1 = nn.Conv2d(3, 16, 3,stride= 2, padding = 1, bias=True, groups=1) . i need its corresponding api in tf.keras.layers.Conv2D.
Can anyone help me out
PS : Here i have a stride of 2
| I have found the solution , hope this might be help full to others as well . As it was difficult to match padding in torch and padding in keras with stride = 2
X = Input(shape = (10,10,3))
X1 = ZeroPadding2D(padding=(1,1), input_shape=(10, 10, 3), data_format="channels_last")(X)
conv1 = Conv2D(16, 3, padding = 'valid', strides = (2,2))(X1)
| https://stackoverflow.com/questions/71979310/ |
Matrix Vector Product across Multiple Dimensions | I have two arrays:
A = torch.rand((64, 128, 10, 10))
B = torch.rand((64, 128, 10))
I would like to compute the product, represented by C, where we do a matrix-vector multiplication across the first and second dimensions of A and B, so:
# C should have shape: (64, 128, 10)
for i in range(0, 64):
for j in range(0, 128):
C[i,j] = torch.matmul(A[i,j], B[i,j])
Does anyone know how to do this using torch.einsum? I tried the following, but I am getting an incorrect result.
C = torch.einsum('ijkl, ijk -> ijk', A, B)
| Here's the options with numpy. (I don't have torch)
In [120]: A = np.random.random((64, 128, 10, 10))
...: B = np.random.random((64, 128, 10))
Your iterative reference case:
In [122]: C = np.zeros((64,128,10))
...: # C should have shape: (64, 128, 10)
...: for i in range(0, 64):
...: for j in range(0, 128):
...: C[i,j] = np.matmul(A[i,j], B[i,j])
...:
matmul with full broadcasting:
In [123]: D = np.matmul(A, B[:,:,:,None])
In [125]: C.shape
Out[125]: (64, 128, 10)
In [126]: D.shape # D has an extra size 1 dimension
Out[126]: (64, 128, 10, 1)
In [127]: np.allclose(C,D[...,0]) # or use squeeze
Out[127]: True
The einsum equivalent:
In [128]: E = np.einsum('ijkl,ijl->ijk', A, B)
In [129]: np.allclose(C,E)
Out[129]: True
| https://stackoverflow.com/questions/71983170/ |
UserWarning: Failed to initialize NumPy: module compiled against API version 0xf but this version of numpy is 0xe (Triggered internally at | (my2022) C:\Users\donhu>pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
Looking in indexes: https://pypi.org/simple, https://download.pytorch.org/whl/cu113
Requirement already satisfied: torch in d:\programdata\anaconda3\envs\my2022\lib\site-packages (1.10.2)
Collecting torchvision
Downloading https://download.pytorch.org/whl/cu113/torchvision-0.12.0%2Bcu113-cp310-cp310-win_amd64.whl (5.4 MB)
|████████████████████████████████| 5.4 MB 1.1 MB/s
Collecting torchaudio
Downloading https://download.pytorch.org/whl/cu113/torchaudio-0.11.0%2Bcu113-cp310-cp310-win_amd64.whl (573 kB)
|████████████████████████████████| 573 kB 6.4 MB/s
Requirement already satisfied: typing_extensions in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from torch) (4.1.1)
Collecting torch
Downloading https://download.pytorch.org/whl/cu113/torch-1.11.0%2Bcu113-cp310-cp310-win_amd64.whl (2186.0 MB)
|████████████████████████████████| 2186.0 MB 4.7 kB/s
Requirement already satisfied: numpy in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from torchvision) (1.21.5)
Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from torchvision) (9.0.1)
Requirement already satisfied: requests in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from torchvision) (2.27.1)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from requests->torchvision) (1.26.8)
Requirement already satisfied: certifi>=2017.4.17 in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from requests->torchvision) (2021.5.30)
Requirement already satisfied: idna<4,>=2.5 in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from requests->torchvision) (3.3)
Requirement already satisfied: charset-normalizer~=2.0.0 in d:\programdata\anaconda3\envs\my2022\lib\site-packages (from requests->torchvision) (2.0.4)
Installing collected packages: torch, torchvision, torchaudio
Attempting uninstall: torch
Found existing installation: torch 1.10.2
Uninstalling torch-1.10.2:
Successfully uninstalled torch-1.10.2
Successfully installed torch-1.11.0+cu113 torchaudio-0.11.0+cu113 torchvision-0.12.0+cu113
(my2022) C:\Users\donhu>python
Python 3.10.4 | packaged by conda-forge | (main, Mar 30 2022, 08:38:02) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
D:\ProgramData\Anaconda3\envs\my2022\lib\site-packages\torch\_masked\__init__.py:223: UserWarning: Failed to initialize NumPy: module compiled against API version 0xf but this version of numpy is 0xe (Triggered internally at ..\torch\csrc\utils\tensor_numpy.cpp:68.)
example_input = torch.tensor([[-3, -2, -1], [0, 1, 2]])
>>> torch.FloatTensor([31, 1, 1989], [26, 8, 1987])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: new() received an invalid combination of arguments - got (list, list), but expected one of:
* (*, torch.device device)
didn't match because some of the arguments have invalid types: (list, list)
* (torch.Storage storage)
* (Tensor other)
* (tuple of ints size, *, torch.device device)
* (object data, *, torch.device device)
>>> torch.FloatTensor([[31, 1, 1989], [26, 8, 1987]])
tensor([[3.1000e+01, 1.0000e+00, 1.9890e+03],
[2.6000e+01, 8.0000e+00, 1.9870e+03]])
>>> import torchtorch.FloatTensor([[31, 1, 1989], [26, 8, 1987]])
File "<stdin>", line 1
import torchtorch.FloatTensor([[31, 1, 1989], [26, 8, 1987]])
^
SyntaxError: invalid syntax
>>> import torchtorch.FloatTensor([[31, 1, 1989], [26, 8, 1987]])
File "<stdin>", line 1
import torchtorch.FloatTensor([[31, 1, 1989], [26, 8, 1987]])
^
SyntaxError: invalid syntax
>>> import torch
>>> torch.FloatTensor([[31, 1, 1989], [26, 8, 1987]])
tensor([[3.1000e+01, 1.0000e+00, 1.9890e+03],
[2.6000e+01, 8.0000e+00, 1.9870e+03]])
>>> jupyter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'jupyter' is not defined
>>> notebook
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'notebook' is not defined
>>> jupyter-notebook
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'jupyter' is not defined
>>> exit()
(my2022) C:\Users\donhu>python -m notebook
[I 15:14:15.768 NotebookApp] The port 8888 is already in use, trying another port.
[I 15:14:15.769 NotebookApp] Serving notebooks from local directory: C:\Users\donhu
[I 15:14:15.770 NotebookApp] Jupyter Notebook 6.4.8 is running at:
[I 15:14:15.770 NotebookApp] http://localhost:8889/?token=a354cd600920030068b4020dfc955b40d721d0da3e749421
[I 15:14:15.770 NotebookApp] or http://127.0.0.1:8889/?token=a354cd600920030068b4020dfc955b40d721d0da3e749421
[I 15:14:15.770 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 15:14:15.828 NotebookApp]
To access the notebook, open this file in a browser:
file:///C:/Users/donhu/AppData/Roaming/jupyter/runtime/nbserver-14140-open.html
Or copy and paste one of these URLs:
http://localhost:8889/?token=a354cd600920030068b4020dfc955b40d721d0da3e749421
or http://127.0.0.1:8889/?token=a354cd600920030068b4020dfc955b40d721d0da3e749421
[I 15:15:03.168 NotebookApp] 302 GET /?token=a354cd600920030068b4020dfc955b40d721d0da3e749421 (::1) 1.000000ms
[W 15:15:09.559 NotebookApp] Notebook Untitled.ipynb is not trusted
[I 15:15:09.849 NotebookApp] Kernel started: d123ea3f-ccd3-4d2c-8bb0-2265c8610c76, name: python3
[I 15:15:17.878 NotebookApp] Starting buffering for d123ea3f-ccd3-4d2c-8bb0-2265c8610c76:c8907cbab1e34c409557d30a3227e5a6
[W 15:15:20.088 NotebookApp] Notebook Untitled.ipynb is not trusted
[I 15:17:20.272 NotebookApp] Saving file at /Untitled.ipynb
[W 15:17:20.272 NotebookApp] Notebook Untitled.ipynb is not trusted
run
import torch
print(torch.__version__)
Error
1.11.0+cu113
D:\ProgramData\Anaconda3\envs\my2022\lib\site-packages\torch\_masked\__init__.py:223: UserWarning: Failed to initialize NumPy: module compiled against API version 0xf but this version of numpy is 0xe (Triggered internally at ..\torch\csrc\utils\tensor_numpy.cpp:68.)
example_input = torch.tensor([[-3, -2, -1], [0, 1, 2]])
How to fix it?
| The problem cause by
Use latest version of PyTorch (too new)
Use latest version of conda (No support NumPy what PyTorch 1.11.0 need), then run Python from conda's virtual environment.
Solution:
Download Python 3.10.4 at https://www.python.org/
Install PyTorch like the command in the question, instlal Jupyter notebook.
No use conda, Anaconda Navigator.
Everything will no problem.
| https://stackoverflow.com/questions/71986643/ |
How to get python packages installed for 32 bit before but works on 64bit as well in Visual Code? E.g. Pytorch | I use
(1) Windows 11,
(2) Python 3.7.8 for 64bit ;
Python 3.8.3 for 32bit
(3) Visual Studio Code.
I noticed that all my python packages are installed on 32Bit, is there any way to get my packages works on 64bit as well? Because I wish to use Pytorch, however, it only works on 64bit
I tried to install packages again, but it installed for my 32 bit? So it cannot install again?
I checked my system path but I have no idea how to do with path for my packages?
I also installed PyTorch in Visual code, but it does not appear installed in my python environment...Why?
I tried to install PyTorch by pip and it gives me error as below:
Updates: ------------------------------------------------
I tried: Ctrl+Shift+P, select that 64bit python
Then, in the terminal I tried to install packages, it still shows that my package is already installed...
| You have selected Python3.7.8(64) in the jupyter notebook, while you have installed the python modules in the Python3.8.3(32) environment. So it will prompt No module named 'pandas'.
And looks like torch has no 32bit version, if you want to use it, you need to select Python3.7.8(64).
So, you can activate the terminal first through open a python file and then clicking the python interpreter on the bottom-right of the VSCode or choosing Python: Select Python interpreter in the command palette directly.
Then take the shortcut of Ctrl+Shift+` to create a new terminal with the activated python environment. After this, you can install the modules in the right place.
You can refer to the official docs for more detail.
| https://stackoverflow.com/questions/71990491/ |
Will gpu be still used for training if I don't transfer tensor and model to gpu using to(device)? | I am using google colab, and I need to know if it uses any GPU for training if I don't do model.to('cuda') and data.to('cuda')?
| If you do not use model.to(torch.device('cuda')) and data.to(torch.device('cuda')) your model and all of your tensors will be remaining on default device which is CPU, so they do not understand the existence of GPU. PyTorch uses CPU for its work.
You can see this Link for more information about torch.device.
| https://stackoverflow.com/questions/71991937/ |
In-place operation Error for Simple Addition and Subtraction Operations | When I run the following code with one layer network it works well. However, when I switch to two layer network it generates the Following Error. Can Some help me resolve the issue. The code is cloned from the following GitHub Repo.
https://github.com/amina01/ESMIL
RuntimeError: one of the variables needed for gradient computation has
been modified by an inplace operation: [torch.cuda.FloatTensor [230,
1]], which is output 0 of TBackward, is at version 2; expected version
1 instead. Hint: enable anomaly detection to find the operation that
failed to compute its gradient, with
torch.autograd.set_detect_anomaly(True).
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import roc_auc_score as auc_roc
from sklearn import metrics
import scipy.io
from sklearn.model_selection import StratifiedKFold
class MyDataset(Dataset):
def __init__(self, bags):
self.bags = bags
def __getitem__(self, index):
examples = self.bags[index]
return examples
def __len__(self):
return len(self.bags)
'''
Single Layer Architecture
'''
#class Net(nn.Module):
# def __init__(self,d):
# super(Net, self).__init__()
# self.out = nn.Linear(d,1)
# def forward(self,x):
# x = x.view(x.size(0), -1)
# x = self.out(x)
# return x
'''
One Hidden Layer Architecture
'''
class Net(nn.Module):
def __init__(self,d):
super(Net, self).__init__()
self.hidden1 = nn.Linear(d,d)
self.out = nn.Linear(d,1)
def forward(self,x):
x = x.view(x.size(0), -1)
x = self.hidden1(x)
x = F.tanh(x)
x = self.out(x)
return x
def create_bags_mat(path='data\\elephant_100x100_matlab.mat'):
mat=scipy.io.loadmat(path)
ids=mat['bag_ids'][0]
f=scipy.sparse.csr_matrix.todense(mat['features'])
l=np.array(scipy.sparse.csr_matrix.todense(mat['labels']))[0]
bags=[]
labels=[]
for i in set(ids):
bags.append(np.array(f[ids==i]))
labels.append(l[ids==i][0])
bags=np.array(bags)
labels=np.array(labels)
return bags, labels
aucs=[]
accs=[]
bags, labels=create_bags_mat()
skf = StratifiedKFold(n_splits=10)
for train, test in skf.split(bags, labels):
bags_tr=bags[train]
y_tr=labels[train]
bags_ts=bags[test]
y_ts=labels[test]
pos_bags=bags_tr[y_tr>0]
neg_bags=bags_tr[y_tr<0]
pos=MyDataset(pos_bags)
neg=MyDataset(neg_bags)
loader_pos = DataLoader(pos, batch_size=1)
loader_neg = DataLoader(neg, batch_size=1)
epochs=10
mlp=Net(230)
mlp.cuda()
# torch.set_default_tensor_type('torch.cuda.FloatTensor')
optimizer = optim.Adam(mlp.parameters())
all_losses=[]
for e in range(epochs):
l=0.0
for idx_p, pbag in enumerate(loader_pos):
pbag=pbag.float()
pbag=Variable(pbag).type(torch.cuda.FloatTensor)
p_scores=mlp.forward(pbag[0])
max_p=torch.max(p_scores)
for idx_n, nbag in enumerate(loader_neg):
nbag=nbag.float()
nbag=Variable(nbag).type(torch.cuda.FloatTensor)
n_scores=mlp.forward(nbag[0])
max_n=torch.max(n_scores)
z=np.array([0.0])
loss=torch.max(Variable(torch.from_numpy(z)).type(torch.cuda.FloatTensor), (max_n-max_p+1))
# loss=torch.max(torch.tensor(0.0), (max_n-max_p+1))
l=l+float(loss)
optimizer.zero_grad()
loss.backward(retain_graph=True)
optimizer.step()
all_losses.append(l)
#testing
test=MyDataset(bags_ts)
loader_ts=DataLoader(test, batch_size=1)
predictions=[]
for param in mlp.parameters():
param.requires_grad =False
for idx_ts, tsbag in enumerate(loader_ts):
tsbag=tsbag.float()
tsbag=Variable(tsbag).type(torch.cuda.FloatTensor)
scores=mlp.forward(tsbag[0])
predictions.append(float(torch.max(scores)))
auc=auc_roc(y_ts, predictions)
aucs.append(auc)
print ('AUC=',auc)
f, t, a=metrics.roc_curve(y_ts, predictions)
AN=sum(x<0 for x in y_ts)
AP=sum(x>0 for x in y_ts)
TN=(1.0-f)*AN
TP=t*AP
Acc2=(TP+TN)/len(y_ts)
acc=max(Acc2)
print ('accuracy=',acc )
accs.append(acc)
print ("\n\nmean auc=", np.mean(aucs))
print ("mean acc=", np.mean(accs))
| The Error was arising due to the max_p=torch.max(p_scores) operation in backpropagation. The problem is be resolved by adding with torch.no_grad(): max_p=torch.max(p_scores) under the first loop. Now the overall code looks like this: However, The performance of the model degraded.
pbag=pbag.float()
pbag=Variable(pbag).type(torch.cuda.FloatTensor)
p_scores=mlp.forward(pbag[0])
with torch.no_grad():
max_p=torch.max(p_scores)
| https://stackoverflow.com/questions/71992113/ |
Pytorch bincount with gradient | I am trying to get gradient from sum of some indexes of an array using bincount. However, pytorch does not implement the gradient. This can be implemented by a loop and torch.sum but it is too slow. Is it possible to do this efficiently in pytorch (maybe einsum or index_add)? Of course, we can loop over indexes and add one by one, however that would increase the computational graph size significantly and is very low performance.
import torch
from torch import autograd
import numpy as np
tt = lambda x, grad=True: torch.tensor(x, requires_grad=grad)
inds = tt([1, 5, 7, 1], False).long()
y = tt(np.arange(4) + 0.1).float()
sum_y_section = torch.bincount(inds, y * y, minlength=8)
#sum_y_section = torch.sum(y * y)
grad = autograd.grad(sum_y_section, y, create_graph=True, allow_unused=False)
print("sum_y_section", sum_y_section)
print("grad", grad)
| We can use a new feature in Pytorch V1.11 called scatter_reduce.
bincount = lambda inds, arr: torch.scatter_reduce(arr, 0, inds, reduce="sum")
| https://stackoverflow.com/questions/71993570/ |
How to get a predicted image of YOLOv5 model? | I'm trying to load YOLOv5 model and using it to predict specific image. My problem is I want to show predicted image with bounding box into my application so I need to get it directly from the predict method of PyTorch to show in my application.
model = torch.hub.load('yolov5', 'custom', path=model_name, force_reload=True,
source='local')
pred = model(image)
pred.show() #show image but can't assign to a variable
pred.save() #save image to runs\detect\exp
I want something like:
predict_image = model(image)
cv2.imshow('Predict', predict_image)
Thank you.
| A quick workaround will be to use "imgs" object from "pred" like the following:
predict_image = model(image)
im_rgb = cv2.cvtColor(predict_image.imgs[0], cv2.COLOR_BGR2RGB) # Because of OpenCV reading images as BGR
cv2_imshow(im_rgb)
I wish this will help you, have a good day.
| https://stackoverflow.com/questions/71995836/ |
early stopping in PyTorch | I tried to implement an early stopping function to avoid my neural network model overfit. I'm pretty sure that the logic is fine, but for some reason, it doesn't work.
I want that when the validation loss is greater than the training loss over some epochs, the early stopping function returns True. But it returns False all the time, even though the validation loss becomes a lot greater than the training loss. Could you see where is the problem, please?
early stopping function
def early_stopping(train_loss, validation_loss, min_delta, tolerance):
counter = 0
if (validation_loss - train_loss) > min_delta:
counter +=1
if counter >= tolerance:
return True
calling the function during the training
for i in range(epochs):
print(f"Epoch {i+1}")
epoch_train_loss, pred = train_one_epoch(model, train_dataloader, loss_func, optimiser, device)
train_loss.append(epoch_train_loss)
# validation
with torch.no_grad():
epoch_validate_loss = validate_one_epoch(model, validate_dataloader, loss_func, device)
validation_loss.append(epoch_validate_loss)
# early stopping
if early_stopping(epoch_train_loss, epoch_validate_loss, min_delta=10, tolerance = 20):
print("We are at epoch:", i)
break
EDIT:
The train and validation loss:
EDIT2:
def train_validate (model, train_dataloader, validate_dataloader, loss_func, optimiser, device, epochs):
preds = []
train_loss = []
validation_loss = []
min_delta = 5
for e in range(epochs):
print(f"Epoch {e+1}")
epoch_train_loss, pred = train_one_epoch(model, train_dataloader, loss_func, optimiser, device)
train_loss.append(epoch_train_loss)
# validation
with torch.no_grad():
epoch_validate_loss = validate_one_epoch(model, validate_dataloader, loss_func, device)
validation_loss.append(epoch_validate_loss)
# early stopping
early_stopping = EarlyStopping(tolerance=2, min_delta=5)
early_stopping(epoch_train_loss, epoch_validate_loss)
if early_stopping.early_stop:
print("We are at epoch:", e)
break
return train_loss, validation_loss
| The problem with your implementation is that whenever you call early_stopping() the counter is re-initialized with 0.
Here is working solution using an oo-oriented approch with __call__() and __init__() instead:
class EarlyStopping():
def __init__(self, tolerance=5, min_delta=0):
self.tolerance = tolerance
self.min_delta = min_delta
self.counter = 0
self.early_stop = False
def __call__(self, train_loss, validation_loss):
if (validation_loss - train_loss) > self.min_delta:
self.counter +=1
if self.counter >= self.tolerance:
self.early_stop = True
Call it like that:
early_stopping = EarlyStopping(tolerance=5, min_delta=10)
for i in range(epochs):
print(f"Epoch {i+1}")
epoch_train_loss, pred = train_one_epoch(model, train_dataloader, loss_func, optimiser, device)
train_loss.append(epoch_train_loss)
# validation
with torch.no_grad():
epoch_validate_loss = validate_one_epoch(model, validate_dataloader, loss_func, device)
validation_loss.append(epoch_validate_loss)
# early stopping
early_stopping(epoch_train_loss, epoch_validate_loss)
if early_stopping.early_stop:
print("We are at epoch:", i)
break
Example:
early_stopping = EarlyStopping(tolerance=2, min_delta=5)
train_loss = [
642.14990234,
601.29278564,
561.98400879,
530.01501465,
497.1098938,
466.92709351,
438.2364502,
413.76028442,
391.5090332,
370.79074097,
]
validate_loss = [
509.13619995,
497.3125,
506.17315674,
497.68960571,
505.69918823,
459.78610229,
480.25592041,
418.08630371,
446.42675781,
372.09902954,
]
for i in range(len(train_loss)):
early_stopping(train_loss[i], validate_loss[i])
print(f"loss: {train_loss[i]} : {validate_loss[i]}")
if early_stopping.early_stop:
print("We are at epoch:", i)
break
Output:
loss: 642.14990234 : 509.13619995
loss: 601.29278564 : 497.3125
loss: 561.98400879 : 506.17315674
loss: 530.01501465 : 497.68960571
loss: 497.1098938 : 505.69918823
loss: 466.92709351 : 459.78610229
loss: 438.2364502 : 480.25592041
We are at epoch: 6
| https://stackoverflow.com/questions/71998978/ |
Output width and heigh with transposed convolution | I have an input of shape torch.Size([4, 256, 1, 5] and I want to upsample it to torch.Size([4, 256, 2, 11]) using torch.nn.ConvTranspose2d(ip_sz, op_sz, kernel_size, stride, padding, output_padding)
I tried different combinations of kernel_size, stride, padding, output_padding however, I am unable to get the desired result.
import torch
import torch.nn as nn
class Dummy(nn.Module):
def __init__(self, ip_sz, op_sz, kernel_size=3, stride=2, padding=1, output_padding=1):
super(Dummy, self).__init__()
self.conv1 = nn.ConvTranspose2d(ip_sz, op_sz, kernel_size=kernel_size,
stride=stride, padding=padding, output_padding=output_padding)
def forward(self, x):
x = self.conv1(x)
print(x.shape)
return x
dummy_model = Dummy(256, 256)
dummy_model(torch.rand([4, 256, 1, 5]))
| Convolution with following parameters should work:
new_dummy = Dummy(256, 256, kernel_size=(2, 3), stride=2, padding=0, output_padding=0)
| https://stackoverflow.com/questions/71999543/ |
How to get unique elements and their firstly appeared indices of a pytorch tensor? | Assume a 2*X(always 2 rows) pytorch tensor:
A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.],
[43., 33., 43., 76., 33., 76., 55., 55., 55.]])
torch.unique(A, dim=1) will return:
tensor([[ 1., 2., 2., 3., 3., 4.],
[43., 33., 43., 33., 76., 55.]])
But I also need the indices of every unique elements where they firstly appear in original input. In this case, indices should be like:
tensor([0, 1, 2, 3, 4, 6])
# Explanation
# A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.],
# [43., 33., 43., 76., 33., 76., 55., 55., 55.]])
# (0) (1) (2) (3) (4) (6)
It's complex for me because the second row of tensor A may not be nicely sorted:
A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.],
[43., 33., 43., 76., 33., 76., 55., 55., 55.]])
^ ^
Is there a simple and efficient method to get the desired indices?
P.S. It may be useful that the first row of the tensor is always in ascending order.
| One possible way to gain such indicies:
unique, idx, counts = torch.unique(A, dim=1, sorted=True, return_inverse=True, return_counts=True)
_, ind_sorted = torch.sort(idx, stable=True)
cum_sum = counts.cumsum(0)
cum_sum = torch.cat((torch.tensor([0]), cum_sum[:-1]))
first_indicies = ind_sorted[cum_sum]
For tensor A in snippet above:
print(first_indicies)
# tensor([0, 1, 2, 4, 3, 6])
Note that unique in this case is equal to:
tensor([[ 1., 2., 2., 3., 3., 4.],
[43., 33., 43., 33., 76., 55.]])
| https://stackoverflow.com/questions/72001505/ |
[FIXED, Roboflow exported CoCo Dataset mistake]YoloV5 cropping image into tiles with overlap (image + bbox) | I have images that are 4928x3280 and I'd like to crop them into tiles of 640x640 with a certain percentage of overlap. The issue is that I have no idea how to deal with the bounding boxes of these files in my dataset as I've found this paper,(http://openaccess.thecvf.com/content_CVPRW_2019/papers/UAVision/Unel_The_Power_of_Tiling_for_Small_Object_Detection_CVPRW_2019_paper.pdf), but not code or so referring to how they did this. There are some examples on the internet that actually have the yoloV5 tiling but without overlap like this(https://github.com/slanj/yolo-tiling) one.
Does anyone know how I could make this myself or if someone has an example of this for me?
| If you want a ready to go library to make possible tiling and inference for yolov5, there is SAHI:
<https://github.com/obss/sahi
You can use it to create tiles with related annotations, to make inferences and evaluate model performance.
| https://stackoverflow.com/questions/72001611/ |
Pytorch tensor to change dimension | I have a RGB image tensor as (3,H,W), but the plt.imshow() can not show RGB image with this shape. I want to change the tensor to (H,W,3). How can I do that, is pytorch function .view() can do that?
| An alternative to using torch.Tensor.permute is to apply torch.Tensor.movedim:
image.movedim(0,-1)
Which is actually more general than image.permute(1,2,0), since it works for any number of dimensions. It has the effect of moving axis=0 to axis=-1 in a sort of insertion operation.
Or equivalently with Numpy, using np.moveaxis:
| https://stackoverflow.com/questions/72010898/ |
PyTorch Dataloader: Dataset complete in RAM | I was wondering if the PyTorch Dataloader can also fetch the complete dataset into RAM so that performance does not suffer if there is enough RAM available
| A concrete example of previous answer:
class mydataset(torch.utils.data.Dataset):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data['x'][index,:], self.data['y'][index,:]
def __len__(self):
return self.data['x'].shape[0]
torch_data_train = mydataset(data_train)
dataload_train = DataLoader(torch_data_train, batch_size=batch_size, shuffle=True, num_workers=2)
| https://stackoverflow.com/questions/72012067/ |
pytorch CUDA version vs. Nvidia CUDA version | Till Apr26th, 2022, CUDA has updated to version 11.6, which can be installed by Nvidia Instruction:
wget https://developer.download.nvidia.com/compute/cuda/11.6.2/local_installers/cuda_11.6.2_510.47.03_linux.run
sudo sh cuda_11.6.2_510.47.03_linux.run
I guess the version of cudatoolkit will also be 11.6
However, there is no version of pytorch that matches CUDA11.6.
On the website of pytorch, the newest CUDA version is 11.3, pytorch version will be 1.11.0(stable)
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
So if I used CUDA11.6 and pytorch1.11.0 with cudatoolkit=11.3, will it perform normally?
and if there is any difference between Nvidia Instruction and conda method below?
conda install cuda -c nvidia
Best regards!
| It should be fine. Otherwise, I saw here that you can build it from the source (I have python=3.8.13) build instructions
pip install torch --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu116
| https://stackoverflow.com/questions/72012334/ |
Using the LSTM layer in encoder in Pytorch | I want to build an autoencoder with LSTM layers. But, at the first step of the encoder, I got an error. Could you please help me with that?
Here is the model which I tried to build:
import numpy
import torch.nn as nn
r_input = torch.nn.LSTM(1, 1, 28)
activation = nn.functional.relu
mu_r = nn.Linear(22, 6)
log_var_r = nn.Linear(22, 6)
y = np.random.rand(1, 1, 28)
def encode_r(y):
y = torch.reshape(y, (-1, 1, 28)) # torch.Size([batch_size, 1, 28])
hidden = torch.flatten(activation(r_input(y)), start_dim = 1)
z_mu = mu_r(hidden)
z_log_var = log_var_r(hidden)
return z_mu, z_log_var
But I got this error in my code:
RuntimeError: input.size(-1) must be equal to input_size. Expected 1, got 28.
| You're not creating the layer in the correct way.
torch.nn.LSTM requires input_size as the first argument, but your tensor has a dimension of 28. It seems that you want the encoder to output a tensor with a dimension of 22. You're also passing the batch as the first dimension, so you need to include batch_first=True as an argument.
r_input = torch.nn.LSTM(28, 22, batch_first=True)
This should work for your specific setup. You should also note that LSTM returns 2 items, the first one is the one you want to use.
hidden = torch.flatten(activation(r_input(y)[0]), start_dim=1)
Please read the declaration on the official wiki for more information.
| https://stackoverflow.com/questions/72015642/ |
RuntimeError: mat1 and mat2 shapes cannot be multiplied (256x16 and 4096x1024) | I am new to Deep Learning and have created a model to classify my images.
Currently, this project raises an error on Google Colab or Kaggle (CPU and GPU) but not on my personal computer (with CPU).
Model:
class CNN(nn.Module):
def __init__(self):
super(CNN,self).__init__()
self.network1 = nn.Sequential(
nn.Conv2d(3, 32, kernel_size = 3, padding = 1),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size = 3, stride = 1, padding = 1),
nn.ReLU(),
nn.MaxPool2d(2,2),
# nn.AdaptiveAvgPool2d((128,128)),
nn.Conv2d(64, 128, kernel_size = 3, stride = 1, padding = 1),
nn.ReLU(),
nn.Conv2d(128 ,128, kernel_size = 3, stride = 1, padding = 1),
nn.ReLU(),
nn.MaxPool2d(2,2),
nn.Conv2d(128, 256, kernel_size = 3, stride = 1, padding = 1),
nn.ReLU(),
nn.Conv2d(256, 256, kernel_size = 3, stride = 1, padding = 1),
nn.ReLU(),
nn.AdaptiveMaxPool2d((4,4))
)
self.network2 = nn.Sequential(
nn.Flatten(),
nn.Linear(256*4*4, 1024),
nn.ReLU(),
nn.Linear(1024, 512),
nn.ReLU(),
nn.Linear(512, n_classes)
)
self.sigm = nn.Sigmoid()
def forward(self,x):
x = self.network1(x)
x = self.network2(x)
return self.sigm(x)
Training:
epoch = 0
model.train()
criterion = nn.BCELoss()
while True:
batch_losses = []
for imgs, labels in data:
imgs, labels = imgs.float().to(device), labels.to(device)
optimizer.zero_grad()
model_result = model(imgs)
loss = criterion(model_result, labels.type(torch.float))
batch_loss_value = loss.item()
loss.backward()
optimizer.step()
batch_losses.append(batch_loss_value)
loss_value = np.mean(batch_losses)
print("epoch:{:2d} iter:{:3d} train: loss:{:.3f}".format(epoch, iteration, loss_value))
if epoch % SAVE_FREQ == 0:
checkpoint_save(model, epoch)
epoch += 1
if EPOCHS < epoch:
break
ERROR:
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_33/872363799.py in <module>
14 optimizer.zero_grad()
15
---> 16 model_result = model(imgs)
17 loss = criterion(model_result, labels.type(torch.float))
18
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
/tmp/ipykernel_33/1050848783.py in forward(self, x)
32 self.sigm = nn.Sigmoid()
33 def forward(self,x):
---> 34 x = self.network(x)
35 return self.sigm(x)
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/container.py in forward(self, input)
139 def forward(self, input):
140 for module in self:
--> 141 input = module(input)
142 return input
143
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/linear.py in forward(self, input)
101
102 def forward(self, input: Tensor) -> Tensor:
--> 103 return F.linear(input, self.weight, self.bias)
104
105 def extra_repr(self) -> str:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (256x16 and 4096x1024)
Input shape is (3, 406, 565)
The summary for this model with this shape is:
----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
Conv2d-1 [-1, 32, 406, 565] 896
ReLU-2 [-1, 32, 406, 565] 0
Conv2d-3 [-1, 64, 406, 565] 18,496
ReLU-4 [-1, 64, 406, 565] 0
MaxPool2d-5 [-1, 64, 203, 282] 0
Conv2d-6 [-1, 128, 203, 282] 73,856
ReLU-7 [-1, 128, 203, 282] 0
Conv2d-8 [-1, 128, 203, 282] 147,584
ReLU-9 [-1, 128, 203, 282] 0
MaxPool2d-10 [-1, 128, 101, 141] 0
Conv2d-11 [-1, 256, 101, 141] 295,168
ReLU-12 [-1, 256, 101, 141] 0
Conv2d-13 [-1, 256, 101, 141] 590,080
ReLU-14 [-1, 256, 101, 141] 0
AdaptiveAvgPool2d-15 [-1, 256, 4, 4] 0
Flatten-16 [-1, 4096] 0
Linear-17 [-1, 1024] 4,195,328
ReLU-18 [-1, 1024] 0
Linear-19 [-1, 512] 524,800
ReLU-20 [-1, 512] 0
Linear-21 [-1, 18] 9,234
Sigmoid-22 [-1, 18] 0
================================================================
Total params: 5,855,442
Trainable params: 5,855,442
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 2.63
Forward/backward pass size (MB): 712.84
Params size (MB): 22.34
Estimated Total Size (MB): 737.80
----------------------------------------------------------------
Solution
In my case, the problem was that I didn't consider the batch size in my image shape and that my dataset had few images with grayscale and few with an alpha channel.
| In my case the problem was that first of all I didn't consider the batch size in my image shape and secondly that my dataset had few images with grayscale and few with an alpha channel.
| https://stackoverflow.com/questions/72021176/ |
vectorize pytorch tensor indexing | I have a batch of images img_batch, size [8,3,32,32], and I want to manipulate each image by setting randomly selected pixels to zero. I can do this using a for loop over each image but I'm not sure how to vectorize it so I'm not processing only one image at a time. This is my code using loops.
batch_size = 8
prct0 = 0.1
noise = torch.tensor([9, 14, 5, 7, 6, 14, 1, 3])
comb_img = []
for ind in range(batch_size):
img = img_batch[ind]
c, h, w = img.shape
prct = 1 - (1 - prct0)**noise[ind].item()
idx = random.sample(range(h*w), int(prct*h*w) )
img_noised = img.clone()
img_noised.view(c,1,-1)[:,0,idx] = 0
comb_img.append(img_noised)
comb_img = torch.stack(comb_img) # output is comb_img [8,3,32,32]
I'm new to pytorch and if you see any other improvements, please share.
| First note: Do you need to use noise? It will be a lot easier if you treat all images the same and don't have a different set number of pixels to set to 0.
However, you can do it this way, but you still need a small for loop (in the list comprehension).
#don't want RGB masking, want the whole pixel
rng = torch.rand(*img_batch[:,0:1].shape)
#create binary mask
mask = torch.stack([rng[i] <= 1-(1-prct0)**noise[i] for i in range(batch_size)])
img_batch_masked = img_batch.clone()
#broadcast mask to 3 RGB channels
img_batch_masked[mask.tile([1,3,1,1])] = 0
You can check that the mask is set correctly by summing mask across the last 3 dims, and seeing if it matches your target percentage:
In [5]: print(mask.sum([1,2,3])/(mask.shape[2] * mask.shape[3]))
tensor([0.6058, 0.7716, 0.4195, 0.5162, 0.4739, 0.7702, 0.1012, 0.2684])
In [6]: print(1-(1-prct0)**noise)
tensor([0.6126, 0.7712, 0.4095, 0.5217, 0.4686, 0.7712, 0.1000, 0.2710])
| https://stackoverflow.com/questions/72022436/ |
Changing the output of a convolutional layer to a tuple of tensors | For processing video frames, I use the squeeze and excitation block for weighting the channels of a convolutional layer.
I want to combine (using torch.stack) the channels(feature maps) of a convolutional layer with the weighted channels (by using the mentioned squeeze and excitation block). But I faced with an error that when using the torch.stack(x, weighted_channels) the argument that is related with the convolutional layer's channelsx, the error says that the TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor.
class conv(nn.Module):
def __init__(self, in_channel, out_channel, out_sigmoid=False):
super(conv, self).__init__()
self.deconv = self._deconv(in_channel=512, out_channel=256, num_conv=3)
self.upsample = Upsample(scale_factor=2, mode='bilinear')
self.SEBlock = SE_Block(c=256)
def _deconv(self, in_channel, out_channel, num_conv=2, kernel_size=3, stride=1, padding=1):
layers=[]
layers.append(BasicConv2d(in_channel, out_channel,kernel_size=kernel_size, stride=stride, padding=padding))
for i in range(1, num_conv):
layers.append(_SepConv2d(out_channel, out_channel,kernel_size=kernel_size, stride=stride, padding=padding))
return nn.Sequential(*layers)
def forward(self, x):
x=self.deconv(x)
x = self.upsample(x)
stack = torch.stack(x, self.SEBlock(x,c=256))
return x
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(out_planes, eps=1e-3, momentum=0.001, affine=True)
self.relu = nn.ReLU()
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
class _SepConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(_SepConv2d, self).__init__()
self.conv_s = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=False, groups=in_planes)
self.bn_s = nn.BatchNorm2d(out_planes)
self.relu_s = nn.ReLU()
self.conv_t = nn.Conv2d(out_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
self.bn_t = nn.BatchNorm2d(out_planes)
self.relu_t = nn.ReLU()
def forward(self, x):
x = self.conv_s(x)
x = self.bn_s(x)
x = self.relu_s(x)
x = self.conv_t(x)
x = self.bn_t(x)
x = self.relu_t(x)
return x
class SE_Block(nn.Module):
"credits: https://github.com/moskomule/senet.pytorch/blob/master/senet/se_module.py#L4"
def __init__(self, c, r=16):
super().__init__()
self.squeeze = nn.AdaptiveAvgPool2d(1)
self.excitation = nn.Sequential(
nn.Linear(c, c // r, bias=False),
nn.ReLU(inplace=True),
nn.Linear(c // r, c, bias=False),
nn.Sigmoid()
)
def forward(self, x):
bs, c, _, _ = x.shape
y = self.squeeze(x).view(bs, c)
y = self.excitation(y).view(bs, c, 1, 1)
return x * y.expand_as(x)
I checked two arguments of torch.stack but the both are of the same size.
| See https://pytorch.org/docs/stable/generated/torch.stack.html.
torch.stack(tensors, dim=0, *, out=None) → Tensor
tensors (sequence of Tensors) – sequence of tensors to concatenate
A sequences of tensors can be a tuple like (tensor1, tensor2, tensor3) or a list [tensor1, tensor2, tensor3]. What you did is input x which is a tensor instead of a sequence of tensors and weighted_channels as the dim parameter into the function.
So as noted in the comments either
torch.stack((x, weighted_channels)) or torch.stack([x, weighted_channels]) should work.
Keep in mind that this is the same for all functions which take an arbitrary number of tensors and does something with them, e.g. torch.cat and all other stack functions like vstack, hstack-
| https://stackoverflow.com/questions/72025879/ |
Vision Transformer attention map by keypoint location - TensorFlow | I have trained a ViT model on TensorFlow for keypoint estimation based on https://github.com/yangsenius/TransPose and I would like to simulate the attention maps of each keypoint like this: https://raw.githubusercontent.com/yangsenius/TransPose/main/attention_map_image_dependency_transposeh_thres_0.00075.jpg
I have found the code on Pytorch but I have no idea about how to simulate it on TensorFlow:
https://github.com/yangsenius/TransPose/blob/dab9007b6f61c9c8dce04d61669a04922bbcd148/visualize.py#L128
| I have solved it by getting the output of the previous layer of the multihead attention layer and passing it by the multihead attention:
atten_maps_hooks = [Model(inputs = model.input, outputs = model.layers[getLayerIndexByName(model, 'encoded_0') - 1].output),
Model(inputs = model.input, outputs = model.layers[getLayerIndexByName(model, 'encoded_1') - 1].output),
Model(inputs = model.input, outputs = model.layers[getLayerIndexByName(model, 'encoded_2') - 1].output),
Model(inputs = model.input, outputs = model.layers[getLayerIndexByName(model, 'encoded_3') - 1].output),
Model(inputs = model.input, outputs = model.layers[getLayerIndexByName(model, 'encoded_4') - 1].output),
Model(inputs = model.input, outputs = model.layers[getLayerIndexByName(model, 'encoded_5') - 1].output)]
for i in range(len(atten_maps_hooks)):
temp = atten_maps_hooks[i].predict(input)
mha, scores = model.get_layer('encoded_' + str(i))(temp, temp, return_attention_scores = True)
enc_atten_maps_hwhw.append(scores.numpy()[0].reshape(shape + shape))
| https://stackoverflow.com/questions/72026063/ |
Is ``torch.autograd.grad" differentiable for its internal variables? | I have a network that incorporates a learnable gradient descent step and is implemented as follows:
Implementation #1:
import torch
from torch import nn
def cal_grad(x, loss):
v = torch.autograd.Variable(x, requires_grad=True)
loss_v = loss(v)
return torch.autograd.grad(loss_v, v, torch.ones_like(loss_v))[0]
class Net_autograd(nn.Module):
def __init__(self):
super(Net_autograd, self).__init__()
self.A = nn.Parameter(torch.rand(100, 50))
self.rho = nn.Parameter(torch.rand(1,))
def forward(self, x_init, y):
grad = cal_grad(x_init, lambda z: 0.5 * (z.mm(self.A) - y).pow(2).sum(dim=[1,])) # calculate gradient implicitly (without giving its formula)
x_hat = x_init - self.rho * grad
return x_hat
net = Net_autograd()
x_init = torch.rand(10, 100, requires_grad=True)
y = torch.rand(10, 50, requires_grad=False)
x_gt = torch.rand(10, 100, requires_grad=False)
x_hat = net(x_init, y)
loss = (x_hat - x_gt).pow(2).mean() # L2 loss
loss.backward()
print('A', net.A.grad)
print('rho', net.rho.grad)
print('x_init', x_init.grad)
It is not that common that I use a learnable matrix self.A to calculate gradient and obtain x_hat, in its forwarding process. I am confused by that why after loss.backward(), the gradient of parameter self.A is None?
And I re-implement the original network by explicitly giving the analytic gradient calculation formula, the parameter self.A can be successfully learned since net.A.grad will not be None:
Implementation #2:
import torch
from torch import nn
class Net_explicit(nn.Module):
def __init__(self):
super(Net_explicit, self).__init__()
self.A = nn.Parameter(torch.rand(100, 50))
self.rho = nn.Parameter(torch.rand(1,))
def forward(self, x_init, y):
grad = (x_init.mm(self.A) - y).mm(self.A.t()) # calculate gradient explicitly
x_hat = x_init - self.rho * grad
return x_hat
net = Net_explicit()
x_init = torch.rand(10, 100, requires_grad=True)
y = torch.rand(10, 50, requires_grad=False)
x_gt = torch.rand(10, 100, requires_grad=False)
x_hat = net(x_init, y)
loss = (x_hat - x_gt).pow(2).mean() # L2 loss
loss.backward()
print('A', net.A.grad)
print('rho', net.rho.grad)
print('x_init', x_init.grad)
I want to ask that:
The second implementation works well as my expectation, but why the first one does not train self.A (with None gradient)? I guess that the torch.autograd.grad itself may not be differentiable for its internal variables, since the external learnable gradient descent step size self.rho and input x_init obtain their own grads.
To implement more complicated pipelines, in which self.A may be even a large network, what can I do to make the implementation #1 works well as #2 (i.e., to make self.A be trainable with autograd mechanisms)?
By the way, I am not sure if the grad of x_init calculated in the forwardings of #1 and #2 are identical or totally equal. Could you please check this for me?
Note: The first dimensions of x_init, y and x_gt, with the size of 10, are the batch dimensions. The version of my torch is 1.7.1, and the torch.autograd.grad does not have the parameter is_grads_batched.
| It seems that I solved this problem by modifying the returning code of function cal_grad to be:
return torch.autograd.grad(loss_v, v, torch.ones_like(loss_v), create_graph=True, retain_graph=True)[0]
| https://stackoverflow.com/questions/72029275/ |
PyTorch: Custom batch sampler exhausts after first epoch | I'm using a DataLoader with a custom batch_sampler to ensure each batch is class balanced. How do I prevent the iterator from exhausting itself on the first epoch?
import torch
class CustomDataset(torch.utils.data.Dataset):
def __init__(self):
self.x = torch.rand(10, 10)
self.y = torch.Tensor([0] * 5 + [1] * 5)
def __len__(self):
len(self.y)
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
def custom_batch_sampler():
batch_idx = [[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]
return iter(batch_idx)
def train(loader):
for epoch in range(10):
for batch, (x, y) in enumerate(loader):
print('epoch:', epoch, 'batch:', batch) # stops after first epoch
if __name__=='__main__':
my_dataset = CustomDataset()
my_loader = torch.utils.data.DataLoader(
dataset=my_dataset,
batch_sampler=custom_batch_sampler()
)
train(my_loader)
Training stops after the first epoch and next(iter(loader)) gives a StopIteration error.
epoch: 0 batch: 0
epoch: 0 batch: 1
epoch: 0 batch: 2
epoch: 0 batch: 3
epoch: 0 batch: 4
| The custom batch sampler needs to be a Sampler or some iterable. In each epoch a new iterator is generated from this iterable. This means you don't actually need to manually make an iterator (which will run out and raise StopIteration after the first epoch), but you can just provide your list, so it should work if you remove the iter():
def custom_batch_sampler():
batch_idx = [[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]
return batch_idx
| https://stackoverflow.com/questions/72034010/ |
Pytorch compute the mean of a 2D tensor at specific rows given a condition | Say I have a tensor
tensor([[0, 1, 2, 2],
[2, 4, 2, 4],
[3, 4, 3, 1],
[4, 4, 4, 3]])
and a tensor of indices
tensor([[1],
[2],
[1],
[3]])
I want to compute the mean where the indices values match. In this case I want the mean of row 1 and 3 so the final output would be
tensor([[1.5, 2.5, 2.5, 1.5],
[2, 4, 2, 4],
[4, 4, 4, 3]])
| You can use torch.scatter_reduce to compute sums. To compute averages we have to use it twice, one for computing sums, and one for counting the summands, such that we can divide by the number of counts. One detail though is that since pytorch uses 0-based indexing we need to subtract 1 from those values:
import torch
a = torch.tensor([[0, 1, 2, 2], [2, 4, 2, 4], [3, 4, 3, 1], [4, 4, 4, 3]])
b = torch.tensor([[1], [2], [1], [3]])
cc = torch.tensor([[1.5, 5.2, 5.2, 1.5], [2, 4, 2, 4], [4, 4, 4, 3]]) # goal
c = torch.scatter_reduce(
a.to(float),
0,
torch.broadcast_to(b, a.shape) - 1,
reduce='mean'
)
print(c)
| https://stackoverflow.com/questions/72036759/ |
Tensor Padding Pytorch | Good evening,
I am having a little trouble with the dimensions of some tensors and I would like to pad them with rows of 0s but I am not managing to do it.
My tensors are of size X by 8 and I want to add rows of 0s (of 8 elements each) until they reach the same size as the tensor with the largest amount of rows in a list.
I've obtained the maximum size with:
max([x.size() for x in dataset])
But I am lost on how to pad the rows.
Thanks a lot for your help.
Pd: Just in case, here is one example of one of my tensors:
tensor([[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.]])
Desired output if the tensor would have 2 more rows:
tensor([[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.]])
| You can utilize the torch.nn.functional.pad function:
x = torch.tensor([[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.]])
Given a maximum number of rows, rows (here rows = 6):
>>> F.pad(x, (0,0,0,rows-len(x)), value=0)
tensor([[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.]])
| https://stackoverflow.com/questions/72043697/ |
Type error on Python: not all arguments converted during string formatting | i am trying to multiply the image for image data set using pytorch random transform.
the code used to work however today it seems to produce error for formatting.
the loop for the data into a larger sample.
or _ in range(80):
for img, label in dataset:
save_image(img, 'img'+str(img_num)+'.png' % '/media/data/abc', normalize=True)
print(img_num)
img_num += 1
why does python code produces a string formatting error? as such
Traceback (most recent call last):
File "/home/user/PycharmProjects/augment/dataaugment.py", line 26, in <module>
save_image(img, 'img'+str(img_num)+'.png' % '/media/data/abc', normalize=True)
TypeError: not all arguments converted during string formatting
is there any solution to resolve or is there any mistake i made?
| When you use the % operator on a string, the first string needs to have formatting placeholders that will be replaced by the values after %. But you have no %s in the first string.
When you're creating pathnames, you should use os.path.join() rather than string operations.
And f-strings are easier to read than concatenation and str() calls when combining variables with strings.
import os
for _ in range(80):
for img, label in dataset:
save_image(img, os.path.join('/media/data/abc', f'img{img_num}.png', normalize=True)
print(img_num)
img_num += 1
| https://stackoverflow.com/questions/72047493/ |
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x20 and 1x1) | I am new to AI and have followed a tutorial to build a linear regression model. When I go to run the code ,I get a RuntimeError which says "mat1 and mat2 shapes cannot be multiplied (1x20 and 1x1)", I think the x_train variable may be the reason causing this problem, but I don't know how to fix it. Here is the code of this program.
import torch
import torch.utils.data
import torch.nn as nn
import matplotlib.pyplot as plt
x_train = torch.arange(1,21,dtype=torch.float32)
true_w = 2.0
true_b = 3
y_true = torch.tensor(true_w*x_train+true_b,dtype=torch.float32)
y_train = y_true-torch.normal(mean=0,std=5,size=(1,20))
net = nn.Sequential(
nn.Linear(1,1)
)
epochs = 1000
learning_rate = 0.01
optimizer = torch.optim.SGD(net.parameters(),lr=learning_rate
for epoch in range(epochs):
optimizer.zero_grad()
# outputs = net(x_train)
# loss = nn.MSELoss(outputs,y_true)
# line below caused RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x20 and 1x1)
outputs = net(x_train)
loss = nn.MSELoss(outputs,y_true)
if epoch %100==0:
print('epoch:{},loss:{}'.format(epoch,loss.item()))
loss.backward()
loss.step()
| Your x_train has shape torch.Size([20]), which your model thinks is a vector with 20 features, but your model is defined as nn.Linear(1,1) so it's expecting an input of size 1.
If you want x_train to be a batch of 20 examples with size 1, you can use unsqueeze() to add an extra dimension:
x_train = torch.arange(1,21,dtype=torch.float32).unsqueeze(1)
print(x_train.shape)
The output will be torch.Size([20, 1]), so your input now has a batch dimension of 20, with each example being size 1.
I think there's a couple of other things to fix in your training loop too:
You should create the MSELoss object first, and then call it during the loop rather than re-creating it every epoch.
loss.step() will throw an error: you should call optimizer.step() instead.
The final code will look like this:
import torch
import torch.utils.data
import torch.nn as nn
import matplotlib.pyplot as plt
x_train = torch.arange(1, 21, dtype=torch.float32).unsqueeze(1)
true_w = 2.0
true_b = 3
y_true = torch.tensor(true_w*x_train+true_b, dtype=torch.float32)
y_train = y_true - torch.normal(mean=0, std=5, size=(1,20))
net = nn.Sequential(nn.Linear(1, 1))
epochs = 1000
learning_rate = 0.01
optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
for epoch in range(epochs):
optimizer.zero_grad()
outputs = net(x_train)
loss = criterion(outputs, y_true)
if epoch %100==0:
print('epoch:{},loss:{}'.format(epoch,loss.item()))
loss.backward()
optimizer.step()
| https://stackoverflow.com/questions/72051609/ |
Colab Session Crashes on importing torch_geometric.data | My colab session always crashes while trying to import torch_geometric.data module. For reference, the code I am writing is as follows:
import torch
def format_pytorch_version(version):
return version.split('+')[0]
TORCH_version = torch.__version__
TORCH = format_pytorch_version(TORCH_version)
def format_cuda_version(version):
return 'cu' + version.replace('.', '')
CUDA_version = torch.version.cuda
CUDA = format_cuda_version(CUDA_version)
!pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-{TORCH}+{CUDA}.html
!pip install torch-sparse -f https://pytorch-geometric.com/whl/torch-{TORCH}+{CUDA}.html
!pip install torch-cluster -f https://pytorch-geometric.com/whl/torch-{TORCH}+{CUDA}.html
!pip install torch-spline-conv -f https://pytorch-geometric.com/whl/torch-{TORCH}+{CUDA}.html
!pip install torch-geometric
!pip install torch_geometric
from torch_geometric.data import Data
When the execution reaches the lats line, the colab session crashes, I have tried switching to GPU and TPU as well, but nothing happens.
The logs shows this:
WARNING:root:kernel fc8fda2d-f1ce-4808-b78f-a18a55132346 restarted
| Got same issue this week.
Downgrading PyTorch to the same version as pytorch_geometric seems to have solved the issue.
!pip install torch==1.10.0+cu111 torchvision==0.11.0+cu111 torchaudio==0.10.0 -f https://download.pytorch.org/whl/torch_stable.html
| https://stackoverflow.com/questions/72054458/ |
Is layer_activation (register_forward_hook) the same as gradient? | I was wondering if the intermediate layer output initialised by register_forward_hook is the same as the gradient of the intermediate output wrt the image?
| You can attach a callback function on a given module with nn.Module.register_full_backward_hook to hook onto the backward pass of that layer. This allows you to access the gradient.
Here is a minimal example, define the hook as you did:
def backward_hook(module, grad_input, grad_output):
print('grad_output:', grad_output)
Initialize your model and attach the hook on its layers
>>> model = nn.Sequential(nn.Linear(10, 5), nn.Linear(5, 2))
Sequential(
(0): Linear(in_features=10, out_features=5, bias=True)
(1): Linear(in_features=5, out_features=2, bias=True)
)
>>> for name, layer in model.named_children():
... print(f'hook onto {name}')
... layer.register_full_backward_hook(backward_hook)
hook onto 0
hook onto 1
Perform an inference:
>>> x = torch.rand(5, 10)
>>> y = model(x).mean()
Perform the backward pass:
>>> y.backward()
grad_output: (tensor([[0.1000, 0.1000],
[0.1000, 0.1000],
[0.1000, 0.1000],
[0.1000, 0.1000],
[0.1000, 0.1000]]),)
grad_output: (tensor([[ 0.0135, 0.0141, -0.0468, -0.0378, -0.0123],
[ 0.0135, 0.0141, -0.0468, -0.0378, -0.0123],
[ 0.0135, 0.0141, -0.0468, -0.0378, -0.0123],
[ 0.0135, 0.0141, -0.0468, -0.0378, -0.0123],
[ 0.0135, 0.0141, -0.0468, -0.0378, -0.0123]]),)
For more examples, you can look at my other answers related to register_full_backward_hook:
Using a non-full backward hook when the forward contains multiple Autograd nodes
How to create a PyTorch hook with conditions?
How to get all the tensors in a graph?
| https://stackoverflow.com/questions/72057797/ |
Argument convention in PyTorch | I am new to PyTorch and while going through the examples, I noticed that sometimes functions have a different convention when accepting arguments. For example transforms.Compose receives a list as its argument:
transform=transforms.Compose([ # Here we pass a list of elements
transforms.ToTensor(),
transforms.Normalize(
(0.4915, 0.4823, 0.4468),
(0.2470, 0.2435, 0.2616)
)
]))
At the same time, other functions receive the arguments individually (i.e. not in a list). For example torch.nn.Sequential:
torch.nn.Sequential( # Here we pass individual elements
torch.nn.Linear(1, 4),
torch.nn.Tanh(),
torch.nn.Linear(4, 1)
)
This has been a common typing mistake for me while learning.
I wonder if we are implying something when:
the arguments are passed as a list
the arguments are passed as individual items
Or is it simply the preference of the contributing author and should be memorized as is?
Update 1: Note that I do not claim that either format is better. I am merely complaining about lack of consistency. Of course (as Ivan stated in his answer) it makes perfect sense to follow one format if there is a good reason for it (e.g. transforms.Normalize). But if there is not, then I would vote for consistency.
| This is not a convention, it is a design decision.
Yes, torch.nn.Sequential (source) receives individual items, whereas torchvision.transforms.Compose (source) receives a single list of items. Those are arbitrary design choices. I believe PyTorch and Torchvision are maintained by different groups of people, which might explain the difference. One could argue it is more coherent to have the inputs passed as a list since it is as a varied length, this is the approach used in more conventional programming languages such as C++ and Java. On the other hand you could argue it is more readable to pass them as a sequence of separate arguments instead, which what languages such as Python.
In this particular case we would have
>>> fn1([element_a, element_b, element_c]) # single list
vs
>>> fn2(element_a, element_b, element_c) # separate args
Which would have an implementation that resembles:
def fn1(elements):
pass
vs using the star argument:
def fn2(*elements):
pass
However it is not always up to design decision, sometimes the implementation is clear to take. For instance, it would be much preferred to go the list approach when the function has other arguments (whether they are positional or keyword arguments). In this case it makes more sense to implement it as fn1 instead of fn2. Here I'm giving second example with keyword arguments. Look a the difference in interface for the first set of arguments in both scenarios:
>>> fn1([elemen_a, element_b], option_1=True, option_2=True) # list
vs
>>> fn2(element_a, element_b, option_1=True, option_2=True) # separate
Which would have a function header which looks something like:
def fn1(elements, option_1=False, option_2=False)
pass
While the other would be using a star argument under the hood:
def fn2(*elements, option_1=False, option_2=False)
pass
If an argument is positioned after the star argument it essentially forces the user to use it as a keyword argument...
Mentioning this you can check out the source code for both Compose and Sequential and you will notice how both only expect a list of elements and no additional arguments afterwards. So in this scenario, it might have been preferred to go with Sequential's approach using the star argument... but this is just personal preference!
| https://stackoverflow.com/questions/72058619/ |
openAI DALL-E ModuleNotFoundError | I installed DALL-E following the instructions on https://github.com/openai/DALL-E
and got :
---> 10 from dall_e import map_pixels, unmap_pixels, load_model
11 from IPython.display import display, display_markdown
12
ModuleNotFoundError: No module named 'dall_e'
| I found that it helped when I changed which Python version I was using.
It fixed my issue when I changed mine from 3.7.- to 3.10.7.
| https://stackoverflow.com/questions/72078830/ |
Changing Learning Rate According to Layer Width in Pytroch | I am trying to train a network where the learning rate for each layer scales with 1/(layer width). Is there a way to do this in pytorch? I tried changing the learning rate in the optimizer and including it in my training loop but that didn't work. I've seen some people talk about this with Adam, but I am using SGD to train. Here are the chunks where I defined my model and training, if thats any help.
class ConvNet2(nn.Module):
def __init__(self):
super(ConvNet2, self).__init__()
self.network = nn.Sequential(
nn.Conv2d(3, 8, 3),
nn.ReLU(),
nn.Conv2d(8,32, 3),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(32, 32, 3),
nn.ReLU(),
nn.Conv2d(32,32, 3),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Flatten(),
nn.Linear(800, 10)
)
def forward(self, x):
return self.network(x)
net2 = ConvNet2().to(device)
def train(network, number_of_epochs):
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(network.parameters(), lr=learning_rate)
for epoch in range(number_of_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, (inputs, labels) in enumerate(trainloader):
# get the inputs
inputs = inputs.to(device)
labels = labels.to(device)
outputs = network(inputs)
loss = criterion(outputs, labels)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = network(inputs)
loss.backward()
optimizer.step()
| In the documentation you can see that you can specify "per-parameter options". Assuming you only want to specify the learning rate for the Conv2d layers (this is easily customizable in the code below) you could do something like this:
import torch
from torch import nn
from torch import optim
from pprint import pprint
class ConvNet2(nn.Module):
def __init__(self):
super(ConvNet2, self).__init__()
self.network = nn.Sequential(
nn.Conv2d(3, 8, 3),
nn.ReLU(),
nn.Conv2d(8,32, 3),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(32, 32, 3),
nn.ReLU(),
nn.Conv2d(32,32, 3),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Flatten(),
nn.Linear(800, 10)
)
def forward(self, x):
return self.network(x)
net2 = ConvNet2()
def getParameters(model):
getWidthConv2D = lambda layer: layer.out_channels
parameters = []
for layer in model.children():
paramdict = {'params': layer.parameters()}
if (isinstance(layer, nn.Conv2d)):
paramdict['lr'] = getWidthConv2D(layer) * 0.1 # Specify learning rate for Conv2D here
parameters.append(paramdict)
return parameters
optimizer = optim.SGD(getParameters(net2.network), lr=0.05)
print(optimizer)
| https://stackoverflow.com/questions/72079140/ |
Custom layer caused the batch dimension mismatch in pytorch. How to fix this problem? | I have tried to train a GCN model.I defined the custom layer I needed. However, It cause some dimension mismatch when I do some batch training.
the codes are as following :
import math
import numpy as np
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from tqdm import tqdm
# =============================================================================
# model define
# =============================================================================
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' \
+ str(self.in_features) + ' -> ' \
+ str(self.out_features) + ')'
class GCN(nn.Module):
def __init__(self, nfeat, nhid, nclass):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.linear = nn.Linear(nclass, 1)
# self.dropout = dropout
def forward(self, x, adj):
x = F.relu(self.gc1(x, adj))
# x = F.dropout(x, self.dropout, training=self.training)
x = F.relu(self.gc2(x, adj))
x = self.linear(x)
return x
def train(dataloader, model, loss_fn, optimizer,adj):
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device)
# Compute prediction error
pred = model(X,adj)
loss = loss_fn(pred, y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test(dataloader, model, loss_fn,adj):
size = len(dataloader.dataset)
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X,adj)
test_loss += loss_fn(pred, y).item()
# correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
# correct /= size
# Accuracy: {(100*correct):>0.1f}%,
print(f"Test Error: \n Avg loss: {test_loss:>8f} \n")
when I run the code :
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")
model = GCN(1,1,1).to(device)
print(model)
# model(X).shape
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(train_dataloader, model, loss_fn, optimizer,Adjacency_matrix)
test(test_dataloader, model, loss_fn,Adjacency_matrix)
print("Done!")
I got the error :
when I looking inside this ,I find the model is working well when I drop the dimension of batch-size. How I need to do to tell the model that this dimension is the batch-size which don't need to compute?
| the error you're seeing is due to you trying to matrix multiple a 3d tensor (your input) by your 2D weights.
To get around this you can simply reshape your data, as we only really care about the last dim when doing matmuls:
def forward(self, input, adj):
b_size = input.size(0)
input = input.view(-1, input.shape[-1])
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
output = output.view(b_size,-1,output.shape[-1])
if self.bias is not None:
return output + self.bias
else:
return output
| https://stackoverflow.com/questions/72090073/ |
PyTorch nn.module won't unbatch operations | I have a nn.Module whose forward function takes in two inputs. Inside the function, I multiply one of the inputs x1 by a set of trainable parameters, and then concatenate them with the other input x2.
class ConcatMe(nn.Module):
def __init__(self, pad_len, emb_size):
super(ConcatMe, self).__init__()
self.W = nn.Parameter(torch.randn(pad_len, emb_size).to(DEVICE), requires_grad=True)
self.emb_size = emb_size
def forward(self, x1: Tensor, x2: Tensor):
cat = self.W * torch.reshape(x2, (1, -1, 1))
return torch.cat((x1, cat), dim=-1)
From my understanding, one is supposed to be able to write operations in PyTorch's nn.Modules like we would for inputs with a batch size of 1. For some reason, this is not the case. I'm getting an error that indicates that PyTorch is still accounting for batch_size.
x1 = torch.randn(100,2,512)
x2 = torch.randint(10, (2,1))
concat = ConcatMe(100, 512)
concat(x1, x2)
-----------------------------------------------------------------------------------
File "/home/my/file/path.py, line 0, in forward
cat = self.W * torch.reshape(x2, (1, -1, 1))
RuntimeError: The size of tensor a (100) must match the size of tensor b (2) at non-singleton dimension 1
I made a for loop to patch the issue as shown below:
class ConcatMe(nn.Module):
def __init__(self, pad_len, emb_size):
super(ConcatMe, self).__init__()
self.W = nn.Parameter(torch.randn(pad_len, emb_size).to(DEVICE), requires_grad=True)
self.emb_size = emb_size
def forward(self, x1: Tensor, x2: Tensor):
batch_size = x2.shape[0]
cat = torch.ones(x1.shape).to(DEVICE)
for i in range(batch_size):
cat[:, i, :] = self.W * x2[i]
return torch.cat((x1, cat), dim=-1)
but I feel like there's a more elegant solution. Does it have something to do with the fact that I'm creating parameters inside nn.Module? If so, what solution can I implement that doesn't require a for loop.
|
From my understanding, one is supposed to be able to write operations in PyTorch's nn.Modules like we would for inputs with a batch size of 1.
I'm not sure where you got this assumption, it is definitely not true - on the contrary: you always need to write them in a way that they can handle the general case of an arbitrary batch dimension.
Judging from your second implementation it seems like you're trying to multiply two tensors with incompatible dimensions. So in order to fix that you'd have to define
self.W = torch.nn.Parameter(torch.randn(pad_len, 1, emb_size), requires_grad=True)
To understand things like that better it would help to learn about broadcasting.
| https://stackoverflow.com/questions/72090626/ |
How to compute Cross Entropy Loss for sequences | I have a sequence continuation/prediction task (input: a sequence of class indices, output: a sequence of class indices) and I use Pytorch.
My neural network returns a tensor of shape (batch_size, sequence_length, numb_classes) where the entries are a number proportional to the propability that the class with this index is the next class in the sequence.
My targets in the training data are of shape (batch_size, sequence_length) (just the sequences of the real predictions).
I want to use the CrossEntropyLoss
My question: How do I use the Cross Entropy Loss function? Which input shapes are required?
Thank you!
| The documentation page of nn.CrossEntropyLoss clearly states:
Input: shape (C), (N, C) or (N, C, d_1, d_2, ..., d_K) with K >= 1 in the case of K-dimensional loss.
Target: If containing class indices, shape (), (N) or (N, d_1, d_2, ..., d_K) with K >= 1 in the case of K-dimensional loss where each value should be between [0, C). If containing class probabilities, the input and each value should be between [0, 1].
Just to be crystal clear, "input" refers to the output prediction of your model
while the "target" is the label tensor. In a nutshell, the target must have one less dimension than that of the input. This missing dimension in the target would contain each class logit value. Usually, we say the target is in the dense format, it only contains the class indices corresponding to the true labels.
The example you give corresponds to the use case of:
#input = (batch_size, sequence_length, numb_classes)
#target = (batch_size, sequence_length)
Which is the case of #input = (N, C, d_1) and #target = (N, d_1), i.e;, you need to permute the axes, or tranpose two axes from your input tensor such that it gets a shape of (batch_size, numb_classes, sequence_length) which is (N, C, d_1). You can do so with either torch.Tensor.transpose or torch.Tensor.permute:
>>> input.permute(0,2,1)
or
>>> input.transpose(1,2)
| https://stackoverflow.com/questions/72091572/ |
How to pass to Linear data with variable length? | I am trying to do sequence classification by first passing data to RNN and then to Linear, normally I would just reshape the output from [batch_size, sequence_size, hidden_size] to [batch_size, sequence_size*hidden_size] to pass it to Linear, but in this case I have sequence of varying lengths, so the output of RNN might be for example [batch_size, 32, hidden_size] or [batch_size, 29, hidden_size], so I don’t know with what shape to initialize the Linear layer (in place of question marks in the code below). Is it at all possible?
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_classes=4):
super().__init__()
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size*????, num_classes)
def forward(self, x):
#x=[batch_size, sequence_length]
out, h_n = self.rnn(x) #out=[batch_size, sequence_length, hidden_size]
out = torch.reshape(out, (BATCH_SIZE, -1)) #out=[batch_size, sequence_length*hidden_size]
out = self.fc(out) #out=[batch_size, num_classes]
return x
Currently each batch is padded to the longest sequence in the batch, is it better to just pad all the sequences to the same length to get rid of this problem? Is changing shape of input to Linear causing some bad side effects?
| Linear layers are meant to take fixed number of features as inputs. If you really want to pass a variable sized input, you could try some kind of imputation (e.g., create a linear layer suited for maximum length and whenever input size is lesser, pad with mean value of feature). But I don't think that's desirable in this scenario (or most of scenarios for that matter).
Since you want to do sequence classification, why don't you just pass a summary of inputs created by the RNN (output at last time step) instead of the whole output i.e., pass [batch_size, hidden_size] (last output of RNN) as input to linear layer. Then your linear layer will be hidden_size x num_classes
This is how the code would look like:
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_classes=4):
super().__init__()
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
#x=[batch_size, sequence_length]
out, h_n = self.rnn(x) #out=[batch_size, sequence_length, hidden_size]
out = out[:, -1, :] #out=[batch_size, hidden_size]
out = self.fc(out) #out=[batch_size, num_classes]
return x
This would work because RNN can learn to summarise the whole input into the last step. Also, you can try LSTM instead of RNN as it might be able to achieve this summarisation even better (since it can handle long-term dependencies more easily).
| https://stackoverflow.com/questions/72099673/ |
mat1 and mat2 shapes cannot be multiplied (19x1 and 19x1) | I have a handmade dataset and all want to do is set a linear regression model with Pytorch.
These are the codes I wrote:
from torch.autograd import Variable
train_x = np.asarray([1,2,3,4,5,6,7,8,9,10,5,4,6,8,5,2,1,1,6])
train_y = train_x * 2
X = Variable(torch.from_numpy(train_x).type(torch.FloatTensor), requires_grad = False).view(19, 1)
y = Variable(torch.from_numpy(train_y).type(torch.FloatTensor), requires_grad = False)
from torch import nn
lr = nn.Linear(19, 1)
loss = nn.MSELoss()
optimizer = torch.optim.SGD(lr.parameters(), lr = 0.01)
output = lr(X) #error occurs here
I guess this is the simplest Pytorch neural network code in the world but it's still giving this error message:
mat1 and mat2 shapes cannot be multiplied (19x1 and 19x1)
I just did all the things on the book but it's still giving this error. Can you help me?
| If you are using a torch.nn.Linear(a,b) as part of a network, then the input must be of shape (n, a), and the output will be of shape (n, b). Therefore you need to make sure that X has shape (n, 19) in your case, so modifying it with
...).view(1, 19)
would do the trick.
| https://stackoverflow.com/questions/72099844/ |
How to Split a folder with multiple dataset into train and test using PyTorch | I have a folder with 48 ECG signal files. The files include .dat and .atr ECG signal records and annotation. I want to split them to train and test to train the AI model. I will be using PyTorch and I want to know a simple way to do this in Python.I prefer a custom split with certain number of files to be in train and the rest in test.
Eg: Train : ['101', '104','107']
Test : ['102', '105','106']
Thanks
| Here first you need to store the Input and attribute location using
a dictionary in python with Input file name as key and Attribute file name as Value.
Then you can split the key of the dictionary and use that as input.
from glob import glob
MainFolder="<Your Folder Name>"
Data={}
for file in glob(MainFolder+"/*.dat"):
At_file=file[:-3]+"atr"
Data[file]=At_file
# Here Data would have Input and attribute file name as key and value pair
# To split the date:
Key_data=list(Data)
import random
random.shuffle(Key_data)
#Here you specify the split ratio of Training and Testing
split=int(len(Key_data)*(0.8))
Train_in=Key_data[:split]
Test_in=Key_data[split:]
Train_at=[Data[i] for i in Train_in]
Test_at=[Data[i] for i in Test_in]
print(Train_in,Train_at,Test_in,Test_at)
Here Train_in is the Input files and Train_at is its corresponding attribute files
This should solve your problem. Comment if you get any error in implementing the above code.
| https://stackoverflow.com/questions/72110022/ |
classify labels to -1 or 1 | I have a tensor with values between -1 and 1 . How can I get a new tensor such that where were negative values now there will be one and where were positive numbers now there will be 1? (efficiently)
Namely,
tensor1 = [-0.1, 0.5, 0.08]
new_tensor = [-1, 1, 1]
and zero will be -1 or 1
| With numpy it is trivial:
import numpy as np
tensor1 = [-0.1, 0.5, 0.08]
new_tensor = np.sign(tensor1)
new_tensor[new_tensor==0] = 1
| https://stackoverflow.com/questions/72111936/ |
PyTorch mat1 and mat2 shapes cannot be multiplied (4x460800 and 80000x16) | I'm trying to find road lanes using PyTorch. I created dataset and my model. But when I try to train my model, I get mat1 and mat2 shapes cannot be multiplied (4x460800 and 80000x16) error. I've tried other topic's solutions but those solutions didn't help me very much.
My dataset is bunch of road images with their validation images. I have .csv file that contains names of images (such as 'image1.jpg, image2.jpg'). Original size of images and validation images is 1280x720. I convert them 200x200 in my dataset code.
Road image:
Validation image:
Here's my dataset:
import os
import pandas as pd
import random
import torch
import torchvision.transforms.functional as TF
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image
class Dataset(Dataset):
def __init__(self, csv_file, root_dir, val_dir, transform=None):
self.annotations = pd.read_csv(csv_file)
self.root_dir = root_dir
self.val_dir = val_dir
self.transform = transform
def __len__(self):
return len(self.annotations)
def __getitem__(self, index):
img_path = os.path.join(self.root_dir, self.annotations.iloc[index, 0])
image = Image.open(img_path).convert('RGB')
mask_path = os.path.join(self.val_dir, self.annotations.iloc[index, 0])
mask = Image.open(mask_path).convert('RGB')
transform = transforms.Compose([
transforms.Resize((200, 200)),
transforms.ToTensor()
])
if self.transform:
image = self.transform(image)
mask = self.transform(mask)
return image, mask
My model:
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super().__init__()
self.cnn_layers = nn.Sequential(
# Conv2d, 3 inputs, 128 outputs
# 200x200 image size
nn.Conv2d(3, 128, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
# Conv2d, 128 inputs, 64 outputs
# 100x100 image size
nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
# Conv2d, 64 inputs, 32 outputs
# 50x50 image size
nn.Conv2d(64, 32, kernel_size=3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.linear_layers = nn.Sequential(
# Linear, 32*50*50 inputs, 16 outputs
nn.Linear(32 * 50 * 50, 16),
# Linear, 16 inputs, 3 outputs
nn.Linear(16, 3)
)
def forward(self, x):
x = self.cnn_layers(x)
x = x.view(x.size(0), -1)
x = self.linear_layers(x)
return x
How to avoid this error and train my images on these validation images?
| The answer: In your case, NN input has a shape (3, 1280, 720), not (3, 200, 200) as you want. Probably you have forgotten to modify transform argument in RNetDataset. It stays None, so transforms are not applied and the image is not resized. Another possibility is that it happens due to these lines:
transform = transforms.Compose([
transforms.Resize((200, 200)),
transforms.ToTensor()
])
if self.transform:
image = self.transform(image)
mask = self.transform(mask)
You have two variables named transform, but one with self. - maybe you messed them up. Verify it and the problem should go away.
How I came up with it: 460800 is clearly a tensor size after reshaping before linear layers. According to the architecture, tensor processed with self.cnn_layers should have 32 layers, so its height multiplied by width should give 460800 / 32 = 14400. Suppose that its height = H, width = W, so H x W = 14400. Let's understand, what was the original input size in this case? nn.MaxPool2d(kernel_size=2, stride=2) layer divides height and width by 2, and it happens three times. So, the original input size has been 8H x 8W = 64 x 14400 = 936000. Finally, notice that 936000 = 1280 * 720. This can't be a magical coincidence. Case closed!
Another suggestion: even if you apply transforms correctly, your code might not work. Suppose that you have an input of size (4, 3, 200, 200), where 4 is a batch size. Layers in your architecture will process this input as follows:
nn.Conv2d(3, 128, kernel_size=3, stride=1, padding=1) # -> (4, 128, 200, 200)
nn.MaxPool2d(kernel_size=2, stride=2) # -> (4, 128, 100, 100)
nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1) # -> (4, 64, 100, 100)
nn.MaxPool2d(kernel_size=2, stride=2) # -> (4, 64, 50, 50)
nn.Conv2d(64, 32, kernel_size=3, stride=1, padding=1) # -> (4, 32, 50, 50)
nn.MaxPool2d(kernel_size=2, stride=2) # -> (4, 32, 25, 25)
So, your first layer in self.linear_layers should be not nn.Linear(32 * 50 * 50, 16), but nn.Linear(32 * 25 * 25, 16). With this change, everything should be fine.
| https://stackoverflow.com/questions/72113116/ |
Utility of wrapping tensor in Variable with requires_grad=False in legacy PyTorch | I'm using a codebase that was written in 2017/18 and I found the following code:
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
I am aware that wrapping tensors in Variable formerly allowed their gradients to be incorporated into the computation graph Torch builds for previous versions of Torch (now no longer needed) but I'm confused what the utility of wrapping a tensor in torch.autograd.Variable(my_tensor, requires_grad=False) would be.
Could someone explain if this was an idiom and what the analogous modern Torch code would be? My guess would be calling detach on the tensor to stop its gradients being tracked.
For reference, the relevant line from the codebase is line 45 from the data_utils.py script of NVIDIA's Tacotron 2 implementation. Thanks.
| In PyTorch 0.3.1 and earlier, any tensor involved in a computation that needed to be tracked by autograd had to be wrapped in a Variable. Semantically Variable.requires_grad in PyTorch 0.3.1 and earlier is equivalent to Tensor.requires_grad now. Basically, requires_grad=False simply tells autograd that you will never need the gradient w.r.t. that variable/tensor. Mathematical operations are only ever recorded (i.e. a computation graph is constructed) if at least one input variable/tensor has requires_grad=True.
Note that any code using PyTorch newer than 0.3.1 does not actually require the use of Variable, this includes the code in the repository you provided (which explicitly requires PyTorch >= 1.0). In 0.4 the functionality of Variable was merged into the Tensor class. In modern PyTorch, you simply have to set the requires_grad attribute of the tensor to achieve the same behavior. By default, a new user-defined tensor is already constructed with requires_grad=False, so the modern equivalent of the code you posted is usually to just delete the Variable line. If you aren't sure if the tensor already has requires_grad == False then you could explicitly set it.
audio_norm = audio_norm.unsqueeze(0)
audio_norm.requires_grad_(False)
You can read the legacy documentation here for more information.
| https://stackoverflow.com/questions/72113541/ |
Why am I wrong in the input of the tensor? | Here is my class for cnn.
class SimpleCnn(nn.Module):
def __init__(self, n_classes):
super().__init__()
self.layer1 = nn.Sequential( # 224*224
nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.layer2 = nn.Sequential( # 112*112
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1),
nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(128),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.layer3 = nn.Sequential( # 56*56
nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=1),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(256),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.layer3 = nn.Sequential( # 28*28
nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, padding=1),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(512),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.layer4 = nn.Sequential( # 14*14
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(512),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.out1 = nn.Linear(512*7*7, 4096) # 7*7
self.out2 = nn.Linear(4096, n_classes)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = x.view(1, -1)
x = self.out1(x)
logits = self.out2(x)
return logits
And it returns such a mistake.
RuntimeError: Given groups=1, weight of size [512, 256, 3, 3], expected input[64, 128, 56, 56] to have 256 channels, but got 128 channels instead.
I've seen other mistakes of such a type but can't find where I'm wrong here.
Thank you for your answer.
| In your code self.layer3 is first defined but then overwritten (a copy-pasta error I assume?). The error is thrown because in the redefinition of layer3 you assume the input has 256 channels, but the output from self.layer2 only has 128 channels.
| https://stackoverflow.com/questions/72113776/ |
Saving Image in tensor array as jpg or png | I am trying to detect the face using mtcnn. The main aim is to detect face, crop and save the cropped image as jpg or png file type. The code implemented is below.
from facenet_pytorch import MTCNN
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
img = Image.open("example.jpg")
mtcnn = MTCNN(margin=20, keep_all=True, post_process=False)
faces = mtcnn(img)
print(faces.shape)
This gives the shape
torch.Size([1, 3, 160, 160])
How to save this cropped portion as jpg file.
| torch.save(faces, "faces.torch")
that wont be saved as an image, if you want to save it as an image:
img = Image.fromarray(faces.cpu().detach().numpy()[0])
img.save("faces.png")
| https://stackoverflow.com/questions/72116045/ |
How to return extra loss from module forward function in PyTorch? | I made a module, that needs an extra loss term, e.g.
class MyModule:
def forward(self, x):
out = f(x)
extra_loss = loss_f(self.parameters(), x)
return out, extra_loss
I can't figure out how to make this module embeddable, for example, into a Sequential model: any regular module like Linear put after this one will fail because extra_loss causes the input to Linear to be a tuple, which Linear does not support.
So what I am looking for is extracting that extra loss after running the model forward
my_module = MyModule()
model = Sequential(
my_module,
Linear(my_module_outputs, 1)
)
output = model(x)
my_module_loss = ????
loss = mse(label, output) + my_module_loss
Does module composability support this scenario?
| IMHO, hooks here is overreaction. Provided extra_loss is additive, we can use global variable like this:
class MyModule:
extra_loss =0
def forward(self, x):
out = f(x)
MyModule.extra_loss += loss_f(self.parameters(), x)
return out
output = model(x)
loss = mse(label, output) + MyModule.extra_loss
MyModule.extra_loss =0
| https://stackoverflow.com/questions/72122761/ |
TypeError: forward() got an unexpected keyword argument 'baseline value'. How do I correctly load a saved model in Skorch? | I saved my Skorch neural net model using the below code:
net_b = NeuralNetClassifier(
Classifier_b,
max_epochs=50,
optimizer__momentum= 0.9,
lr=0.1,
device=device,
)
#Fit the model on the full data
net_b.fit(merged_X_train, merged_Y_train);
#Test saving
import pickle
with open('MLP.pkl', 'wb') as f:
pickle.dump(net_b, f)
When I try to load this model again and run it against test data, I receive the following error:
TypeError: forward() got an unexpected keyword argument 'baseline value'
This is my code:
#Split the data
X_train, y_train, X_valid, y_valid,X_test, y_test = train_valid_test_split(rescaled_data, target = 'fetal_health',
train_size=0.8, valid_size=0.1, test_size=0.1)
input_dim = f_df_toscale.shape[1]
output_dim = len(np.unique(f_target))
hidden_dim_a = 20
hidden_dim_b = 12
device = 'cpu'
class Classifier_b(nn.Module):
def __init__(self,
input_dim = input_dim,
hidden_dim_a = hidden_dim_b,
output_dim = output_dim):
super(Classifier_b, self).__init__()
#Take the inputs and pass these to a hidden layer
self.hidden = nn.Linear(input_dim,hidden_dim_b)
#Take the hidden layer and pass it through an additional hidden layer
self.hidden_b = nn.Linear(hidden_dim_a,hidden_dim_b)
#Take the hidden layer and pass to a multi nerouon output
self.output = nn.Linear(hidden_dim_b,output_dim)
def forward(self, x):
hidden = F.relu(self.hidden(x))
hidden = F.relu(self.hidden_b(hidden))
output = F.softmax(self.output(hidden))
return output
#load the model
with open('MLP.pkl', 'rb') as f:
model_MLP = pickle.load(f)
#Test the model
y_pred = model_MLP.predict(X_test)
ML = accuracy_score(y_test, y_pred)
print('The accuracy score for the MLP is ', ML)
When I run this model normally in the original notebook everything run fines. But when I try to load my model from a saved state I get the error. Any idea why? I have nothing called 'baseline value'.
Thanks
| The save and load model can be problematic if the code changes. So it is better to use
save_params() and load_params()
In your case
net_b.save_params(f_params='some-file.pkl')
To load the model first initialize (initializing is very important) and then load parameters
new_net.initialize()
new_net.load_params(f_params='some-file.pkl')
| https://stackoverflow.com/questions/72127915/ |
Pytorch nn.CrossEntropyLoss() always returns 0 | I am building a multi-class Vision Transformer Network. When passing my values through my loss function, it always returns zero. My output layer consisits of 37 Dense Layers with a softmax-unit on each on of them. criterion is created with nn.CrossEntropyLoss().The output of criterion is 0.0 for every iteration. I am using the colab notebook. I printed out the output and label for one iteration:
for output, label in zip(iter(ouputs_t), iter(labels_t)):
loss += criterion(
output,
# reshape label from (Batch_Size) to (Batch_Size, 1)
torch.reshape(label, (label.shape[0] , 1 ))
)
output: tensor([[0.1534],
[0.5797],
[0.6554],
[0.4066],
[0.2683],
[0.1773],
[0.7410],
[0.5136],
[0.5695],
[0.3970],
[0.4317],
[0.7216],
[0.8336],
[0.4517],
[0.4004],
[0.5963],
[0.3079],
[0.5956],
[0.3876],
[0.2327],
[0.7919],
[0.2722],
[0.3064],
[0.9779],
[0.8358],
[0.1851],
[0.2869],
[0.3128],
[0.4301],
[0.4740],
[0.6689],
[0.7588]], device='cuda:0', grad_fn=<UnbindBackward0>)
label: tensor([[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[1.],
[1.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[0.],
[1.],
[0.]], device='cuda:0')
My Model:
class vit_large_patch16_224_multiTaskNet(nn.Module):
def __init__(self, output_classes, frozen_feature_layers=False):
super().__init__()
vit_base_patch16_224 = timm.create_model('vit_large_patch16_224',pretrained=True)
self.is_frozen = frozen_feature_layers
# here we get all the modules(layers) before the fc layer at the end
self.features = nn.ModuleList(vit_base_patch16_224.children())[:-1]
self.features = nn.Sequential(*self.features)
if frozen_feature_layers:
self.freeze_feature_layers()
# now lets add our new layers
in_features = vit_base_patch16_224.head.in_features
# it helps with performance. you can play with it
# create more layers, play/experiment with them.
self.fc0 = nn.Linear(in_features, 512)
self.bn_pu = nn.BatchNorm1d(512, eps = 1e-5)
self.output_modules = nn.ModuleList()
for i in range(output_classes):
self.output_modules.append(nn.Linear(512, 1))
# initialize all fc layers to xavier
for m in self.modules():
if isinstance(m, nn.Linear):
torch.nn.init.xavier_normal_(m.weight, gain = 1)
def forward(self, input_imgs):
output = self.features(input_imgs)
final_cs_token = output[:, 0]
output = self.bn_pu(F.relu(self.fc0(final_cs_token)))
output_list= list()
for output_modul in self.output_modules:
output_list.append(torch.sigmoid(output_modul(output)))
# Convert List to Tensor
output_tensor = torch.stack(output_list)
#
output_tensor = torch.swapaxes(output_tensor, 0 , 1)
return output_tensor
def _set_freeze_(self, status):
for n,p in self.features.named_parameters():
p.requires_grad = status
# for m in self.features.children():
# for p in m.parameters():
# p.requires_grad=status
def freeze_feature_layers(self):
self._set_freeze_(False)
def unfreeze_feature_layers(self):
self._set_freeze_(True)
| You are in a multi-class classification scenario, which means you can consider your problem as c-binary class classification done in parallel (where c is the total number of class). Having output_t the logit tensor containing the values outputted by your model's last linear layer and target the ground-truth tensor containing the true classes states for each instance in the batch. You can apply nn.BCEWithLogitsLoss since it works with multi-dimensional tensors out of the box:
With dummy inputs:
>>> output_t = torch.rand(47, 32, 1)
>>> target = torch.randint(0, 2, (47, 32, 1)).float()
Then initializing and calling the loss function:
>>> loss = nn.BCEWithLogitsLoss()
>>> loss(output_t, target)
tensor(0.7246)
| https://stackoverflow.com/questions/72128353/ |
Building 2 layer neural network with Pytorch | I am trying to build a simple 2 layer network, it has 2 inputs and 1 output, and the code is as follows:
num_input = 2
num_output = 1
# Input
x1 = torch.rand(1, 2)
# Weights
W1 = torch.rand(2,3)
W2 = torch.rand(3,1)
# biases
b1 = torch.rand(1,3)
b2 = torch.rand(1,1)
# Activation function
def f(inp):
inp[inp >= 0] = 1
inp[inp < 0] = 0
return inp
# Predict output
out = f(torch.mm(x1, W1) + b1)
y=W2*out +b2
print(y)
# Check solution
assert list(y.size()) == [1, num_output], f"Incorrect output size ({y.size()})"
print("nice!")
from this code I always get incorrect output size, can anyone give me a hint, how can I get the correct output size?
| y=out@W2 +b2
You were doing elementwise multiplication. That was not changing the size of the output as you desired.
Just to be clear python 3.5 and above can use this "@" syntax - which is doing the same thing as torch.mm() - that is matrix multiplication.
Dimensions: (Now)
Now you have (1,2) input multiplied with (2,3) weights and adding (1,3) bias. Shape is (1,3) and then you matrix mutiply with (1,3) and (3,1) output is (1,1) and bias to it making the final output size (1,1).
Dimensions (before)
Side Note:
Also you can use the nn.Linear to do all these operations easily without specifying the weights and biases like that.
| https://stackoverflow.com/questions/72130884/ |
RuntimeError: shape '[128, 3, 5, 4, 5, 4]' is invalid for input of size 185856 | I'm using the following code to extract descriptors from images using a Visual Transformer (vit_b_16) but I get the error: RuntimeError: shape '[128, 3, 5, 4, 5, 4]' is invalid for input of size 185856. Does anyone know what I'm doing wrong and how I can fix it?
def img_to_patch(x, patch_size, flatten_channels=True):
B, C, H, W = x.shape
x = x.reshape(B, C, H//patch_size, patch_size, W//patch_size, patch_size)
x = x.permute(0, 2, 4, 1, 3, 5) # [B, H', W', C, p_H, p_W]
x = x.flatten(1,2) # [B, H'*W', C, p_H, p_W]
if flatten_channels:
x = x.flatten(2,4) # [B, H'*W', C*p_H*p_W]
return x
class AttentionBlock(nn.Module):
def __init__(self, embed_dim, hidden_dim, num_heads, dropout=0.0):
super().__init__()
self.layer_norm_1 = nn.LayerNorm(embed_dim)
self.attn = nn.MultiheadAttention(embed_dim, num_heads)
self.layer_norm_2 = nn.LayerNorm(embed_dim)
self.linear = nn.Sequential(
nn.Linear(embed_dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, embed_dim),
nn.Dropout(dropout)
)
def forward(self, x):
inp_x = self.layer_norm_1(x)
x = x + self.attn(inp_x, inp_x, inp_x)[0]
x = x + self.linear(self.layer_norm_2(x))
return x
class VisionTransformer(nn.Module):
def __init__(self, embed_dim, hidden_dim, num_channels, num_heads, num_layers, num_classes, patch_size, num_patches, dropout=0.0):
super().__init__()
self.patch_size = patch_size
# Layers/Networks
self.input_layer = nn.Linear(num_channels*(patch_size**2), embed_dim)
self.transformer = nn.Sequential(*[AttentionBlock(embed_dim, hidden_dim, num_heads, dropout=dropout) for _ in range(num_layers)])
self.mlp_head = nn.Sequential(
nn.LayerNorm(embed_dim),
nn.Linear(embed_dim, num_classes)
)
self.dropout = nn.Dropout(dropout)
# Parameters/Embeddings
self.cls_token = nn.Parameter(torch.randn(1,1,embed_dim))
self.pos_embedding = nn.Parameter(torch.randn(1,1+num_patches,embed_dim))
def forward(self, x):
# Preprocess input
print(x.shape)
x = img_to_patch(x, self.patch_size)
print(x.shape)
B, T, _ = x.shape
x = self.input_layer(x)
# Add CLS token and positional encoding
cls_token = self.cls_token.repeat(B, 1, 1)
x = torch.cat([cls_token, x], dim=1)
x = x + self.pos_embedding[:,:T+1]
# Apply Transforrmer
x = self.dropout(x)
x = x.transpose(0, 1)
x = self.transformer(x)
# Perform classification prediction
cls = x[0]
out = self.mlp_head(cls)
return out
class ViT(pl.LightningModule):
def __init__(self, model_kwargs, lr):
super().__init__()
self.save_hyperparameters()
self.model = VisionTransformer(**model_kwargs)
# self.example_input_array = next(iter(train_loader))[0]
def forward(self, x):
return self.model(x)
and I'm initialising the Transformer like this:
if network_variant == 'vb16':
net = ViT(model_kwargs={
'embed_dim': 256,
'hidden_dim': 512,
'num_heads': 8,
'num_layers': 6,
'patch_size': 4,
'num_channels': 3,
'num_patches': 64,
'num_classes': num_classes,
'dropout': 0.2
},
lr=3e-4)
This is my first time using PyTorch and Vision Transformers so I'm really not sure what I'm doing wrong.
| The error is saying that numpy is trying to fill a matrix with dimensions 128 * 35454, which requires 153,600 elements. However, the data before the reshape has 185,856 elements. Most likely you're miscounting some indices. The difference is 32256=12843*21, which provides some hints about which indices you're probably miscounting... The only place you're calling reshape() is the second line of img_to_patch(), so I assume that's where the error comes from. (Including the traceback in your question would help confirm this.)
Check the sizes of the variables leading up to that line and confirm they're what you expect.
Looking at your code, the most likely problem is that you're rounding off when dividing H and W by patch_size. If H and W aren't multiples of patch_size, you'll need something to decide which pixels to drop: np.reshape() won't make that decision on its own.
| https://stackoverflow.com/questions/72131476/ |
Efficiently add numbers to the end of each dimension of a tensor | I have a tensor x of shape (n, 200). I want to make it shape (n, 218), by appending a tensor of 18 numbers to the end of every "row" of the current tensor. n varies based on the batch size, so I want a way to do this for any n.
As of right now, I have a working solution, but I was wondering if there is a built-in way to do this, I did not see anything in the documentation particularly.
My method is:
import torch.nn.functional as F
x = F.pad(input = x, (0, 18, 0, 0)) # pad each tensor in dim 2 with 18 zeroes
for index in range(x.shape[0]):
x[index][-18] = nums_to_add # nums_to_add is a tensor with size (1,18)
This works just fine, but I was wondering if there is any easier way to do this, without first padding the zeroes.
| torch.cat() is what you are looking for. Here is a snippet:
import torch
a = torch.randint(1,10,(3,4))
b = torch.randint(1,10,(3,2))
print(a)
print(b)
a = torch.cat((a,b),axis=1) # axis should be one here
print(a)
Output
tensor([[2, 5, 3, 8],
[3, 9, 5, 3],
[9, 4, 9, 9]])
tensor([[6, 4],
[1, 1],
[8, 3]])
tensor([[2, 5, 3, 8, 6, 4],
[3, 9, 5, 3, 1, 1],
[9, 4, 9, 9, 8, 3]])
Now here is a similar example just used repeat to make it same shape in dim=0 so that we can concatenate it easily. (Trying to follow OP's suggestion exactly)
import torch
a = torch.randint(1,10,(5,200)) # shape(5,200)
b = torch.randint(1,10,(1,18)).repeat((5,1)) # shape(5,18)
a = torch.cat((a,b),axis=1) # axis should be one here
print(a.shape) # (5,218)
The only tricky part of the above solution is the repeat() part (If you can say it complicated ...), which basically repeats this tensor along the specified dimensions. Check here.
| https://stackoverflow.com/questions/72135574/ |
Does pytorch support multiple tensor CAddTable? | I found in official doc that CAddTable should be done as
x = x1 + x2 # instead of CAddTable(x1, x2) in older version
and PyTorch would do the rest of things like autograd
But how about if I have multiple tensors, aka. changing the input above from two tensors to a list of tensors. Could PyTorch still do the similar things?
| Just for a clean display of the code snip in the comment:
x = torch.stack((x1, x2, x3, x4), dim=0)
y = torch.sum(x, dim=0, keepdim=False) # same shape as x1, x2...
| https://stackoverflow.com/questions/72135729/ |
Pytorch with CUDA local installation fails on Ubuntu | I am trying to install PyTorch with CUDA.
I followed the instructions (installation using conda) mentioned in
https://pytorch.org/get-started/locally/
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c
pytorch
The conda install command runs without giving any error:
conda list displays the following:
# Name Version Build Channel
cudatoolkit 11.3.1 h2bc3f7f_2
pytorch 1.11.0 py3.9_cuda11.3_cudnn8.2.0_0 pytorch
pytorch-mutex 1.0 cuda pytorch
torch 1.10.2 pypi_0 pypi
torchaudio 0.11.0 py39_cu113 pytorch
torchvision 0.11.3 pypi_0 pypi
But when I check whether GPU driver and CUDA is enabled and accessible by PyTorch
torch.cuda.is_available()
returns false.
Prior to Pytorch installation, I checked and confirmed the pre-requisites mentioned in
https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#system-requirements
https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#pre-installation-actions
Here are my ubuntu server details:
Environment:
OS/kernel:
Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-154-generic x86_64)
Footnote under the table: Table 1. Native Linux Distribution Support in CUDA 11.6
mentions
For Ubuntu LTS on x86-64, the Server LTS kernel (e.g. 4.15.x for
18.04) is supported in CUDA 11.6.
GCC
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
GLIBC
ldd (Ubuntu GLIBC 2.27-3ubuntu1.5) 2.27
GPU
GeForce GTX 1080 Ti
Kernel headers and development packages
$ uname -r
4.15.0-176-generic
As per my understanding, conda pytorch installation with CUDA will install the CUDA driver too.
I am not sure where did I went wrong.
Thanks in advance.
EDIT:
$ nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2017 NVIDIA Corporation
Built on Fri_Nov__3_21:07:56_CDT_2017
Cuda compilation tools, release 9.1, V9.1.85
nvcc shows CUDA version 9.1
whereas
$ nvidia-smi
Wed May 11 06:44:31 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 410.104 Driver Version: 410.104 CUDA Version: 10.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A |
| 25% 40C P8 11W / 250W | 18MiB / 11177MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
| 1 GeForce GTX 108... Off | 00000000:06:00.0 Off | N/A |
| 25% 40C P8 11W / 250W | 2MiB / 11178MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
| 2 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A |
| 25% 35C P8 11W / 250W | 2MiB / 11178MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 4119 G /usr/lib/xorg/Xorg 9MiB |
| 0 4238 G /usr/bin/gnome-shell 6MiB |
+-----------------------------------------------------------------------------+
nvidia-smi shows CUDA version 10.0
https://varhowto.com/check-cuda-version/
This article mentions that nvcc refers to CUDA-toolkit whereas nvidia-smi refers to NVIDIA driver.
Q1: Does it shows that there are two different CUDA installation at the system wide level?
Nvidia Cudatoolkit vs Conda Cudatoolkit
The CUDA toolkit (version 11.3.1) I am installing in my conda environment is different from the one installed as system wide level (which is shown by the output of nvcc and nvidia-smi).
Q2: As per the above stackoverflow thread answer, they can be separate. Or is it the reason for my failure to install cuda locally?
| I have solved the issue.
Disclaimer: I am a newbie in CUDA.
Following answer is based on a) what I have read in other threads b) my experience based on those discussions.
Core Logic:
CUDA driver's version >= CUDA runtime version
Reference: Different CUDA versions shown by nvcc and NVIDIA-smi
In most cases, if nvidia-smi reports a CUDA version that is
numerically equal to or higher than the one reported by nvcc -V, this
is not a cause for concern. That is a defined compatibility path in
CUDA (newer drivers/driver API support "older" CUDA toolkits/runtime
API).
As I am using conda's cudatoolkit:
Driver API: nvidia-smi
Runtime API: conda's cudatoolkit
For cudatoolkit 11.3.1, I was using nvidia-smi CUDA Version: 10.0
Solution:
Upgrade NVIDIA drivers.
Upgraded the NVIDIA drivers following the instruction at https://linuxconfig.org/how-to-install-the-nvidia-drivers-on-ubuntu-18-04-bionic-beaver-linux
Post upgradation, here's the output of nvidia-smi:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 470.103.01 Driver Version: 470.103.01 CUDA Version: 11.4 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce ... Off | 00000000:05:00.0 Off | N/A |
| 27% 46C P8 12W / 250W | 19MiB / 11177MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
| 1 NVIDIA GeForce ... Off | 00000000:06:00.0 Off | N/A |
| 25% 44C P8 11W / 250W | 2MiB / 11178MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
| 2 NVIDIA GeForce ... Off | 00000000:09:00.0 Off | N/A |
| 25% 39C P8 11W / 250W | 2MiB / 11178MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| 0 N/A N/A 3636 G /usr/lib/xorg/Xorg 9MiB |
| 0 N/A N/A 4263 G /usr/bin/gnome-shell 6MiB |
+-----------------------------------------------------------------------------+
Now driver version(11.4) >= runtime version (11.3.1)
PyTorch is now able to use CUDA with GPU:
In [1]: import torch
In [2]: torch.cuda.is_available()
Out[2]: True
| https://stackoverflow.com/questions/72139806/ |
Define flatten layer in neural network using pytorch | I'm trying to define a flatten layer before initiating fully connected layer. As my input is a tensor with shape (512, 2, 2), so I want to flatten this tensor before FC layers.
I used to get this error:
empty(): argument 'size' must be tuple of ints, but found element of type Flatten at pos 2
import torch.nn as nn
class Network(nn.Module):
def __init__(self):
super(Network,self).__init__()
self.flatten=nn.Flatten()
self.fc1=nn.Linear(self.flatten,512)
self.fc2=nn.Linear(512,256)
self.fc3=nn.Linear(256,3)
def forward(self,x):
x=self.flatten(x) # Flatten layer
x=torch.ReLU(self.fc1(x))
x=torch.ReLU(self.fc2(x))
x=torch.softmax(self.fc3(x))
return x
| This line is not correct:
self.fc1 = nn.Linear(self.flatten, 512)
the first argument in_features for nn.Linear should be int not the nn.Module
in your case you defined flatten attribute as a nn.Flatten module:
self.flatten = nn.Flatten()
to fix this issue, you have to pass in_features equals to the number of feature after flattening:
self.fc1 = nn.Linear(n_features_after_flatten, 512)
| https://stackoverflow.com/questions/72143098/ |
Issues with Pytorch and Torchvision on MAC M1 - python / conda | Im trying to run Pytorch and Torchvision on Mac M1. I follow these instructions successfully install pytorch and run it natively on apple - https://betterprogramming.pub/how-to-install-pytorch-on-apple-m1-series-512b3ad9bc6
Issues comes when trying to install Torchvision - I conda install torchvision (version 0.22). But when I try to import it I get the error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/torchvision/__init__.py", line 2, in <module>
from torchvision import datasets
File "/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/torchvision/datasets/__init__.py", line 9, in <module>
from .fakedata import FakeData
File "/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/torchvision/datasets/fakedata.py", line 3, in <module>
from .. import transforms
File "/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/torchvision/transforms/__init__.py", line 1, in <module>
from .transforms import *
File "/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/torchvision/transforms/transforms.py", line 17, in <module>
from . import functional as F
File "/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/torchvision/transforms/functional.py", line 5, in <module>
from PIL import Image, ImageOps, ImageEnhance, PILLOW_VERSION
ImportError: cannot import name 'PILLOW_VERSION' from 'PIL' (/Users/gracecolverd/miniconda3/envs/pytorch_m2/lib/python3.8/site-packages/PIL/__init__.py)
It seems to be trying to pull a deprecated function PILLOW_VERSION, but when I check the PIL init file referenced, there is no mention of the PILLOW_VERSION
"""Pillow (Fork of the Python Imaging Library)
Pillow is the friendly PIL fork by Alex Clark and Contributors.
https://github.com/python-pillow/Pillow/
Pillow is forked from PIL 1.1.7.
PIL is the Python Imaging Library by Fredrik Lundh and Contributors.
Copyright (c) 1999 by Secret Labs AB.
Use PIL.__version__ for this Pillow version.
;-)
"""
from . import _version
# VERSION was removed in Pillow 6.0.0.
# PILLOW_VERSION was removed in Pillow 9.0.0.
# Use __version__ instead.
__version__ = _version.__version__
del _version
_plugins = [
"BlpImagePlugin",
"BmpImagePlugin",
"BufrStubImagePlugin",
"CurImagePlugin",
"DcxImagePlugin",
"DdsImagePlugin",
"EpsImagePlugin",
"FitsStubImagePlugin",
"FliImagePlugin",
"FpxImagePlugin",
"FtexImagePlugin",
"GbrImagePlugin",
"GifImagePlugin",
"GribStubImagePlugin",
"Hdf5StubImagePlugin",
"IcnsImagePlugin",
"IcoImagePlugin",
"ImImagePlugin",
"ImtImagePlugin",
"IptcImagePlugin",
"JpegImagePlugin",
"Jpeg2KImagePlugin",
"McIdasImagePlugin",
"MicImagePlugin",
"MpegImagePlugin",
"MpoImagePlugin",
"MspImagePlugin",
"PalmImagePlugin",
"PcdImagePlugin",
"PcxImagePlugin",
"PdfImagePlugin",
"PixarImagePlugin",
"PngImagePlugin",
"PpmImagePlugin",
"PsdImagePlugin",
"SgiImagePlugin",
"SpiderImagePlugin",
"SunImagePlugin",
"TgaImagePlugin",
"TiffImagePlugin",
"WebPImagePlugin",
"WmfImagePlugin",
"XbmImagePlugin",
"XpmImagePlugin",
"XVThumbImagePlugin",
]
class UnidentifiedImageError(OSError):
"""
Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified.
"""
pass
Ive checked the folder above to see if there is a PILLOW init but havnt found anything. Would love to fix this so I dont have to use colab forever! Thanks
| Solved this - the issues was in the Torchvision functional.py script.
In the error it mentioned which files were trying to pull this function
. I searched in /Users/gracecol/miniconda3/envs/tv/lib/python3.10/site-packages/torchvision/transforms
for PILLOW_VERSION and in functional.py I had to replace PILLOW_VERSION with "__version__"
| https://stackoverflow.com/questions/72143980/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.