id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st32868
|
Yes. With map_location=lambda storage, loc: storage, tensors in checkpoint are in CPU memory at first.
However, I guess load_state_dict may cast tensors to the corresponding device of model parameters internally, and the references to the casted tensors are still held by checkpoint. I don’t really trace it down.
|
st32869
|
I’ll have to check this on my end. Embarrassingly, I ended up getting a new gpu and the temporary spike didn’t matter all that much anymore.
|
st32870
|
Hi roytseng, I face the same problem when using 0.3.1, and it still blocking me. I have tried del+cuda.empty_cache() but it doesn’t work in my case. I notice your comment “pytorch 0.3.1 has a bug on this, it’s fix in master”, could you explain more on this? Links to the original issues or commits would be really helpful(i have checked commits about optimizers but do not find it). Thanks in advance!
|
st32871
|
Hi zjoe,
I not really remember if the bug in load_state_dict of optimizer is related to the memory usage increment or not (I guess it’s not). However, it’s sure that this bug has been fixed in pytorch0.4.
|
st32872
|
Hi all,
Have you been able to fix the problem?
I am experiencing the same problem and I am using pytorch 0.5, so it does not seem that the new versions solve the problem. I am using:
if load:
checkpoint = torch.load('./model.ckpt')
startEpoch = checkpoint['StartEpoch']
model.load_state_dict(checkpoint['state_dict'])
del checkpoint
torch.cuda.empty_cache()
but the problem persists. The problem is located in the point
loss.backward
however, the model is the same; and I am not loading anything else than the model and the epoch number. I need to reduce the batch size which is very annoying.
Thanks,
Dani.
|
st32873
|
del checkpoint # dereference seems crucial
Worked for me !
It seems to have saved around +500mb in my case!
I was able to save but not load in pytorch. The checkpoint definitely took up valuable valuable gpu memory.
torch.cuda.empty_cache()
Helped clear around 300mb!
Thank you @roytseng !
|
st32874
|
This thread is really old, but I have to report this can still be an issue with pytorch 1.8.1. I had to lower model’s batch size from 64 to 40 to just be able to resume from a checkpoint before for example. That’s quite a performance hit actually. This method works beautifully and is still relevant, cheers.
Edit: I can also confirm map_location=cpu is also works.
|
st32875
|
I enjoyed using the unreleased torch.vmap() particularly because I find it canonical to author models without thinking about a batch dimension. When modules like batchNorm1d are involved this is impossible right?
Are there any workarounds or plans to address this issue?
|
st32876
|
Let’s say I am predicting a quaternion. How do I implement this piecewise constraint that is conditioned on the scalar/real “w” (for quaternion = [x,y,z,w]).
In Python:
def positive_real_quat(quat):
"""
Flip quaternion to positive real hemisphere so there is a single quaternion describing each rotation
:param quat: [x,y,z,w]
:return:
"""
x, y, z, w =quat
if w >= 0:
return quat
else:
return -quat
But I need the above code to be differentiable as the final function in my neural network. How do I do it?
|
st32877
|
Since you are only multiplying with -1 for a negative w, your function should not break the computation graph.
I’ve changed the input to a tensor and it seems to work fine:
def positive_real_quat(quat):
x, y, z, w = quat.split(1, 1)
if w >= 0:
return quat
else:
return -quat
# Positive
x1 = torch.tensor([[1., 1., 1., 1.]], requires_grad=True)
out1 = positive_real_quat(x1)
out1.mean().backward()
# Check grad
print(x1.grad)
> tensor([[0.2500, 0.2500, 0.2500, 0.2500]])
# Negative
x2 = torch.tensor([[1., 1., 1., -1.]], requires_grad=True)
out2 = positive_real_quat(x2)
out2.mean().backward()
# Check grad
print(x2.grad)
> tensor([[-0.2500, -0.2500, -0.2500, -0.2500]])
|
st32878
|
It seems to be saying that you can always “differentiate” through if else conditionals because you only pass the gradient through the conditional that is selected… kind of like how max is differentiable because you only pass the gradient through the maximum value…
Are there any cases where program logic is not differentiable?
|
st32879
|
Note that torch.max and your approach are a bit different.
While torch.max works on a tensor and will pass the gradient to the max value (as you’ve explained), your approach would create different computation graphs.
Since PyTorch creates the computation graph (which is used to calculate the gradients in the backward pass) dynamically, you can use plain Python conditions, loops, etc. in your code.
|
st32880
|
I guess what I’m looking for is some rigorous argument that gradient descent will minimize a computation graph that contains Python conditions and logic.
|
st32881
|
Hi, I am also very interested in this question. We are trying to implement a “custom” (to our problem) piecewise function using simple if/else logic. Simplified example; we create torch parameters (a,b,c and d) and say that e.g. “if input < 5: value = ainput + b, else: value = cinput + d”.
The backpropagation and optimization seems to only give gradients for some of the values though, although we know that some of the inputs are in the different “ranges” (we have inputs both over and under 5, following the example above).
Will Pytorch accept such a function and the backpropagation + optimization (SGD) algorithm actually work for our function?
|
st32882
|
I have a model given by
class M2(nn.Module):
def __init__( self, dim_x=28*28, dim_y=10):
super(M2, self).__init__()
self.phi_y = nn.Sequential(nn.Linear(dim_x, 500), nn.ReLU(inplace=True),
nn.Linear(500, 500), nn.ReLU(inplace=True),
nn.Linear(500, dim_y))
def forward(self, x):
pass
I want to add trainable parameters to every parameter in self.phi_y. Then, I would like to use the resulting new network, and use it to make prediction and calculate loss in the forward function. During training, I would like to optimize the parameters of self.phi_y as well as the added parameters.
Thanks!
|
st32883
|
Dear PyTorch-Community!
I’m very new to the programming using python and from time to time I feel too dumb to understand it. I got I really basic problem right now, but there’s someone out there to help, for sure
Most of you might know the ‘training a classifier’ algorythm from pytorch (Training a Classifier — PyTorch Tutorials 1.8.1+cu102 documentation 1). I’d like to use it on my own dataset of cow-pictures.
Problem: How do I get my own data instead of the cifar10 dataset in there? I tried a million things but none worked…
Thanks in advance!
|
st32884
|
What have you tried already and where are you stuck at the moment?
Knowing about the failed attempts would be helpful so that we could point you towards potential issues.
In the meantime you could take a look at this tutorial 1, which explains how to write a custom Dataset and use a DataLoader.
|
st32885
|
Dear ptrblck,
Thank you so much for your response!
So far I annotated my pictures using CVAT and also got a csv-file with those annotations.
The tutorial is giving me this code, where I poorly tried to modify the input to be my dataset:
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
batch_size = 4
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
I tried to replace the “tochvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)” part with the root to my dataset and changed my classes to the two relevant for me: “cow”, “no_cow”
|
st32886
|
I wouldn’t try to reuse another Dataset if your custom data doesn’t match the layout, stored file format etc. Take a look at the creation of the FaceLandmarkDataset in the linked tutorial.
The basic idea is to load all paths, store the transformations etc. in the __init__, return the number of samples in the __len__, and load, process, as well as return each sample and target in the __getitem__.
The common approach would be to store the image paths in the __init__ with the corresponding targets and load each sample using the index in the __getitem__.
|
st32887
|
Alright, sounds reasonable
To be sure: If I define the dataset as described in the FaceLandmarkDataset tutorial I should be able to load it in this given code and use it?
|
st32888
|
Yes, you should be able to download the mentioned data and use it with the posted FaceLandmarkDataset. The tutorial is also executable on Google Colab.
For your custom Dataset you would of course need to change the paths and adapt the data structure etc.
|
st32889
|
I created this simplified version of VGG16:
class VGG16COMBO(nn.Module):
def __init__(self, num_classes):
super(VGG16COMBO, self).__init__()
# calculate same padding:
# (w - k + 2*p)/s + 1 = o
# => p = (s(o-1) - w + k)/2
self.block_1 = nn.Sequential(
nn.Conv2d(in_channels=1,
out_channels=64,
kernel_size=(3, 3),
stride=(1, 1),
# (1(32-1)- 32 + 3)/2 = 1
padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(in_channels=64,
out_channels=64,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2),
stride=(2, 2))
)
self.block_2 = nn.Sequential(
nn.Conv2d(in_channels=64,
out_channels=128,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(in_channels=128,
out_channels=128,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2),
stride=(2, 2))
)
self.block_3 = nn.Sequential(
nn.Conv2d(in_channels=128,
out_channels=256,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(in_channels=256,
out_channels=256,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.Conv2d(in_channels=256,
out_channels=256,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(256),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2),
stride=(2, 2))
)
self.block_4 = nn.Sequential(
nn.Conv2d(in_channels=256,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
nn.Conv2d(in_channels=512,
out_channels=512,
kernel_size=(3, 3),
stride=(1, 1),
padding=1),
nn.BatchNorm2d(512),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2),
stride=(2, 2))
)
self.classifier = nn.Sequential(
nn.Linear(2048, 4096),
nn.ReLU(True),
nn.Dropout(p=0.25),
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(p=0.25),
nn.Linear(4096, num_classes),
)
def forward(self, m, c):
m = self.block_1(m)
m = self.block_2(m)
m = self.block_3(m)
m = self.block_4(m)
m = m.view(m.size(0), -1)
m = self.classifier(m)
c = self.block_1(c)
c = self.block_2(c)
c = self.block_3(c)
c = self.block_4(c)
c = c.view(c.size(0), -1)
c = self.classifier(c)
x = torch.cat((m, c), dim=1)
return x
As you can see, in the forward I pass 2 arguments, m and c, that are referred to data of Mnist and Cifar10.
Then I create the model:
modelcombo = VGG16COMBO(1).cuda()
print(modelcombo)
# Define an optimizier
import torch.optim as optim
optimizer = optim.SGD(modelcombo.parameters(), lr = 0.01)
# Define a loss
criterion = nn.BCEWithLogitsLoss()
The problem is in the training function:
def train(net, loaders, optimizer, criterion, epochs=20, dev=dev, save_param = False, model_name="valerio"):
try:
net = net.to(dev)
#print(net)
# Initialize history
history_loss = {"train": [], "val": [], "test": []}
history_accuracy = {"train": [], "val": [], "test": []}
# Store the best val accuracy
best_val_accuracy = 0
# Process each epoch
for epoch in range(epochs):
# Initialize epoch variables
sum_loss = {"train": 0, "val": 0, "test": 0}
sum_accuracy = {"train": 0, "val": 0, "test": 0}
# Process each split
for split in ["train", "val", "test"]:
if split == "train":
net.train()
else:
net.eval()
# Process each batch
for (input, labels) in loaders[split]:
# Move to CUDA
input = input.to(dev)
labels = labels.to(dev)
# Reset gradients
optimizer.zero_grad()
# Compute output
pred = net(input)
#pred = pred.squeeze(dim=1) # Output shape is [Batch size, 1], but we want [Batch size]
labels = labels.unsqueeze(1)
labels = labels.float()
loss = criterion(pred, labels)
# Update loss
sum_loss[split] += loss.item()
# Check parameter update
if split == "train":
# Compute gradients
loss.backward()
# Optimize
optimizer.step()
# Compute accuracy
#pred_labels = pred.argmax(1) + 1
pred_labels = (pred >= 0.5).long() # Binarize predictions to 0 and 1
batch_accuracy = (pred_labels == labels).sum().item()/input.size(0)
# Update accuracy
sum_accuracy[split] += batch_accuracy
# Compute epoch loss/accuracy
epoch_loss = {split: sum_loss[split]/len(loaders[split]) for split in ["train", "val", "test"]}
epoch_accuracy = {split: sum_accuracy[split]/len(loaders[split]) for split in ["train", "val", "test"]}
# Store params at the best validation accuracy
if save_param and epoch_accuracy["val"] > best_val_accuracy:
#torch.save(net.state_dict(), f"{net.__class__.__name__}_best_val.pth")
torch.save(net.state_dict(), f"{model_name}_best_val.pth")
best_val_accuracy = epoch_accuracy["val"]
# Update history
for split in ["train", "val", "test"]:
history_loss[split].append(epoch_loss[split])
history_accuracy[split].append(epoch_accuracy[split])
# Print info
print(f"Epoch {epoch+1}:",
f"TrL={epoch_loss['train']:.4f},",
f"TrA={epoch_accuracy['train']:.4f},",
f"VL={epoch_loss['val']:.4f},",
f"VA={epoch_accuracy['val']:.4f},",
f"TeL={epoch_loss['test']:.4f},",
f"TeA={epoch_accuracy['test']:.4f},")
except KeyboardInterrupt:
print("Interrupted")
finally:
# Plot loss
plt.title("Loss")
for split in ["train", "val", "test"]:
plt.plot(history_loss[split], label=split)
plt.legend()
plt.show()
# Plot accuracy
plt.title("Accuracy")
for split in ["train", "val", "test"]:
plt.plot(history_accuracy[split], label=split)
plt.legend()
plt.show()
Because when I call the function the problem is that I am passing only one dataloader, the one of mnist, and not for cifar.
# Train model
train(modelcombo, loaders, optimizer, criterion, epochs=10, dev=dev) #loaders is only for mnist
#I want to pass also loaders_cifar
TypeError: forward() missing 1 required positional argument: 'c'
Now, I have to modify the training function, the forward function, or I have to combine the loaders in such a way?
|
st32890
|
Hi,
your def forward(self, m, c): expects an argument ‘c’ (as the error tells as well).
I don’t know, what your loaders contains, but based on your model, you do also have to pass the CIFAR data.
Regards,
Unity05
|
st32891
|
These are the loaders of MNIST
# Define loaders
from torch.utils.data import DataLoader
train_loader = DataLoader(train_set, batch_size=64, num_workers=2, shuffle=True, drop_last=True)
val_loader = DataLoader(val_set, batch_size=64, num_workers=2, shuffle=False, drop_last=False)
test_loader = DataLoader(test_set, batch_size=64, num_workers=2, shuffle=False, drop_last=False)
# Define dictionary of loaders
loaders = {"train": train_loader,
"val": val_loader,
"test": test_loader}
And these of CIFAR
# Define loaders
from torch.utils.data import DataLoader
train_loader_cifar = DataLoader(train_set_cifar, batch_size=64, num_workers=2, shuffle=True, drop_last=True)
val_loader_cifar = DataLoader(val_set_cifar, batch_size=64, num_workers=2, shuffle=False, drop_last=False)
test_loader_cifar = DataLoader(test_set_cifar, batch_size=64, num_workers=2, shuffle=False, drop_last=False)
# Define dictionary of loaders
loaders_cifar = {"train": train_loader_cifar,
"val": val_loader_cifar,
"test": test_loader_cifar}
|
st32892
|
Then instead of for (input, labels) in loaders[split]: you might want to do something like for (input_m, labels_m), (input_c, labels_c) in zip(loaders[split], loaders_cifar[split]): and therefore also instead of pred = net(input) something like pred = net(input_m, input_c).
Regards,
Unity05
|
st32893
|
I did in this way:
def train(net, loaders, optimizer, criterion, epochs=10, dev=dev, save_param = False, model_name="valerio"):
loaders_mnist, loaders_cifar = loaders
try:
net = net.to(dev)
#print(net)
# Initialize history
history_loss = {"train": [], "val": [], "test": []}
history_accuracy = {"train": [], "val": [], "test": []}
# Store the best val accuracy
best_val_accuracy = 0
# Process each epoch
for epoch in range(epochs):
# Initialize epoch variables
sum_loss = {"train": 0, "val": 0, "test": 0}
sum_accuracy = {"train": 0, "val": 0, "test": 0}
# Process each split
for split in ["train", "val", "test"]:
if split == "train":
net.train()
else:
net.eval()
# Process each batch
for ((input_mnist, labels_mnist), (input_cifar, labels_cifar)) in zip(loaders_mnist[split], loaders_cifar[split]):
#for (input, labels) in loaders[split]:
# Move to CUDA
input_mnist = input_mnist.to(dev)
labels_mnist = labels_mnist.to(dev)
input_cifar = input_cifar.to(dev)
labels_cifar = labels_cifar.to(dev)
# Reset gradients
optimizer.zero_grad()
# Compute output
pred = net(input_mnist, input_cifar)
#pred = pred.squeeze(dim=1) # Output shape is [Batch size, 1], but we want [Batch size]
labels = labels.unsqueeze(1)
labels = labels.float()
loss = criterion(pred, labels)
# Update loss
sum_loss[split] += loss.item()
# Check parameter update
if split == "train":
# Compute gradients
loss.backward()
# Optimize
optimizer.step()
# Compute accuracy
#pred_labels = pred.argmax(1) + 1
pred_labels = (pred >= 0.5).long() # Binarize predictions to 0 and 1
batch_accuracy = (pred_labels == labels).sum().item()/input.size(0)
# Update accuracy
sum_accuracy[split] += batch_accuracy
# Compute epoch loss/accuracy
epoch_loss = {split: sum_loss[split]/len(loaders[split]) for split in ["train", "val", "test"]}
epoch_accuracy = {split: sum_accuracy[split]/len(loaders[split]) for split in ["train", "val", "test"]}
# Store params at the best validation accuracy
if save_param and epoch_accuracy["val"] > best_val_accuracy:
#torch.save(net.state_dict(), f"{net.__class__.__name__}_best_val.pth")
torch.save(net.state_dict(), f"{model_name}_best_val.pth")
best_val_accuracy = epoch_accuracy["val"]
# Update history
for split in ["train", "val", "test"]:
history_loss[split].append(epoch_loss[split])
history_accuracy[split].append(epoch_accuracy[split])
# Print info
print(f"Epoch {epoch+1}:",
f"TrL={epoch_loss['train']:.4f},",
f"TrA={epoch_accuracy['train']:.4f},",
f"VL={epoch_loss['val']:.4f},",
f"VA={epoch_accuracy['val']:.4f},",
f"TeL={epoch_loss['test']:.4f},",
f"TeA={epoch_accuracy['test']:.4f},")
except KeyboardInterrupt:
print("Interrupted")
finally:
# Plot loss
plt.title("Loss")
for split in ["train", "val", "test"]:
plt.plot(history_loss[split], label=split)
plt.legend()
plt.show()
# Plot accuracy
plt.title("Accuracy")
for split in ["train", "val", "test"]:
plt.plot(history_accuracy[split], label=split)
plt.legend()
plt.show()
# Train model
train(modelcombo, (loaders, loaders_cifar), optimizer, criterion, epochs=3, dev=dev)
I have this error:
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-120-991dbce10c53> in <module>()
1 # Train model
----> 2 train(modelcombo, (loaders, loaders_cifar), optimizer, criterion, epochs=3, dev=dev)
<ipython-input-119-8f7766b35a35> in train(net, loaders, optimizer, criterion, epochs, dev, save_param, model_name)
34 pred = net(input_mnist, input_cifar)
35 #pred = pred.squeeze(dim=1) # Output shape is [Batch size, 1], but we want [Batch size]
---> 36 labels = labels.unsqueeze(1)
37 labels = labels.float()
38 loss = criterion(pred, labels)
UnboundLocalError: local variable 'labels' referenced before assignment
Obviously I tried to fix, with the above code, but I failed:
def train2(net, loaders, optimizer, criterion, epochs=10, dev=dev, save_param = False, model_name="valerio"):
loaders_mnist, loaders_cifar = loaders
try:
net = net.to(dev)
#print(net)
# Initialize history
history_loss = {"train": [], "val": [], "test": []}
history_accuracy = {"train": [], "val": [], "test": []}
# Store the best val accuracy
best_val_accuracy = 0
# Process each epoch
for epoch in range(epochs):
# Initialize epoch variables
sum_loss = {"train": 0, "val": 0, "test": 0}
sum_accuracy = {"train": 0, "val": 0, "test": 0}
# Process each split
for split in ["train", "val", "test"]:
if split == "train":
net.train()
else:
net.eval()
# Process each batch
for ((input_mnist, labels_mnist), (input_cifar, labels_cifar)) in zip(loaders_mnist[split], loaders_cifar[split]):
#for (input, labels) in loaders[split]:
# Move to CUDA
input_mnist = input_mnist.to(dev)
labels_mnist = labels_mnist.to(dev)
input_cifar = input_cifar.to(dev)
labels_cifar = labels_cifar.to(dev)
# Reset gradients
optimizer.zero_grad()
# Compute output
pred = net(input_mnist, input_cifar)
#pred = pred.squeeze(dim=1) # Output shape is [Batch size, 1], but we want [Batch size]
labels_mnist = labels_mnist.unsqueeze(1)
labels_mnist = labels_mnist.float()
labels_cifar = labels_cifar.unsqueeze(1)
labels_cifar = labels_cifar.float()
labels = labels_mnist, labels_cifar
loss = criterion(pred, labels)
# Update loss
sum_loss[split] += loss.item()
# Check parameter update
if split == "train":
# Compute gradients
loss.backward()
# Optimize
optimizer.step()
# Compute accuracy
#pred_labels = pred.argmax(1) + 1
pred_labels = (pred >= 0.5).long() # Binarize predictions to 0 and 1
batch_accuracy = (pred_labels == labels).sum().item()/input.size(0)
# Update accuracy
sum_accuracy[split] += batch_accuracy
# Compute epoch loss/accuracy
epoch_loss = {split: sum_loss[split]/len(loaders[split]) for split in ["train", "val", "test"]}
epoch_accuracy = {split: sum_accuracy[split]/len(loaders[split]) for split in ["train", "val", "test"]}
# Store params at the best validation accuracy
if save_param and epoch_accuracy["val"] > best_val_accuracy:
#torch.save(net.state_dict(), f"{net.__class__.__name__}_best_val.pth")
torch.save(net.state_dict(), f"{model_name}_best_val.pth")
best_val_accuracy = epoch_accuracy["val"]
# Update history
for split in ["train", "val", "test"]:
history_loss[split].append(epoch_loss[split])
history_accuracy[split].append(epoch_accuracy[split])
# Print info
print(f"Epoch {epoch+1}:",
f"TrL={epoch_loss['train']:.4f},",
f"TrA={epoch_accuracy['train']:.4f},",
f"VL={epoch_loss['val']:.4f},",
f"VA={epoch_accuracy['val']:.4f},",
f"TeL={epoch_loss['test']:.4f},",
f"TeA={epoch_accuracy['test']:.4f},")
except KeyboardInterrupt:
print("Interrupted")
finally:
# Plot loss
plt.title("Loss")
for split in ["train", "val", "test"]:
plt.plot(history_loss[split], label=split)
plt.legend()
plt.show()
# Plot accuracy
plt.title("Accuracy")
for split in ["train", "val", "test"]:
plt.plot(history_accuracy[split], label=split)
plt.legend()
plt.show()
Error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-113-96aba51d9c54> in <module>()
1 # Train model
----> 2 train2(modelcombo, (loaders, loaders_cifar), optimizer, criterion, epochs=3, dev=dev)
3 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight)
2824 reduction_enum = _Reduction.get_enum(reduction)
2825
-> 2826 if not (target.size() == input.size()):
2827 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
2828
AttributeError: 'tuple' object has no attribute 'size'
|
st32894
|
Well,
AttributeError: 'tuple' object has no attribute 'size' this is because BCE does not take tuple as arguments, but you’re passing labels = labels_mnist, labels_cifar. You might want to treat them as different pairs (MNIST and CIFAR) in the same batch (reduction would also take the job to apply the reduction. That would of course mean you had to do the necessary changes on the model output.
However, I’ve just seen that your concatenating the MNIST and CIFAR results at dimension 1 from the classifier. I’m not sure if that’s intentional. If not, then you could return them as a tuple, what would furthermore help you in the loss part.
However, may I ask why you want to process two different datasets in one forward ‘in parallel’?.
Regards,
Unity05
|
st32895
|
However, I’ve just seen that your concatenating the MNIST and CIFAR results at dimension 1 from the classifier. I’m not sure if that’s intentional.
Yes, it is intentional. I want a multi input network. I am doing an experiment of meta-transfer learning, in which I sum weights of 2 networks basically. And now i am trying to have a multi input network trained on 2 datasets.
You are right, I am defining a new loss function for this experiment, I will not use BCEWithLogitLoss
So, do you suggest to modify something in the net, or I can work on my custom loss function?
My CustomLoss will be this: CrossEntropy(MNIST) + CrossEntropy(CIFAR10) + CrossEntropy([MNIST+CIFAR10]-MNIST) (this last term of loss should guarantee that the network on MNIST have similar performances before and after the operation of sum.
Tomorrow I will try to implement something like this, and probably I will ask for help here
Edit:
@Unity05 do you think a solution like this could be good?
class CustomLossFunction(nn.Module):
def __init__(self):
super(CustomLossFunction, self).__init__()
def forward(self, pred_mnist, pred_cifar, target_mnist, target_cifar):
loss_mnist = nn.BCEWithLogitsLoss(pred_mnist, target_mnist)
loss_cifar = nn.BCEWithLogitsLoss(pred_cifar, target_cifar)
loss_mnist_cifar = nn.BCEWithLogitsLoss(pred_mnist_cifar - pred_mnist, target_mnist_cifar - target_mnist)
loss_sum = loss_mnist + loss_cifar + loss_mnist_cifar
return loss_sum
|
st32896
|
Given a tensor of values in the range [0, 1], multiplying these values with a scalar p and applying a softmax gives scaled probabilities that sum to 1. Increasing p pushes the values to either 0 or 1. See example:
values = torch.tensor([0.00, 0.25, 0.50, 0.75, 1.00])
softmax_values = torch.stack([torch.softmax(p*values, 0) for p in np.arange(0, 20)])
for input, outputs in zip(values, softmax_values.T):
c = plt.gca()._get_lines.get_next_color()
plt.plot([0], [input], 'o', c=c)
plt.plot(outputs, c=c)
plt.xlabel("p")
plt.show()
Dots represent the input values and lines show softmax values of those values given a certain p.
Setting low values of p results in all softmax values converge to 1 / n_values = 1 / 5 = 0.2.
How do I instead create a function that gradually transform the input values to their softmax as p → inf?
That function would look like:
|
st32897
|
Solved by KFrank in post #2
Hi Zimo!
There are lots of possibilities. (You could choose between them by
imposing further conditions on the behavior of your function.)
Here is an illustration of one possible choice:
>>> import torch
>>> torch.__version__
'1.7.1'
>>> _ = torch.manual_seed (2021)
>>> def gradual (values, p)…
|
st32898
|
Hi Zimo!
ZimoNitrome:
How do I instead create a function that gradually transform the input values to their softmax as p → inf?
There are lots of possibilities. (You could choose between them by
imposing further conditions on the behavior of your function.)
Here is an illustration of one possible choice:
>>> import torch
>>> torch.__version__
'1.7.1'
>>> _ = torch.manual_seed (2021)
>>> def gradual (values, p):
... return torch.where (values == values.max(), 1.0 - (1.0 - values)**p, values**p)
...
>>> values = torch.rand (5)
>>> values
tensor([0.1304, 0.5134, 0.7426, 0.7159, 0.5705])
>>> gradual (values, 1)
tensor([0.1304, 0.5134, 0.7426, 0.7159, 0.5705])
>>> gradual (values, 2)
tensor([0.0170, 0.2636, 0.9337, 0.5125, 0.3254])
>>> gradual (values, 3)
tensor([0.0022, 0.1353, 0.9829, 0.3669, 0.1857])
>>> gradual (values, 5)
tensor([3.7761e-05, 3.5664e-02, 9.9887e-01, 1.8803e-01, 6.0419e-02])
>>> gradual (values, 10)
tensor([1.4259e-09, 1.2719e-03, 1.0000e+00, 3.5355e-02, 3.6504e-03])
Best.
K. Frank
|
st32899
|
Thanks for the answer K. Frank.
I will try to tinker with this solution in a few hours.
Do you happen to know if torch.where breaks the gradent tree? I am looking for a differentiable function even if I know that for large values of p, the gradient will be strangled.
|
st32900
|
Hi Zimo!
ZimoNitrome:
Do you happen to know if torch.where breaks the gradent tree?
torch.where() does not break the computation graph – that’s a good
thing about it.
But, furthermore, in this specific case, each individual element of values
only participates in a single the branch of the torch.where() function.
I’m just using it as a more compact way to single out the largest element
in values, rather than indexing with argmax().
Best.
K. Frank
|
st32901
|
Yes it seems to work quite nicely
values = torch.tensor([0.20, 0.40, 0.60, 0.80], requires_grad=True)
def gradual (values, p):
return torch.where (values == values.max(), 1.0 - (1.0 - values)**p, values**p)
softmax_values = torch.stack([gradual(values, p) for p in np.arange(1, 20)])
for input, outputs in zip(values, softmax_values.T):
c = plt.gca()._get_lines.get_next_color()
plt.plot([0], [input], 'o', c=c)
plt.plot(outputs.detach(), c=c)
plt.xlabel("p")
plt.show()
loss = softmax_values.mean()
loss.backward()
values.grad
tensor([0.0206, 0.0365, 0.0822, 0.0206])
Do you know if that is the case generally, that using torch.where(x == max(x), t1, t2) is differentiable while torch.argmax(x) is not? I guess they have different use-cases but this feels like a very nice “trick” to maintain gradient.
|
st32902
|
I want use PyTorch’s dataloader with multiprocessing to return tensors allocated in the GPU. The docs explicitly say this is not recommended and point to the CUDA in multiprocessing documentation:
https://pytorch.org/docs/stable/notes/multiprocessing.html#cuda-in-multiprocessing
From the documentation I gather that this should work properly as long as I wrap my training code in if __main__ == '__name__', use “spawn” as the multiprocessing context, keep persistent_workers = True, and del the tensors after using them on the main training loop, so the workers can release the memory of the copied tensors. Is this correct or are there any other issues I should be aware of regarding this?
|
st32903
|
Hello everyone.
Recently, I have been handling my own point cloud dataset.
I want to use torch-points3d library but I cant find how to make custom dataset.
Does anyone know a solution?
|
st32904
|
Hi everyone, I encountered an strange error today… A RuntimeError: CUDA error: an illegal memory access was encountered pops up at torch.cuda.empty_cache().
Even more peculiarly, this issue comes out at the 39th epoch of a training session… How could that be?
Info:
Traceback (most recent call last):
File "build_model_and_train.py", line 206, in <module>
train_loss, train_acc = train()
File "build_model_and_train.py", line 105, in train
torch.cuda.empty_cache()
File "/public/workspace/z/miniconda3/envs/ST-Torch/lib/python3.7/site-packages/torch/cuda/memory.py", line 35, in empty_cache
torch._C._cuda_emptyCache()
Code snippet:
def train():
model.train()
loss_all=0
correct = 0
for i, data in enumerate(train_loader, 0):
torch.cuda.empty_cache() # This is where the issue lies!
data = data.to(device)
optimizer.zero_grad()
output = model(data.x, data.batch)
torch.cuda.empty_cache() # This is not where the issue lies.
label = data.y.to(device)
loss = loss_func(output, label)
loss.backward()
loss_all += loss.item()
output = output.detach().cpu().numpy().squeeze()
label = label.detach().cpu().numpy().squeeze()
correct += (abs(output-label)<0.5).sum()
optimizer.step()
return loss_all / len(train_dataset), correct / len(train_dataset)
## Start training
# Omitted dataset generation, DataLoader, and initial setup
os.environ["CUDA_VISIBLE_DEVICES"] = '2'
......
device = torch.device('cuda')
edge_index = edge_index.to(device)
model = GCN().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay = l2_reg)
loss_func = torch.nn.BCELoss() # binary cross-entropy
train_loader = DataLoader(train_dataset, batch_size=batch_size, drop_last = True)
val_loader = DataLoader(val_dataset, batch_size=batch_size)
for epoch in range(num_epochs):
gc.collect()
torch.cuda.empty_cache() # Yes I put this everywhere because I am suffering from OOMs...
train_loss, train_acc = train()
|
st32905
|
CUDA operations are executed asynchronously, so the illegal memory access error would most likely happen before you are calling empty_cache(). To isolate it, you could run the script via CUDA_LAUNCH_BLOCKING=1 python script.py args and check the stacktrace, which should point to the failing operation. Also, in case you are using an older PyTorch release, I would recommend to update it to the latest stable or nightly release.
|
st32906
|
Thanks for your reply! I am using the latest stable version actually. Will check the failing operations.
|
st32907
|
Hello friend. I’m training multivariate input data using LSTM network.
You can see my data type below.
I’m training 64 Input size data.
The ‘Evaluation data’ includes Attack data labeled with ‘T’ containing intermediate random bit values.
I trained only normal data(only labeled as ‘R’) and evaluate data which has random bit and labeled as ‘T’ as shown in the data example below.
'''
Evaluation Data ↓Label
0111100000000000000000000010000100000000000000000000000000000000R
0111100000000000000000000010000100000000000000000000000000000000R
1000010011111101001011001000100100000000000000000000000000000000T #<--- Attack
0111100000000000000000001010000100000000000000000000000000000000R
0111100000000000000000000100000100000000000000000000000000000000R
...
0111100000000000000000001000000100000000000000000000000000000000R
0111100000000000000000000011000100000000000000000000000000000000R
0010101100100010100010100011010100000000000000000000000000000000T #<--- Attack
0111100000000000000000000100000100000000000000000000000000000000R
0111100000000000000000001100000100000000000000000000000000000000R
...
0111100100000000000000000011000000000000000000000000000000000000R
0111100100000000000000000010000000000000000000000000000000000000R
0101101001000010100100000000110100000000000000000000000000000000T #<--- Attack
0111100100000000000000001011000000000000000000000000000000000000R
0111100100000000000000001010000000000000000000000000000000000000R
...
0111011000000000000000000010111100000000000000000000000000000000R
0110110111000111100000010010011100000000000000000000000000000000T #<--- Attack
0111011000000000000000000001111100000000000000000000000000000000R
'''
def sliding_windows(data, seq_length):
'''
Separate 64bit by 1bit and make it as list
'''
x = []
y = []
L = len(data)
for i in range(L - seq_length-1):
_x = [list(map(int,e[:-1])) for e in data[i:(i+seq_length)]]
_y = list(map(int, data[i+seq_length][:-1]))
x.append(_x)
y.append(_y)
return np.array(x),np.array(y)
def sliding_windows_eval(data, seq_length):
'''
Separate 64bit by 1bit and make it as list
'''
x = []
y = []
gt = []
L = len(data)
for i in range(L - seq_length):
_x = [list(map(int,e[:-2])) for e in data[i:(i+seq_length)]]
_y = list(map(int, data[i+seq_length][:-2]))
x.append(_x)
y.append(_y)
gt.append(data[i + seq_length][-2])
return np.array(x),np.array(y), np.array(gt)
class LSTM(nn.Module):
def __init__(self):
super(LSTM, self).__init__()
self.num_classes = 64
self.num_layers = 1
self.input_size = 64
self.hidden_size = 512
self.lstm = nn.LSTM(input_size=self.input_size, hidden_size=self.hidden_size,
num_layers=self.num_layers, batch_first=True)
self.fc = nn.Linear(self.hidden_size, self.num_classes)
def forward(self, x):
h_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) #([1, batch, 512])
c_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) #([1, batch, 512])
# Propagate input through LSTM
output, (h_out, _) = self.lstm(x, (h_0, c_0)) # x : [batch, seq, 64], output : [batch, seq, 64]
# h_out : [1, batch, 512]
h_out = h_out.view(-1, self.hidden_size)
out = self.fc(h_out)
return out
# Train ------------------------------------------------------------------------------------------ #
with open('./log/%s_normal.log' % ID, 'r') as f:
training_data = f.readlines()
x, y = sliding_windows(training_data, seq_length)
trainX = torch.Tensor(np.array(x))
trainY = torch.Tensor(np.array(y))
dataset = TensorDataset(trainX, trainY)
dataloader = DataLoader(dataset, batch_size=1000, shuffle=False)
# optimizer = torch.optim.Adam(lstm.parameters(), lr=learning_rate)
optimizer = torch.optim.SGD(lstm.parameters(), lr=learning_rate)
for epoch in range(num_epochs):
for batch_idx, samples in enumerate(dataloader):
x_samples, y_samples = samples
outputs = lstm(x_samples)
optimizer.zero_grad()
# obtain the loss function
loss = criterion(outputs, y_samples)
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print("Epoch: %d, loss: %1.5f" % (epoch, loss.item()))
PATH = 'D:/002_5_OTIDS/log/{}_normal.pt'.format(ID)
torch.save(lstm.state_dict(), PATH)
# ----------------------------------------------------------------------------------------------- #
# Test ------------------------------------------------------------------------------------------ #
PATH = 'D:/002_5_OTIDS/log/{}_normal.pt'.format(ID)
lstm.load_state_dict(torch.load(PATH))
val_losses = []
with open('./log_fuzzy/%s_fuzzy.log' % ID, 'r') as f:
test_data = f.readlines()
x, y, gt = sliding_windows_eval(test_data, seq_length)
testX = torch.Tensor(np.array(x))
testY = torch.Tensor(np.array(y))
dataset = TensorDataset(testX, testY)
dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
with torch.no_grad(): # [21.05.11] check one by one
for idx, samples in enumerate(dataloader):
x_samples, y_samples = samples
lstm.eval()
outputs = lstm(x_samples)
val_loss = criterion(outputs, y_samples)
val_losses.append(val_loss)
if gt[idx] == 'T':
print(val_loss)
# ----------------------------------------------------------------------------------------------- #
My question is
I got val_loss 0.2xxxx which has label ‘T’ and 0.1xxxx which has label ‘R’
This doesn’t seem to have big difference. Is this due to the nature of my data?
or My training is wrong??
Can you check my code a little bit? Is there a wrong?
Thanks ahead.
Have a good day.
|
st32908
|
I wanna find some torch function like this:
input : a = [[1,2,3,4], [5,6,7,8]], b = [[0,0,0,0],[0,0,0,0]]
output : c = [[[1,0],[2,0],[3,0],[4,0]],[[5,0],[6,0],[7,0],[8,0]]]
Does this kind of function exist in torch?
|
st32909
|
Solved by ptrblck in post #2
Yes, you can use torch.stack:
a = torch.tensor([[1,2,3,4], [5,6,7,8]])
b = torch.tensor([[0,0,0,0],[0,0,0,0]])
c = torch.tensor([[[1,0],[2,0],[3,0],[4,0]],[[5,0],[6,0],[7,0],[8,0]]])
print(c)
> tensor([[[1, 0],
[2, 0],
[3, 0],
[4, 0]],
[[5, 0],
…
|
st32910
|
Yes, you can use torch.stack:
a = torch.tensor([[1,2,3,4], [5,6,7,8]])
b = torch.tensor([[0,0,0,0],[0,0,0,0]])
c = torch.tensor([[[1,0],[2,0],[3,0],[4,0]],[[5,0],[6,0],[7,0],[8,0]]])
print(c)
> tensor([[[1, 0],
[2, 0],
[3, 0],
[4, 0]],
[[5, 0],
[6, 0],
[7, 0],
[8, 0]]])
d = torch.stack((a, b), dim=2)
print(d)
> tensor([[[1, 0],
[2, 0],
[3, 0],
[4, 0]],
[[5, 0],
[6, 0],
[7, 0],
[8, 0]]])
|
st32911
|
I’m working through a tutorial on transformers (Tutorial 6: Transformers and Multi-Head Attention — UvA DL Notebooks v1.0 documentation 3) and I came across this block of code about positional encoding.
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
"""
Inputs
d_model - Hidden dimensionality of the input.
max_len - Maximum length of a sequence to expect.
"""
super().__init__()
# Create matrix of [SeqLen, HiddenDim] representing the positional encoding for max_len inputs
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
# register_buffer => Tensor which is not a parameter, but should be part of the modules state.
# Used for tensors that need to be on the same device as the module.
# persistent=False tells PyTorch to not add the buffer to the state dict (e.g. when we save the model)
self.register_buffer('pe', pe, persistent=False)
def forward(self, x):
x = x + self.pe[:, :x.size(1)]
return x
I haven’t understood what the register_buffer does, would someone be able to explain it in an easier way? I get that it’s saved alongside model parameters but isn’t included in gradient calculations - so what’s the difference between this and just setting the requires_grad to be False?
|
st32912
|
Hi all,
I’m looking for a way to speed up my current data loading scheme, and would really appreciate any suggestions you might have.
I’m currently trying to build a workflow to hopefully train on up to >100M data points with a total size of >20TB. (each data point is more complicated than just X and y, hence the size. I can clarify more if needed). Of course holding all that data in RAM and ask GPU to fetch data from there is not possible, so in order to do this, I’m currently doing it this way: first pre-process all the data in chunks of 5000 datapoints, and save them as separate lmdb files 1.lmdb, 2.lmdb,... (each containing 5000 datapoints). during training, process the 5000 chunks sequentially. so first load and train with all the datapoints in 1.lmdb, before load and train datapoints in 2.lmdb, which I called the “partial caching scheme”, and the dataset code looks like:
class DatasetPartialCache(Dataset):
def __init__(
self,
db_paths,
):
self.db_paths = db_paths
self.envs = []
self.keys_list = []
self.length_list = []
for db_path in self.db_paths:
temp_env = self.connect_db(db_path)
self.envs.append(temp_env)
self.keys_list.append(
[f"{j}".encode("ascii") for j in range(temp_env.stat()["entries"])]
)
self._keylen_cumulative = np.cumsum(self.length_list).tolist()
self.total_length = np.sum(self.length_list)
def __len__(self):
return self.total_length
def __load_dataset__(self, db_idx):
dataset = []
with self.envs[db_idx].begin(write=False) as txn:
for idx in range(self.length_list[db_idx]):
data = txn.get(self.keys_list[db_idx][idx])
data_object = pickle.loads(data)
dataset.append(data_object)
self.loaded_db_idx = db_idx
self.loaded_dataset = dataset
def __getitem__(self, idx):
db_idx = bisect.bisect(self._keylen_cumulative, idx)
if db_idx != 0:
el_idx = idx - self._keylen_cumulative[db_idx - 1]
else:
el_idx = idx
if db_idx != self.loaded_db_idx:
self.__load_dataset__(db_idx)
return self.loaded_dataset[el_idx]
@property
def input_dim(self):
return self[0].fingerprint.shape[1]
def connect_db(self, lmdb_path):
env = lmdb.open(
lmdb_path,
subdir=False,
readonly=True,
lock=False,
readahead=False,
meminit=False,
max_readers=1,
)
return env
The functions to keep an eye on are the getitem function and the load_dataset function. basically, the idea is when it’s first asking for a data point within a lmdb file, load the whole lmdb file to RAM, and the sampler is specially designed to process all the data points within a lmdb file first before moving on to the next lmdb file.
The sampler loos like this in case you are interested:
class PartialCacheSampler(Sampler):
def __init__(self, length_list, val_frac):
len_cumulative = np.cumsum(length_list)
len_dataset = np.sum(length_list)
len_val = int(len_dataset * val_frac)
len_train = len_dataset - len_val
for i, cum_len in enumerate(len_cumulative):
if cum_len >= len_train:
self.length_list = length_list[: i + 1]
self.length_list[-1] -= cum_len - len_train
break
self.num_datasets = len(self.length_list)
self.start_idx_list = [0] + np.cumsum(self.length_list).tolist()
self.total_length = np.sum(self.length_list)
def __iter__(self):
datapoint_order = []
dataset_order = torch.randperm(self.num_datasets).tolist()
for dataset_idx in dataset_order:
start_idx = self.start_idx_list[dataset_idx]
datapoint_order += [
i + start_idx
for i in torch.randperm(self.length_list[dataset_idx]).tolist()
]
return iter(datapoint_order)
basically it randomizes the order of lmdb files for each epoch (10.lmdb > 5.lmdb > 22.lmdb >…), and randomize the orders of datapoint within each lmdb file, but still ask for all the datapoints within each lmdb file first before moving on to the next, to keep the partial cache scheme working. I did test this scheme and it works, so it can deal with an arbitrarily large amount of training data as long as they can be stored on disk.
However, I did a benchmark of this scheme, versus a similar scheme but with all the datapoints in all the lmdb files pre-load into RAM (full cache), and it’s about 3-5x slower. I did a further diagnose and found that the loading time of each lmdb file is ~5s, and the training time on that 5000 datapoints is ~2s, so most of the time GPU was just sitting there idle, waiting for data to be loaded to RAM. so I’m trying to find a way to optimize the dataset, do you have any idea how to improve the current workflow, ideally with a minimal amount of changes? Maybe there are some tools existing for this purpose that I’m not aware of?
One idea I had was having independent processes to “pre-load” the next few lmdb files to RAM while the model is being trained on the current one to eliminate the IO bottleneck. But I have absolutely no clue how to carry this out. Note that the sequence of lmdb files is randomized for every epoch.
Please let me know if you have any thoughts on this. Any suggestion/comment would be greatly appreciated.
|
st32913
|
i have tensors of size [336,261] generated in for loop for 10 iterations, i want them to be stored as out=[10,336,261]. what is the possible way to do this?
Right now i am storing it in list but when i have been unable to convert the list in a tensor module. any suggestions or help?
|
st32914
|
Solved by a_d in post #2
Hello
you could use torch.stack
If tensor_list is the list of the tensors you obtain after the loop then -
desired_tensor = torch.stack(tensor_list, dim=0)
|
st32915
|
Hello
you could use torch.stack
If tensor_list is the list of the tensors you obtain after the loop then -
desired_tensor = torch.stack(tensor_list, dim=0)
|
st32916
|
Hi all,
I am new to deep learning and pytorch. Really struggling. I need to implement federated learning on BreakHis database for cancer prediction. I implemented using VGG19 and only getting accuracy of 56%. Any one can help to increase the accuracy and debug my code?
|
st32917
|
Hello all,
I’m a newbie to PyTorch and I would like to run inference on a mobile device (ARM-based). I have my PyTorch model that needs to run outside my development environment where the model prediction will be executed.
Is there a PyTorch interpreter for embedded devices or what is workflow when the model needs to be run on embedded devices? How should I proceed to execute the PyTorch models on memory and computational constraint devices?
Thank you.
|
st32918
|
I’m currently working on porting code from Keras to PyTorch. I’m working with many GPUs and CPUs so it’s important to have batch generation happening in parallel. My problem is that I’m trying to use the num_workers argument on the DataLoader class, but am meeting with errors. Current relevant toy code:
import torch
torch.multiprocessing.set_start_method('spawn')
from torch.utils.data import Dataset, DataLoader
X_train = torch.randn(100,100)
y_train = torch.randn(100,100)
w_train = torch.randn(100,100)
class My_Dataset(Dataset):
def __init__(self, x_input, y_labels, w_labels):
self.y_labels = y_labels
self.w_labels = w_labels
self.x_input = x_input
self.len = self.x_input.shape[0]
def __len__(self):
return self.len
def __getitem__(self, idx):
if __name__ == '__main__':
print('Error! being run by {}'.format(__name__))
X = self.x_input[idx]
y = self.y_labels[idx]
w = self.w_labels[idx]
return X, y, w
training_dataset = My_Dataset(X_train, y_train, w_train)
training_dataloader = DataLoader(training_dataset, batch_size=10, shuffle=True, num_workers=15, pin_memory=False)
for batch_num, (inputs, labels_y, labels_w) in enumerate(training_dataloader):
(inputs, labels_y, labels_w) =(inputs.cuda(), labels_y.cuda(), labels_w.cuda())
print(inputs)
Removing torch.multiprocessing.set_start_method(‘spawn’) causes the code to run, but the batch generation runs in the main process (the error message I wrote into the dataset prints, also on my non-toy problem it takes unacceptably long). I’ve tried both ‘spawn’ and ‘forkserver’, but both fail and I can’t even figure out how to get a relevant error message. Right now the error just says one of the processes failed and setting num_workers =0 might get a better message.
Python version = 3.7.9, torch version = 1.7.0
|
st32919
|
Solved by ptrblck in post #4
Based on the first post I assume that your code runs fine with num_workers=0 for the full epoch and doesn’t yield any error?
If that’s the case, could you check if you have enough shared memory available?
|
st32920
|
Unsure if you are using Windows, but you could try to use the if-clause protection as described here 50.
Could you also post the error messages you are seeing?
|
st32921
|
I’m on Linux. I implemented the if-clause protection, but it didn’t change the behavior of the code.
Behavior with torch.multiprocessing.set_start_method(‘fork’):
prints 100x
Error! being run by __main__
Behavior with torch.multiprocessing.set_start_method(‘spawn’):
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _try_get_data(self, timeout)
871 try:
--> 872 data = self._data_queue.get(timeout=timeout)
873 return (True, data)
~/.conda/envs/torch_env/lib/python3.7/multiprocessing/queues.py in get(self, block, timeout)
103 timeout = deadline - time.monotonic()
--> 104 if not self._poll(timeout):
105 raise Empty
~/.conda/envs/torch_env/lib/python3.7/multiprocessing/connection.py in poll(self, timeout)
256 self._check_readable()
--> 257 return self._poll(timeout)
258
~/.conda/envs/torch_env/lib/python3.7/multiprocessing/connection.py in _poll(self, timeout)
413 def _poll(self, timeout):
--> 414 r = wait([self], timeout)
415 return bool(r)
~/.conda/envs/torch_env/lib/python3.7/multiprocessing/connection.py in wait(object_list, timeout)
920 while True:
--> 921 ready = selector.select(timeout)
922 if ready:
~/.conda/envs/torch_env/lib/python3.7/selectors.py in select(self, timeout)
414 try:
--> 415 fd_event_list = self._selector.poll(timeout)
416 except InterruptedError:
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/_utils/signal_handling.py in handler(signum, frame)
65 # Python can still get and update the process status successfully.
---> 66 _error_if_any_worker_fails()
67 if previous_handler is not None:
RuntimeError: DataLoader worker (pid 17676) exited unexpectedly with exit code 1. Details are lost due to multiprocessing. Rerunning with num_workers=0 may give better error trace.
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
<ipython-input-7-b7dbc62fb341> in <module>
5
6 if __name__ == '__main__':
----> 7 main()
<ipython-input-7-b7dbc62fb341> in main()
1 def main():
----> 2 for batch_num, (inputs, labels_y, labels_w) in enumerate(training_dataloader):
3 (inputs, labels_y, labels_w) =(inputs.cuda(), labels_y.cuda(), labels_w.cuda())
4 #print(inputs)
5
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __next__(self)
433 if self._sampler_iter is None:
434 self._reset()
--> 435 data = self._next_data()
436 self._num_yielded += 1
437 if self._dataset_kind == _DatasetKind.Iterable and \
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _next_data(self)
1066
1067 assert not self._shutdown and self._tasks_outstanding > 0
-> 1068 idx, data = self._get_data()
1069 self._tasks_outstanding -= 1
1070 if self._dataset_kind == _DatasetKind.Iterable:
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _get_data(self)
1032 else:
1033 while True:
-> 1034 success, data = self._try_get_data()
1035 if success:
1036 return data
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _try_get_data(self, timeout)
883 if len(failed_workers) > 0:
884 pids_str = ', '.join(str(w.pid) for w in failed_workers)
--> 885 raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str)) from e
886 if isinstance(e, queue.Empty):
887 return (False, None)
RuntimeError: DataLoader worker (pid(s) 17676) exited unexpectedly
Behavior with torch.multiprocessing.set_start_method(‘forkserver’):
---------------------------------------------------------------------------
Empty Traceback (most recent call last)
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _try_get_data(self, timeout)
871 try:
--> 872 data = self._data_queue.get(timeout=timeout)
873 return (True, data)
~/.conda/envs/torch_env/lib/python3.7/multiprocessing/queues.py in get(self, block, timeout)
104 if not self._poll(timeout):
--> 105 raise Empty
106 elif not self._poll():
Empty:
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
<ipython-input-7-b7dbc62fb341> in <module>
5
6 if __name__ == '__main__':
----> 7 main()
<ipython-input-7-b7dbc62fb341> in main()
1 def main():
----> 2 for batch_num, (inputs, labels_y, labels_w) in enumerate(training_dataloader):
3 (inputs, labels_y, labels_w) =(inputs.cuda(), labels_y.cuda(), labels_w.cuda())
4 #print(inputs)
5
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __next__(self)
433 if self._sampler_iter is None:
434 self._reset()
--> 435 data = self._next_data()
436 self._num_yielded += 1
437 if self._dataset_kind == _DatasetKind.Iterable and \
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _next_data(self)
1066
1067 assert not self._shutdown and self._tasks_outstanding > 0
-> 1068 idx, data = self._get_data()
1069 self._tasks_outstanding -= 1
1070 if self._dataset_kind == _DatasetKind.Iterable:
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _get_data(self)
1032 else:
1033 while True:
-> 1034 success, data = self._try_get_data()
1035 if success:
1036 return data
~/.conda/envs/torch_env/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _try_get_data(self, timeout)
883 if len(failed_workers) > 0:
884 pids_str = ', '.join(str(w.pid) for w in failed_workers)
--> 885 raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str)) from e
886 if isinstance(e, queue.Empty):
887 return (False, None)
RuntimeError: DataLoader worker (pid(s) 17746, 17747, 17748, 17749, 17750, 17751, 17752, 17753, 17754, 17755, 17756, 17757, 17758, 17759, 17760) exited unexpectedly
If anyone has suggestions on getting more specific error messages, that would also be very helpful. Right now I don’t know how to make things print from inside the process. Also very helpful if someone has a toy example of a dataloader with num_workers>0 that plays nice
|
st32922
|
Based on the first post I assume that your code runs fine with num_workers=0 for the full epoch and doesn’t yield any error?
If that’s the case, could you check if you have enough shared memory available?
|
st32923
|
As I understand, this is your main concern:
bayes_and_blues:
but the batch generation runs in the main process
It may look like batch generation is been doing only in the main, but if you check the output of the Linux top command throughout the program execution, you will clearly see the additional number of processes has been fired up, and they were busy utilizing some PCU compute power.
With regard to the printing of error about executing in main, I am not sure, but I think every instance of dataloader has its own instance of dataset.
|
st32924
|
Yes, the code runs with ‘num_workers=0’ for the full epoch and doesn’t yield any error (other than the one I wrote in).
As for shared memory available, the system has several hundred GB of memory. Should be more than enough for 100*100 random floats even with 15 workers. Am I missing something special about shared memory?
|
st32925
|
If it is spinning up more processes, they’re not doing anything to make things faster. On my problem with the GPU also involved I see that batch generation is throttling my process (because adding operations to __get_item__() makes things take longer) and setting num_workers=15 doesn’t speed things up (like it does in keras).
|
st32926
|
Yes, system RAM isn’t used as shared memory and you can adapt it in your system step.
|
st32927
|
Projects could be really complicated. To understand what is a problem I would try to profile my program and find the bottleneck. It could be in any major moving part of the pipeline: from preparing data and generating the batches to training the models on the distributed system. So, for example I would check if my cpus are struggling to prepare data for GPU/s and GPU/s are spending a lot of time waiting for the data or is it perhaps vice versa and the model is too big, so batches are waiting to come into GPU for too long. It could also be the problem to utilize all GPUs correctly using distributed parallel training and so on.
|
st32928
|
On my problem if I just have the dataloader supply a a tensor from memory it takes ~1 s/iteration. However, my setup requires that during training I add a tensor of random noise to the tensor. Generating the random tensor is CPU intensive and the time per iteration jumps to ~6s/iteration with 1 CPU (I can’t precompute the noise because I add different noise every epoch). In Keras adding workers brings this back down to ~1s/iteration because I can use many CPUs to generate the random noise and prepare the batch. Right now I haven’t found an analog in tensorflow that lets me do this successfully.
|
st32929
|
Ok, now I can see you have some troublesome point in your pipeline. It may help to post some code snippets on how you create tensors and add noise tensors so other people in pytorch community can help to improve performance.
|
st32930
|
Looks like this was probably the issue. The system only has 45k of shared. I found this 20 thread to be relevant.
Unfortunately, I don’t think I’m going to be able to make changes to the system settings.
|
st32931
|
In my experience, num_workers has unpredictable behavior for many threads. Having 16 logical threads I can usually only run around 8 as a stable configuration and only get a memory error once in a blue moon.
If anyone else is having problems I would suggest running 4-6 num_workers. More is often not needed.
|
st32932
|
Hello!
I am currently having diffiiculties with implementing the lottery ticket hypothesis.
I got a trained and pruned model, and i am trying to transfer the weight masks from the trained network to the untrained one.
I have tried this but it has no effect:
def transfer_hooks(trained_model,fresh):
fresh.conv1.register_forward_pre_hook(trained_model.conv1._forward_pre_hooks)
Also, deepcopy seems to be broken when copying pruned layers, throwing
RuntimeError: Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment
I have also tried with
copymodel.load_state_dict(torch.load(model_path))
but it only works if i apply pruning once on the copymodel before loading, else it throws:
RuntimeError: Error(s) in loading state_dict for network:
Missing key(s) in state_dict: "conv1.weight", "conv2.weight", "fc1.weight", "fc2.weight".
Unexpected key(s) in state_dict: "conv1.weight_orig", "conv1.weight_mask", "conv2.weight_orig", "conv2.weight_mask", "fc1.weight_orig", "fc1.weight_mask", "fc2.weight_orig", "fc2.weight_mask".
is there a more elegant solution out there, that doesnt require to apply a pruning step on the network beforehand and simply allows me to transfer the “pruning” component?
|
st32933
|
You pruned model is in a pruned reparametrization state, where pruned weights have been replaced as such: weight --> weight_orig, weight_mask.
Now, if you try to load those into an unpruned model via a state_dict, it will of course fail, because that reparametrization doesn’t exist in your unpruned model, and the keys in the state_dicts don’t match.
Instructions on how to solve this are provided in these answers: Proper way to load a pruned network 14
Let me know if you have any further questions.
|
st32934
|
Hey @Dan_Blanaru , any luck with transferring the forward pre hook from checkpoint to a newly instantiated model? If I understand correctly, PyTorch hooks are applied to the model instance and not to the parameters. So unless one saves the model instance along with the state_dict, the hooks are lost?
|
st32935
|
I am sorry to ask this, may be not related to forum, but what is this cashe folder? and for what its used
?
|
st32936
|
Hi,
I saw this in code:
coors = coors.int()
and coors is a tensor, whose shape is [1515,4].
I have googled the init function but found nothing.
Anybody know this function?
|
st32937
|
Solved by ptrblck in post #2
Based on your code snippet it seems you are looking for the int() operator, not init().
If that’s the case: the int() operation will return a tensor transformed to the int32 data type:
x = torch.randn(10) * 10
print(x)
> tensor([ 2.9199, -13.7902, -0.3769, -11.2643, -2.8111, -0.7583, -2.9747,…
|
st32938
|
Based on your code snippet it seems you are looking for the int() operator, not init().
If that’s the case: the int() operation will return a tensor transformed to the int32 data type:
x = torch.randn(10) * 10
print(x)
> tensor([ 2.9199, -13.7902, -0.3769, -11.2643, -2.8111, -0.7583, -2.9747,
12.1106, -2.1383, 6.7038])
y = x.int()
print(y)
> tensor([ 2, -13, 0, -11, -2, 0, -2, 12, -2, 6], dtype=torch.int32)
|
st32939
|
Currently, I am pursuing a regression problem where I am attempting to estimate the time derivative of chemical species undergoing reaction and I am having a issue with the scales of my output. Since this is a detonation reaction, my outputs can range from essentially 0 for most cases to very large for others (during a detonation).
I think I am having problems with MSE as the loss function for this problem, since what I am really after is a low percentage error on each derivative estimation. If the output is meant to be 0.01 and the network predicts 10, I would like to punish this much more heavily than if the output is meant to be 1000 and the network predicts 1010. As of right now, I suspect that these large derivatives are dominating due to large contributions to loss.
Is there a loss function that implements a relative error loss based on training data? If I am correct in thinking that there is not, what is the recommended way to define a custom loss function?
|
st32940
|
I am not sure about the loss that would be good for your case but if you want a custom loss formulation here is a great thread Custom loss functions - #2 by ptrblck 47
|
st32941
|
Hi everyone,
I’m using a custom Dataset, which loads data from a single h5. This runs fast and works well with num_workers=6.
However, I have 20 files I would like to load from, so I created 20 datasets and tried to use the mentioned dataset by creating a torch.utils.data.dataset.ConcatDataset.
Surprisingly, this runs extremely slow. As it turns out, 87% of the time is spent waiting.
image1127×159 21.3 KB
Things I thought and tried:
After looking this up, I saw a suggestion to use pin_memory=False. This did not help to speed up anything. The suggestion is found here: DataLoader: method 'acquire' of '_thread.lock' objects - #2 by bask0
I can’t use the torch.utils.data.dataset.ChainDataset, since my dataset is not iterable.
Looking for a solution, I came across the DistributedSampler. I thought this would maybe enable different workers to work with different subsets of the data, obviating the need to access the same object (a guess of mine). Looking this up, I saw only mentions of multi-nodes/multi-gpus training, which I’m not searching for.
torch.utils.data — PyTorch 1.7.0 documentation 3
Does anyone know how to approach this?
Thanks in advance!
|
st32942
|
+1. Same issue here. Training performance varies for each batch, some batches are loaded very quickly, some take an unacceptable amount of time.
Have 3000 .npy files with multiple samples in each. Unable to find a scalable solution for building a map-style dataset when samples are distributed across multiple files on disk.
|
st32943
|
import math
from copy import copy
from pathlib import Path
import numpy as np
import pandas as pd
import requests
import torch
import torch.nn as nn
from PIL import Image
from torch.cuda import amp
def autopad(k, p=None): # kernel, padding
# Pad to 'same'
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p
class Conv(nn.Module):
# Standard convolution
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
super(Conv, self).__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
self.bn = nn.BatchNorm2d(c2)
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
def forward(self, x):
print("Conv forward")
return self.act(self.bn(self.conv(x)))
def fuseforward(self, x):
return self.act(self.conv(x))
class Focus(nn.Module):
# Focus wh information into c-space
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
super(Focus, self).__init__()
self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
# self.contract = Contract(gain=2)
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
# return self.conv(self.contract(x))
x = torch.ones(3,416,416)
print("input dimension : ",x.shape)
print(x[..., ::2, ::2].shape)
print(x[..., 1::2, ::2].shape)
print(x[..., ::2, 1::2].shape)
print(x[..., 1::2, 1::2].shape)
x = torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]])
print(x.shape)
focuslayer = Focus(3,6)
x = focuslayer.conv(x)
print(x.shape)
error message :
Expected 4-dimensional input for 4-dimensional weight [6, 12, 1, 1], but got 3-dimensional input of size [12, 208, 208] instead
Can anyone please help me debug this ? I am a beginner trying to understand how layers work.
|
st32944
|
Usually conv layers expect a 4 dimensional input where the first dimension is the batch dimension. If you are trying to pass a single image or example can you try something like x.unsqueeze(0) to add a batch dimension?
|
st32945
|
Hi all, I’m able to import torch but am getting an error about torch not being defined (NameError: name ‘torch’ is not defined) for the following statement:
device = torch.device(‘cuda’) if torch.cuda.is_available() else torch.device(‘cpu’)
Background: do not have cuda, just using cpu. python version: 3.7.6, pytorch ver: 1.5.1, using conda. Any insights would be greatly appreciated, thanks
|
st32946
|
Sometimes when I encounter this, restarting the Python kernel and re-importing torch does the trick.
|
st32947
|
you can use the option execution enviroment → change type of execution enviroment → aceleration by hardaware : none
|
st32948
|
I have trained a ResNet-50 model on CIFAR-10 using transfer learning with some modifications. After which, I am using torch.nn.utils.prune to prune weights using global magnitude pruning in an iterative manner. The model architecture is as follows:
print(fine_tuned_model)
ResNet(
(conv1): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
(layer1): Sequential(
(0): Bottleneck(
(conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(layer2): Sequential(
(0): Bottleneck(
(conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(3): Bottleneck(
(conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(layer3): Sequential(
(0): Bottleneck(
(conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False)
(1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(3): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(4): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(5): Bottleneck(
(conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(layer4): Sequential(
(0): Bottleneck(
(conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(downsample): Sequential(
(0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False)
(1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(1): Bottleneck(
(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
(2): Bottleneck(
(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
)
)
(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
(fc): Linear(in_features=2048, out_features=10, bias=True)
)
To count the number of pruned connections (or, number of zeroes), number of total connections and the resulting sparsity, the following two functions are defined:
def measure_module_sparsity(module, weight = True, bias = False, use_mask = False):
num_zeros = 0
num_elements = 0
if use_mask == True:
for buffer_name, buffer in module.named_buffers():
if "weight_mask" in buffer_name and weight == True:
num_zeros += torch.sum(buffer == 0).item()
num_elements += buffer.nelement()
if "bias_mask" in buffer_name and bias == True:
num_zeros += torch.sum(buffer == 0).item()
num_elements += buffer.nelement()
else:
for param_name, param in module.named_parameters():
if "weight" in param_name and weight == True:
num_zeros += torch.sum(param == 0).item()
num_elements += param.nelement()
if "bias" in param_name and bias == True:
num_zeros += torch.sum(param == 0).item()
num_elements += param.nelement()
sparsity = num_zeros / num_elements
return num_zeros, num_elements, sparsity
def measure_global_sparsity(
model, weight = True,
bias = False, conv2d_use_mask = False,
linear_use_mask = False):
num_zeros = 0
num_elements = 0
for module_name, module in model.named_modules():
if isinstance(module, torch.nn.Conv2d):
module_num_zeros, module_num_elements, _ = measure_module_sparsity(
module, weight=weight, bias=bias, use_mask=conv2d_use_mask)
num_zeros += module_num_zeros
num_elements += module_num_elements
elif isinstance(module, torch.nn.Linear):
module_num_zeros, module_num_elements, _ = measure_module_sparsity(
module, weight=weight, bias=bias, use_mask=linear_use_mask)
num_zeros += module_num_zeros
num_elements += module_num_elements
sparsity = num_zeros / num_elements
return num_zeros, num_elements, sparsity
To call the function-
num_zeros, num_elements, sparsity = measure_global_sparsity(
fine_tuned_model, weight = True,
bias = False, conv2d_use_mask = True,
linear_use_mask = False)
this gives the error:
ZeroDivisionError Traceback (most recent call last)
in
----> 1 num_zeros, num_elements, sparsity = measure_global_sparsity(
2 fine_tuned_model, weight = True,
3 bias = False, conv2d_use_mask = True,
4 linear_use_mask = False)
5
in measure_global_sparsity(model, weight, bias, conv2d_use_mask, linear_use_mask)
10
11 if isinstance(module, torch.nn.Conv2d):
—> 12 module_num_zeros, module_num_elements, _ = measure_module_sparsity(
13 module, weight=weight, bias=bias, use_mask=conv2d_use_mask)
14 num_zeros += module_num_zeros
in measure_module_sparsity(module, weight, bias, use_mask)
21 num_elements += param.nelement()
22
—> 23 sparsity = num_zeros / num_elements
24
25 return num_zeros, num_elements, sparsity
ZeroDivisionError: division by zero
What’s the problem OR is there another way to count the: number of zeroes and the total number of parameters within this ResNet-50 model?
|
st32949
|
Hi Arjun!
grid_world:
def measure_module_sparsity(module, weight = True, bias = False, use_mask = False):
num_zeros = 0
num_elements = 0
if use_mask == True:
for buffer_name, buffer in module.named_buffers():
...
else:
for param_name, param in module.named_parameters():
...
sparsity = num_zeros / num_elements
return num_zeros, num_elements, sparsity
22
—> 23 sparsity = num_zeros / num_elements
24
25 return num_zeros, num_elements, sparsity
ZeroDivisionError: division by zero
What’s the problem … ?
If you call measure_module_sparsity() on a Module such as ReLU
that contains neither buffers nor parameters, then num_elements (and
num_zeros) will remain zero (because they never get incremented)
so you get the ZeroDivisionError.
Best.
K. Frank
|
st32950
|
I am referring to ResNet paper by Kaiming He et al. where in Table 1, the first conv layer has 64 filters in it. I just changed filter size from 7 to 3 and stride from 2 to 1.
Probably, removing a max pool layer might also make sense since CIFAR-10 dataset has small images to begin with which don’t need spatial reduction right after the first conv layer.
|
st32951
|
I don’t think that “measure_module_sparsity()” function will get called on a module such as “ReLU” because within “measure_global_sparsity()” function, the for loop:
for module_name, module in model.named_modules():
if isinstance(module, torch.nn.Conv2d):
module_num_zeros, module_num_elements, _ = measure_module_sparsity(
module, weight=weight, bias=bias, use_mask=conv2d_use_mask)
num_zeros += module_num_zeros
num_elements += module_num_elements
will make sure that “measure_module_sparsity()” is only called for Conv2d and/or Linear layers.
At least, that’s what my understanding of the code is.
|
st32952
|
Hi Arjun!
grid_world:
I don’t think that “measure_module_sparsity()” function will get called on a module such as “ReLU”
Yes, you are correct. My mistake.
All I can say is that your code works for me (on a stock torchvision
resnet50).
It is possible to instantiate a degenerate Linear (or Conv2d) that has
no elements in its parameters, but that would be weird, and doesn’t
happen in torchvision’s resnet50 and does not appear to be happening
in your model.
All I can suggest is that you check (and tell us) what version of pytorch
you are using, and instrument your code so that it prints out the name
(and details) of any module for which num_elements is zero before
performing the division.
Here is a script that runs your function on a stock resnet50 and also
illustrates a degenerate Linear:
import torch
print (torch.__version__)
import torchvision
print (torchvision.__version__)
_ = torch.manual_seed (2021)
def measure_module_sparsity(module, weight = True, bias = False, use_mask = False):
num_zeros = 0
num_elements = 0
if use_mask == True:
for buffer_name, buffer in module.named_buffers():
if "weight_mask" in buffer_name and weight == True:
num_zeros += torch.sum(buffer == 0).item()
num_elements += buffer.nelement()
if "bias_mask" in buffer_name and bias == True:
num_zeros += torch.sum(buffer == 0).item()
num_elements += buffer.nelement()
else:
for param_name, param in module.named_parameters():
if "weight" in param_name and weight == True:
num_zeros += torch.sum(param == 0).item()
num_elements += param.nelement()
if "bias" in param_name and bias == True:
num_zeros += torch.sum(param == 0).item()
num_elements += param.nelement()
sparsity = num_zeros / num_elements
return num_zeros, num_elements, sparsity
def measure_global_sparsity(
model, weight = True,
bias = False, conv2d_use_mask = False,
linear_use_mask = False):
num_zeros = 0
num_elements = 0
for module_name, module in model.named_modules():
if isinstance(module, torch.nn.Conv2d):
module_num_zeros, module_num_elements, _ = measure_module_sparsity(
module, weight=weight, bias=bias, use_mask=conv2d_use_mask)
num_zeros += module_num_zeros
num_elements += module_num_elements
elif isinstance(module, torch.nn.Linear):
module_num_zeros, module_num_elements, _ = measure_module_sparsity(
module, weight=weight, bias=bias, use_mask=linear_use_mask)
num_zeros += module_num_zeros
num_elements += module_num_elements
sparsity = num_zeros / num_elements
return num_zeros, num_elements, sparsity
mod = torchvision.models.resnet50()
print ('type (mod) =', type (mod))
print ('measure_global_sparsity (mod) =', measure_global_sparsity (mod))
lin = torch.nn.Linear (1, 0)
print ('lin =', lin)
print ('calling measure_global_sparsity (lin) ...')
measure_global_sparsity (lin)
And here is its output:
1.9.0.dev20210504
0.10.0.dev20210504
type (mod) = <class 'torchvision.models.resnet.ResNet'>
measure_global_sparsity (mod) = (4, 25502912, 1.5684483403307042e-07)
lin = Linear(in_features=1, out_features=0, bias=True)
calling measure_global_sparsity (lin) ...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 70, in <module>
File "<string>", line 53, in measure_global_sparsity
File "<string>", line 31, in measure_module_sparsity
ZeroDivisionError: division by zero
Best.
K. Frank
|
st32953
|
PyTorch Version: 1.8.1
Torchvision Version: 0.9.1
Good idea. Let me try your suggestion and get back.
I am using Global, unstructured, absolute magnitude & iterative pruning by using “torch.nn.utils.prune” for which computing global sparsity is important. The algo used involves using a trained model as follows:
prune p% of smallest magnitude weights globally (p = 20%)
Fine-tune for n epochs to recover from the damage caused due to pruning
|
st32954
|
How Flashlight release 15 is gonna affect PyTorch development?
What are the plans?
|
st32955
|
hey,
is there a quick way to fill filters with Gauss filters + noise. i am familiar with …
def weights_init(m):
if isinstance(m, nn.Conv2d):
m.weight.data.normal_(0, 0.02)
m.bias.data.normal_(0, 0.001)
However I don’t know how to init s.t. we have gaussian filters.
|
st32956
|
Generate your filter with https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.filters.gaussian_filter.html 316
copy over into m.weight.data
m.weight.data is of shape: nOutputChannels x nInputChannels x kernelHeight x kernelWidth, so you have to generate nOutputChannels * nInputChannels, then make a numpy array of the same shape as m.weight.data and then copy:
generated_filters = ... # some scipy / numpy logic
m.weight.data.copy_(torch.from_numpy(generated_filters))
|
st32957
|
I solved it as above answer as
generated_filters = gaussian_filter(m.weight.data, sigma=0.5)
m.weight.data.copy_(torch.from_numpy(generated_filters))
Thank you.
|
st32958
|
Gaussian is another word for normal distribution, so you can just use:
torch.nn.init.normal_(m.weight, 0, 0.5)
Assuming you want a standard deviation (or sigma) of 0.5 and a mean of 0.
Also see: torch.nn.init — PyTorch 1.8.1 documentation 10
|
st32959
|
I would like to do a hyper-parameter search so I trained and evaluated with all of the combinations of parameters.
But watching nvidia-smi memory-usage, I found that GPU-memory usage value slightly increased each after a hyper-parameter trial and after several times of trials, finally I got out of memory error. I think it is due to cuda memory caching in no longer use Tensor. I know torch.cuda.empty_cache but it needs do del valuable beforehand. In my case, I couldn’t locate memory consuming variable.
What is the best way to release the GPU memory cache?
|
st32960
|
Hi,
torch.cuda.empty_cache() (EDITED: fixed function name) will release all the GPU memory cache that can be freed.
If after calling it, you still have some memory that is used, that means that you have a python variable (either torch Tensor or torch Variable) that reference it, and so it cannot be safely released as you can still access it.
You should make sure that you are not holding onto some objects in your code that just grow bigger and bigger with each loop in your search.
|
st32961
|
Thanks, @albanD !
So, the variables no longer referenced will be freed by using torch.cuda.empty_cache() right?
And I started to locate the memory consuming objects, but I couldn’t locate what variables gave me a bad effect.
As for variables related to cuda, I use same variable name (e.g. model, criterion) in different trials.
Anyway, I suspected below evaluation loop (sorry, it’s version 0.4, maybe version causes the problem?),
for i, (X, y) in tqdm(enumerate(val_loader), total=len(val_loader)):
X = Variable(X.cuda())
y = Variable(y.squeeze().cuda(non_blocking=False))
with torch.no_grad():
outputs = model(X)
loss = criterion(outputs, y)
prec1, prec5 = accuracy(outputs.data, target, top_k=(1, 5))
losses.update(loss.data[0], X.size(0))
top1.update(prec1[0], X.size(0))
top5.update(prec5[0], X.size(0))
|
st32962
|
So any variable that is no longer reference is freed in the sense that its memory can be used to create new tensors, but this memory is not released to the os (so will still look like it’s used using nvidia-smi).
empty_cache forces the allocator that pytorch uses to release to the os any memory that it kept to allocate new tensors, so it will make a visible change while looking at nvidia-smi, but in reality, this memory was already available to allocate new tensors.
Your code look good, I would double check that things that you send to your logger are not Variables but just python numbers using .item() as necessary.
Also, if you’re using 0.4 (I assume current master), then you should remove Variable and .data from your code and replace loss.data[0] by loss.item()
|
st32963
|
Thank you for detailed answering! I tried other things such as del model, loss, ... but no one helps…
Actually, I am using a little bit older version from the current master branch. But I have thought I should remove Variable and refactor code someday, so your instruction is so helpful, Thanks!
|
st32964
|
albanD:
torch.cuda.empty()
AttributeError: module ‘torch.cuda’ has no attribute ‘empty’
|
st32965
|
The variables prec1[0] and prec5[0] still hold reference to tensors. These should be replaced with prec1[0].item() and prec5[0].item() respectively. This is due to the fact that the accuracy method part of the pytorch imagenet training example code returns a tensor and can cause memory leak.
lyakaap:
top1.update(prec1[0], X.size(0))
top5.update(prec5[0], X.size(0))
@albanD Could you please clarify the difference between detach() and item() when called on a tensor. Are these effectively the same?
|
st32966
|
detach() return a tensor that shares storage (and the same device) with origin tensor, while item() return a converted python object.
|
st32967
|
I also face memory problem and using this command works.
Why torch doesn’t empty cache automatically though? Does emptying cache have much overhead?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.