id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st99468
|
Hi, my training set is very unbalanced, I mean big time. I use the sklearn.utils.class_weight.compute_class_weight() to get the weights of the classes and get the following coefficients: array([20.98221801, 21.80828959, 20.86804102, 0.25916362]). So we have 3 equally weighted classes and 1 very overwhelming.
As far as I understand, there is no need to normalize the weights for the WeightedRandomSampler():
# define the array of weights same shape as data
weights = np.empty_like(train_targets, dtype=np.float32)
# project the weights along the training set
for i in range(weights.shape[0]):
weights[i] = class_weights[train_targets[i]]
weights = torch.from_numpy(weights)
Then I am trying to return indices only from the dataloader, so I have:
data = Data()
weighted_sampler = WeightedRandomSampler(weights=weights, num_samples=len(train_targets), replacement=True)
# define dataloader
dataloader = DataLoader(data, sampler=weighted_sampler, batch_size=64, drop_last=True)
However, the dataloader is still heavily unbalanced:
for index in dataloader:
print(index.numpy())
print(targets[index])
break
|
st99469
|
Thanks for the code!
I’m not familiar with sklearn’s compute_clas_weight method, but from the docs it looks like the inverse class frequencies are returned, which should be alright.
It seems your classes 0 to 2 are the minority classes while you have a lot of samples of class3. Is that correct?
Skimming through your code I cannot find any obvious errors. Could you tell me your PyTorch version so that I could have a look later why it’s not working?
|
st99470
|
Yes, that is correct. Here is the pytorch version:
pytorch-cpu 0.4.0 py36_cpuhe774522_1 pytorch.
|
st99471
|
I used 0.4.0 and tried to stay as close to your code as possible.
This code works on my machine:
data = torch.randn(1000, 1)
target = torch.cat((
torch.zeros(998),
torch.ones(1),
torch.ones(1)*2
)).long()
cls_weights = torch.from_numpy(
compute_class_weight('balanced', np.unique(target.numpy()), target.numpy())
)
weights = cls_weights[target]
sampler = WeightedRandomSampler(weights, len(target), replacement=True)
dataset = TensorDataset(data, target)
batch_size = 64
loader = DataLoader(
dataset,
sampler=sampler,
batch_size=batch_size,
drop_last=True
)
for x, y in loader:
for cls in range(3):
print('Class {}: {}'.format(cls, (y==cls).sum().float() / batch_size))
Could you try it out and compare it to your code?
|
st99472
|
Ok, I found what is different; I was using the Dataset derivative as follows:
# dataset class for the data
class Data(Dataset):
def __init__(self):
pass
def __len__(self):
pass
def __getitem__(self, idx):
return idx
I was expecting it to return the indices I could use to subset the training set, however the weighting didn’t work. It DOES work with the TensorDataset, so I will use it instead. Thank you for your help!
|
st99473
|
Good to hear it’s working now!
However, your approach should also work, as the indices are sampled to select the target classes.
You could replace the TensorDataset with this dummy dataset:
class MyDataset(Dataset):
def __init__(self, data, target):
self.data = data
self.target = target
def __getitem__(self, index):
return index
def __len__(self):
return len(self.data)
, and you will see, that the indices of 998 and 999 are repeated very often.
Could you provide a code snippet so that I could have another look and make sure it’s not a bug for a special edge case?
|
st99474
|
So here is the thing: I defined the weights for the train_targets, however I used the sampled indices to pull the targets which is a super set of the train_targets, hence no exception was raised and it went under the radar.
If I define the weights for the full targets set and sample the indices from there as well everything works like it should be. Thank you for your time and help!
|
st99475
|
I was stuck trying to load a checkpoint trained using DataParallel and a bunch of things seem to have worked so far for me. It took several iterations to fix, and I had to find the following after many attempts of searching. I feel there’s still some things I’m doing wrong, and am hoping this thread would help.
DataParallel Training from start
I found that the usage(gpu0) = gpu1 + gpu2 + gpu3 + gpu0, which was due to computing loss outside. The following confused me, since it said loss can be outside.
Is the loss function paralleled when using DataParallel?
When using DataParallel to wrap my module, do I need to do anything to also parallelize the loss functions?
For example, let’s say that I have large batch size and large output tensors to compute MSE against a target. This operation would benefit from splitting the batch across multiple GPUs, but I’m not sure if the following code does that:
model = MyModule()
model = nn.parallel.DataParallel(model, device_ids=range(args.number_gpus))
model.cuda()
output = model(data)
criterion = nn.MSELoss()…
The methods in the below thread meanwhile worked, once I put model + loss inside DataParallel, it balanced GPU memory to some extent.
DataParallel imbalanced memory usage
Hi there,
I’m going to re-edit the whole thread to introduce a unlikely behavior with DataParallel
Right now there are several recent posts about this topic and I would like to summarize the problem.
Right now it seems there is an imbalaced usage of GPUs when calling DataParallel.
[image]
From my experience and other users’ explanations I will explain why this happens:
Using DataParallel there are 4 types of data to consider:
Input
Output
Groun…
DataParallel Training from checkpoint
Everytime I tried to load it directly, I was getting out of memory error without even reaching the peak batch size I could achieve from the above setting. Eventually, loading weights to CPU first and then load_state_dict on the model from that worked to balance the memory imbalance across GPUs. I believe the following thread partially helped me out:
GPU memory usage increases by ~90% after torch.load
Yes, I have experienced the same situation before. This is quiet annoying ! I will bump on OOM if I would like to resume training from a checkpoint.
Current Status
There is still an imbalance. I’m using 3 1080 Tis (1-3) with 11GB max memory. Attempts to increase further gives me OOM, while clearly [2] and [3] has free space.
The following is the main training routine, at this point:
def checkpoint(model, opt, checkpoint_path):
_payload = {
"model": model.module.state_dict(),
"opt": opt.state_dict()
}
with open(checkpoint_path, "wb+") as fp:
torch.save(_payload, fp)
def load(model, opt, checkpoint_path):
_payload = torch.load(checkpoint_path, map_location=torch.device("cpu"))
model.module.load_state_dict(_payload["model"])
opt.load_state_dict(_payload["opt"])
args = Args()
model = MaskedMLE.build_model(args, task)
reduce = True
max_epochs = 80
criterion = nn.NLLLoss(ignore_index=dataset.vocab.pad())
model = LossGenerator(model, criterion)
checkpoint_path = "/scratch/jerin/best_checkpoint.pt"
model = model.to(device)
model = DataParallel(model)
opt = optim.Adam(model.parameters())
if os.path.exists(checkpoint_path):
load(model, opt, checkpoint_path)
for epoch in tqdm(range(max_epochs), total=max_epochs, desc='epoch'):
pbar = tqdm_progress_bar(loader, epoch=epoch)
meters["loss"].reset()
count = 0
for src, src_lens, tgt, tgt_lens in pbar:
count += 1
opt.zero_grad()
src, tgt = src.to(device), tgt.to(device)
loss = model(src, src_lens, tgt)
loss.sum().backward()
meters['loss'].update(loss.mean().item())
pbar.log(meters)
opt.step()
avg_loss = meters["loss"].avg
meters['epoch'].update(avg_loss)
checkpoint(model, opt, checkpoint_path)
What are further improvements I could do? Could someone explain the internals of these things (loading, checkpoint) and best practices?
|
st99476
|
If I understand the source code of DataParallel correctly, you could try commenting this line model = model.to(device). Also, try specifying the output_device for DataParallel to see if it works.
|
st99477
|
I tried a bunch of the combos.
Commenting out model = model.to(device) gets me Broadcast not implemented for CPUTensors...
Looking at the source now, if all outputs have to be gathered at one device, wouldn’t that increase the usage on device_ids[0] anyway? Is there anyway to circumvent this?
|
st99478
|
Your main problem is you are using Adam. Adam parameters take memory from the main gpu to store its parameters. As far as I know there is nothing you can do. The bigger your model is, the worse this problem will be.
You can try to ask some developer if there is a way of spliting the memory usage of adam among all the gpus but, as you could see in the thread i opened, I got no answer.
|
st99479
|
Can you link the thread corresponding to adam here? Or is it the one I mentioned above?
|
st99480
|
Dear all,
I’m trying to implement the Neural-expectation maximisation architecture in pytorch.
Unfortunately, such a model requires a VanillaRNN without any activation function (or a sigmoid activation function). Currently, the pytorch._backend library seems to support only RNNs with tanh or ReLU activations. However, the RNNBase module is not documented but appears to support different execution modes. I’m not sure if such modes are just LSTM, GRU, RNN_tanh and RNN_ReLU.
Does anyone know if calling the RNNBase module with an empty mode works and in case what should I expect as output?
If I have to implement a simple RNN without activation in python-native, does anyone know how slow would it be w.r.t. the C implementation?
Cheers,
Sandro
|
st99481
|
By the time you remove the activation function, isn’t the RNN cell just a linear model (with input torch.cat([inp_t, h_t_minus_1], -1) and output h_t) applied at each timestep?
I would expect the speed penalty to be small. For a much more complex model, LLTM, the C++ tutorial shows a speedup (reduction in running time) of 30% for Python+Autograd vs. implementing a forward + custom backward in C++, and my analysis seems split this into ~10%pts “move to C++” and ~20%pts “custom backward”. But again, this is for a much more complex model, I would expect the benefits in your case to be considerably more marginal.
Best regards
Thomas
|
st99482
|
Thanks for the answer,
yes you are right, if you remove the activation_fn an RNN became almost a linear model.
I’m finishing the implementation, not sure how slow it would be. I hope it would be decent.
|
st99483
|
Hi guys, I’m starting to learn about LSTM recently and I don’t quite understand about hidden_size in torch.nn.LSTM. Can anyone help me to understand this?
|
st99484
|
I want to get the output of a layer which is a tensor of images, convert it to numpy arrays and apply a custom function on them, and return the output to the model. So it would be something like this:
def sum(args):
# convert args to numpy arrays
???
#calculating sum of all the elements
s=np.sum(args)
return s
This would be in the middle of the model, which means some other layers will be added to this functions output.
Thank you very much for your help.
|
st99485
|
Hi,
If you convert your tensors to numpy arrays, you won’t be able to backpropagate gradients through it. which means that anything before this part will not have gradients. Is that fine for you?
|
st99486
|
Hi, Thank you for your answer. I actually ran into the problem you mentioned. Do you know any way to pass this? In other words it is not fine with me:). Can I create a copy of the tensor and do my operations on it and then return it to the model?
Thanks
|
st99487
|
I guess args is tensor of the model output right?
As @albanD mentioned, if you convert args(tensor) into s(numpy ) then use s as loss, there occurs no gradient computation.
torch.Tensor supports numpy like operations. I suppose you would rather use tensor operations described here 17
|
st99488
|
Yes args is the model’s output tensor. unfortunately my operation is is not defined in the tensor operations, and is far more complex than those. Thank you for your reply.
|
st99489
|
In that case you would need to write your own backward function.
Have a look at the Extending PyTorch docs 166.
|
st99490
|
OK thanks, I was afraid that I have to do something like that LOL. Thank you for pointing the one that I should focus on.
|
st99491
|
I have a trainning data images set, when I create dataloader, if I read image one by one, it is too slow. I want to in advance read these images and then save them to H5 file or torch.save(). What difference between them?
|
st99492
|
Hello, i’m doing transfer learning on Resnet34 for kaggle Diabetic retinopathy challenge dataset. in this code snippets the size of the output image is 512*512
Here’s how i loaded the data:
data_transforms = {
'train': transforms.Compose([
transforms.RandomRotation((90, 180)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()
]),
'val': transforms.Compose([
transforms.ToTensor()
]),
'test': transforms.Compose([
transforms.ToTensor(),
])
}
data_dir = 'new_dataset/'
image_dataset = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val', 'test']}
dataloaders = {x: DataLoader(image_dataset[x],
batch_size=16,
shuffle=True,
num_workers=0)
for x in ['train', 'val', 'test']}
dataSizes = {x: len(image_dataset[x]) for x in ['train', 'val', 'test']}
class_names = image_dataset['train'].classes
and here is the Main function:
def weights_init(model):
if isinstance(model, nn.Conv2d):
torch.nn.init.kaiming_normal_(model.weight.data)
elif isinstance(model, nn.Linear):
torch.nn.init.kaiming_normal_(model.weight.data)
model.bias.data.normal_(mean=0,std=1e-2)
elif isinstance(model, nn.BatchNorm2d):
model.weight.data.uniform_()
model.bias.data.zero_()
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
model = models.resnet34(pretrained=True)
model.avgpool = nn.AvgPool2d(10,10)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 2)
model = model.to(device)
model = tourch.nn.DataParallel(model, device_ids=[0])
model.module.fc.apply(weights_init)
criterion = nn.CrossEntropyLoss()
lr = 0.01
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)
class_names = ['normal','upnormal']
true = []
pred = []
accuracy =0
num_epochs = 30
mymodel, train_losses, train_acc, val_losses, val_acc=train_model(model, criterion, optimizer, scheduler, num_epochs=num_epochs)
my problem is the training stopped at epoch 23 (the code did not raise an error but it was stuck for 8 hours in this epoch, this is not the duration of the epoch during training) and my GPU utilization was 0%.
This code was run on Windows. Can anyone tell me what was happening there or what’s the meaning of a stuck epoch like this or where did it come from?
|
st99493
|
I am trying to implement multi-label dice loss, but am getting the following exception:
File ".../training.py", line 167, in main
diceLoss_devtensor.backward()
File ".../.venv/lib/python3.6/site-packages/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File .../.venv/lib/python3.6/site-packages/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: CuDNN error: CUDNN_STATUS_NOT_SUPPORTED. This error may appear if you passed in a non-contiguous input.
Here’s my code:
prediction_devtensor = self.model(input_devtensor)
sum2 = lambda t: t.view(t.size(0), t.size(1), -1).sum(dim=2)
diceCorrect_devtensor = sum2(prediction_devtensor * label_devtensor)
dicePrediction_devtensor = sum2(prediction_devtensor)
diceLabel_devtensor = sum2(label_devtensor)
epsilon_devtensor = torch.ones_like(diceCorrect_devtensor) * 0.01
diceLoss_devtensor = 1 - (2 * diceCorrect_devtensor + epsilon_devtensor) / (dicePrediction_devtensor + diceLabel_devtensor + epsilon_devtensor)
# this gets .backward() called on it in the stack trace above
return diceLoss_devtensor.mean()
I made sure my Dataset called .contiguous() on the tensors it returned, but that didn’t change anything. The model is a fairly simple implementation of UNet for 3D data.
Any suggestions for how I can troubleshoot? I’ve sprinkled some assert t.is_contiguous() around the model, etc. but that hasn’t caught anything (though I wasn’t comprehensive).
|
st99494
|
Looks like I might have run into https://github.com/pytorch/pytorch/issues/4107 186 since reducing the size of the array makes the problem seem to go away.
|
st99495
|
I see that some of the tutorials are upgraded (or are new) and are marked internally with “preview.”
Are there any concise documents that simply list what the new features actually are, and what’s changed from 0.4 to 1.0? I understand that a fully detailed list of breaking changes (if any) would probably be deferred until after the release is no longer in preview, but a list of updates and new features seems appropriate.
|
st99496
|
Solved by justusschock in post #2
You could have a look at the Release Notes
|
st99497
|
This looks like exactly what I am looking for-- not sure why I didn’t see it when I looked for it.
Thank you.
|
st99498
|
Hi
my pytorch version is 0.3.1
When I try to use tenserA=tenserA.cuda(1), the code always uses 400Mb of gpu 0 's memory, how to slove this. As the rule of the server does not allow me to use gpu 0 ,i have to slove it.
|
st99499
|
HI,
How do you check memory usage? If you use nvidia-smi, you should know that by default, the numbering from nvidia smi is not the same as the one for other programs.
You can set export CUDA_DEVICE_ORDER=PCI_BUS_ID to make all applications use the same numbering as nvidia-smi.
Also to avoid using GPU you should not, you can use CUDA_VISIBlE_DEVICES=1 to prevent your application from seeing any other gpu that the number 1 (this ordering is the other programs one).
|
st99500
|
This is a crosspost from here 1
I am trying to implement Yolo-v2 in pytorch. However, I seem to be running out of memory just passing data through the network. The model is large and is shown below. However, I feel like I’m doing something stupid here with my network (like not freeing memory somewhere). The network works as expected on cpu.
The test code (where memory runs out) is:
x = torch.rand(32,3,416, 416).cuda()
model = Yolov2().cuda()
y = model(x.float())
Question
Anything that is obviously wrong with my model?
How do I make this more efficient with memory?
Other comments?
The model:
import torch
from torch import nn
import torch.nn.functional as F
class Yolov2(nn.Module):
def __init__(self):
super(Yolov2, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm3 = nn.BatchNorm2d(128)
self.conv4 = nn.Conv2d(in_channels=128, out_channels=64, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm4 = nn.BatchNorm2d(64)
self.conv5 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm5 = nn.BatchNorm2d(128)
self.conv6 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm6 = nn.BatchNorm2d(256)
self.conv7 = nn.Conv2d(in_channels=256, out_channels=128, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm7 = nn.BatchNorm2d(128)
self.conv8 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm8 = nn.BatchNorm2d(256)
self.conv9 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm9 = nn.BatchNorm2d(512)
self.conv10 = nn.Conv2d(in_channels=512, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm10 = nn.BatchNorm2d(256)
self.conv11 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm11 = nn.BatchNorm2d(512)
self.conv12 = nn.Conv2d(in_channels=512, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm12 = nn.BatchNorm2d(256)
self.conv13 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm13 = nn.BatchNorm2d(512)
self.conv14 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm14 = nn.BatchNorm2d(1024)
self.conv15 = nn.Conv2d(in_channels=1024, out_channels=512, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm15 = nn.BatchNorm2d(512)
self.conv16 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm16 = nn.BatchNorm2d(1024)
self.conv17 = nn.Conv2d(in_channels=1024, out_channels=512, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm17 = nn.BatchNorm2d(512)
self.conv18 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm18 = nn.BatchNorm2d(1024)
self.conv19 = nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm19 = nn.BatchNorm2d(1024)
self.conv20 = nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm20 = nn.BatchNorm2d(1024)
self.conv21 = nn.Conv2d(in_channels=3072, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm21 = nn.BatchNorm2d(1024)
self.conv22 = nn.Conv2d(in_channels=1024, out_channels=125, kernel_size=1, stride=1, padding=0)
def reorg_layer(self, x):
stride = 2
batch_size, channels, height, width = x.size()
new_ht = int(height/stride)
new_wd = int(width/stride)
new_channels = channels * stride * stride
# from IPython.core.debugger import Tracer; Tracer()()
passthrough = x.permute(0, 2, 3, 1)
passthrough = passthrough.contiguous().view(-1, new_ht, stride, new_wd, stride, channels)
passthrough = passthrough.permute(0, 1, 3, 2, 4, 5)
passthrough = passthrough.contiguous().view(-1, new_ht, new_wd, new_channels)
passthrough = passthrough.permute(0, 3, 1, 2)
return passthrough
def forward(self, x):
out = F.max_pool2d(F.leaky_relu(self.batchnorm1(self.conv1(x)), negative_slope=0.1), 2, stride=2)
out = F.max_pool2d(F.leaky_relu(self.batchnorm2(self.conv2(out)), negative_slope=0.1), 2, stride=2)
out = F.leaky_relu(self.batchnorm3(self.conv3(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm4(self.conv4(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm5(self.conv5(out)), negative_slope=0.1)
out = F.max_pool2d(out, 2, stride=2)
out = F.leaky_relu(self.batchnorm6(self.conv6(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm7(self.conv7(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm8(self.conv8(out)), negative_slope=0.1)
out = F.max_pool2d(out, 2, stride=2)
out = F.leaky_relu(self.batchnorm9(self.conv9(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm10(self.conv10(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm11(self.conv11(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm12(self.conv12(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm13(self.conv13(out)), negative_slope=0.1)
# from IPython.core.debugger import Tracer; Tracer()()
passthrough = self.reorg_layer(out)
out = F.max_pool2d(out, 2, stride=2)
out = F.leaky_relu(self.batchnorm14(self.conv14(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm15(self.conv15(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm16(self.conv16(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm17(self.conv17(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm18(self.conv18(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm19(self.conv19(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm20(self.conv20(out)), negative_slope=0.1)
out = torch.cat([passthrough, out], 1)
out = F.leaky_relu(self.batchnorm21(self.conv21(out)), negative_slope=0.1)
out = self.conv22(out)
return out
Additional Info:
Torch version is '0.4.1.post2'
Running on aws p2.xlarge (limit 12gb GPU memory).
The number of parameters for this model is 67137565. Which would occupy <500MB.
this thread from pytorch might be related.
|
st99501
|
Hi,
What is the size of the input you give to your conv14? It looks like it has many channels.
Also remember that during a forward pass, not only the net needs to be on the GPU but many intermediary results needed to compute the gradients need to be kept around,
How much memory does the net uses on CPU?
|
st99502
|
I want to convert the pytorch code to keras, adaptive_avg_pool2d(x,[14, 14]), for this method, don’t know how to convert it to tensorflow or keras. Anyone can help? Thanks in advance.
|
st99503
|
Hi, I am having an issue with using fft. I installed pytorch using pip3 install torch torchvision on Mac OSX 10.11.6 with Python 3.6. I could not find much about this error online so I apologize if it’s something simple and appreciate any pointers.
Here is a minimal example:
import torch
x = torch.randn(4, 3, 2)
torch.fft(x, 2)
leads to the error
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-11-ca08a48f699a> in <module>()
5
6 x = torch.randn(4, 3, 2)
----> 7 torch.fft(x, 2)
RuntimeError: fft: ATen not compiled with MKL support
|
st99504
|
Hi,
The problem is that the pip package does not ship MKL with it and MKL is required at the moment for fft support on cpu. If you use gpu tensors, that should work.
If you do need it on cpu, you can either install using conda as the conda package ships with MKL. Otherwise, you will have to install MKL on your machine and then compile from source.
|
st99505
|
Thanks! I had tried installing MKL but missed the step about compiling from source.
|
st99506
|
Hi,
When I try to train a pre-trained (on Imagenet) Resnet152 model, I get the following error:
RuntimeError: cuda runtime error (2) : out of memory at /b/wheel/pytorch-src/torch/lib/THC/generic/THCStorage.cu:66
I am using a K80 on an AWS EC2 p2.xlarge instance, so I am confused, since there is 12gb of VRAM available.
Any thoughts on why this is ocurrring?
Thanks
|
st99507
|
@smth
So, it threw this error at the end of training the first epoch, when it was just about to begin testing for accuracy.
The batch_size was 20 for both the trainloader and testloader, so I am confused, since it is already fairly low. Should I reduce it further to, say, 10?
Thanks
Settings:
trainloader_aug = data_utils.DataLoader(train_dataset, batch_size=20, shuffle=True)
testloader = data_utils.DataLoader(test_dataset, batch_size=20, shuffle=True)
|
st99508
|
Yep, that solved it, the batch_size was too large apparently. Thanks for your help!
|
st99509
|
Hi, what the batch_size do you set? I am using p2.xlarge and resnet152, but it keeps saying “runtime error” even I have set it to 10.
|
st99510
|
I am doing two-class classification with resnet34 and suddenly the same error of “out of memory at /pytorch/torch/lib/THC/generic/THCStorage.cu:58” is occuring. previously code was running with any batch size. I reduced the batch size to 2 but the error remains. Anyone knows how to rectify this error?
Thanks!
|
st99511
|
Using the torchvision resnet 50 model i have noticed printing out the model using the simple
print(model)
prints out:
ResNet(
(conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace)
(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)
(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)
)
)
You can see there are no RelU layers in between the layers of bottleneck. whereas if you at the code for forward pass of bottleneck module
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
You can see there are reLU layers in between the Conv2d the layers. Why are these ReLU layers not showing up in the model structure, only the last ReLU layer is printed out.
|
st99512
|
Solved by Florian_1990 in post #2
If you look closely at the forward function, there is only one ReLU layer (self.relu). But it is used three times. This can be done, because ReLU layers do not learn any parameters as opposed to convolution or batch normalization layers.
To answer your question: Using print only prints the module i…
|
st99513
|
If you look closely at the forward function, there is only one ReLU layer (self.relu). But it is used three times. This can be done, because ReLU layers do not learn any parameters as opposed to convolution or batch normalization layers.
To answer your question: Using print only prints the module in question and all of its submodules (which will print their submodules etc.). It does not print the “structure” or the forward function. And the modules might even be printed in another order as they are used in the forward pass (depending on the order of definition in the module constructor).
|
st99514
|
There is no builtin solution for that. If you think about it, it is a hard question: How would you print skip connections? Or how would you handle simple operations or function calls within the forward function (e. g. +, torch.cat, or torch.mean)? What about recurrent networks?
|
st99515
|
This could help to visualize:
GitHub
szagoruyko/pytorchviz 16
A small package to create visualizations of PyTorch execution graphs - szagoruyko/pytorchviz
|
st99516
|
Hi all,
I have a basic Pytorch question!
If I create three objects of one torch.nn.Module class, do they share the same parameters i.e. those parameters influence each other or I’ll have three distinct sets of totally separated parameters?
For example, let’s say my class is an autoencoder, I’ll create three objects of it, feed different inputs to these objects and train those three autoencoder objects with their own optimizers. Is there any connection between parameters of these three objects?
Thanks!
|
st99517
|
hosseinshn:
If I create three objects of one torch.nn.Module class, do they share the same parameters i.e. those parameters influence each other or I’ll have three distinct sets of totally separated parameters?
They do not share the same parameters. For example, consider nn.Linear(). Each time when we create an object, they have their own weights.
hosseinshn:
For example, let’s say my class is an autoencoder, I’ll create three objects of it, feed different inputs to these objects and train those three autoencoder objects with their own optimizers. Is there any connection between parameters of these three objects?
There would not be any connection unless you share some modules. ( for example, by passing through constructor)
|
st99518
|
Recently I’ve been trying to wrap my cuda kernel with pytorch c-extension. Many examples I can search online is to use THCudaTensor* in a c wrapper function, but it seems to me that the tensor is float. My cuda-kernel takes uint8 in and output int16. Should I still use THCudaTensor* as interface and cast them to uint8/int16 internally?
Also, if in the wrapper function I want to call the cuda kernel many times, each time the kernel produce some intermediate tensors as output. Should I pass the temporary output from outside or can I define the temporary within?
My cuda kernel:
__global__ my_cuda_kernel (uint8* input1, uint8* input2, int16* output)
{
// do something
}
__global__ my_cuda_kernel_2 (uint8* input1, uint8* input2, int16* input3, int16* output)
{
// do something
}
void c_wrapper(THCState* state, THCudaTensor* input1, THCudaTensor* input2, THCudaTensor* Output)
{
uint8* input1_ = THCudaTensor_data(state, input1); // how to cast?
uint8* input2_ = THCudaTensor_data(state, input2);
int16* output_ = THCudaTensor_data(state, output); // how to cast?
int16* temporary_out = xxxx; // how can I allocate memory from within?
my_cuda_kernel<<<32, 32, 0, THCState_getCurrentStream(state)>>>(input1, input2, temporary_out);
my_cuda_kernel_2<<<32, 32, 0, THCState_getCurrentStream(state)>>>(input1, input2, temporary_out, output);
}
|
st99519
|
InnovArul:
ere any issue with that?
My kernel is a complicated image processing algorithm, so it takes in rgb values as uint8 naturally. Sure I can change them to float, but it takes more space and I guess gpu would be slower in handling float.
|
st99520
|
I have not used integer tensor (THCudaIntTensor*) so far.
But I could see, it has been used in torch layers.
github.com
torch/cunn/blob/master/lib/THCUNN/generic/SparseLinear.cu#L20
static bool checkSize2D(THCTensor* t, long size0, long size1)
{
return t->nDimension == 2 && t->size[0] == size0 && t->size[1] == size1;
}
static bool checkSize1D(THCTensor* t, long size0)
{
return t->nDimension == 1 && t->size[0] == size0;
}
static inline void copyCudaFloatingType(THCState *state, THCudaIntTensor *buf, THCTensor *t) {
#ifdef THC_REAL_IS_FLOAT
THCudaIntTensor_copyCudaFloat(state, buf, t);
#elif defined(THC_REAL_IS_DOUBLE)
THCudaIntTensor_copyCudaDouble(state, buf, t);
#elif defined(THC_REAL_IS_HALF)
THCudaIntTensor_copyCudaHalf(state, buf, t);
#endif
}
void THNN_(SparseLinear_updateOutput)(
|
st99521
|
Hello,
I’m a n00b trying to make a simple neural network for the MNIST dataset. My goal is to make this net have a variable number of layers and activation functions chosen by the user.
I have pytorch 0.4.1 with no cuda on my laptop
So first I set off to define my own module, which had an empty parameter list and I read on stack overflow that I could just overwrite the parameters method by adding all the parameters of each Linear layer to one list. I also made a one-hot encoding function.
import torch
def encoding_function(num_categories):
“”“one hot encoder, given the number of categories returns a one-hot
encoder function the eats tensors of size (N,1) (where N is batch size
and each row corresonds to one numerical value) and spits out a
tensors of size (N,num_categories) where each row corresponds to
the one hot encoding associated to the numerical value”""
def encoder(vals):
"""vals of size (N,1), each row is a one value in
[0,num_categories-1]"""
batch_size = vals.size(0)
encoded_vals = torch.zeros((batch_size, num_categories))
for i in range(batch_size):
val = vals[i].item()
encoded_vals[i][val] = 1
return encoded_vals
return encoder
class NNet(torch.nn.Module):
def __init__(self, layer_shapes, activation_functions):
super(NNet, self).__init__()
assert len(layer_shapes) == len(activation_functions) + 1
self.layer_shapes = layer_shapes
self.activation_functions = activation_functions
linear_functions = list()
for i in range(len(self.layer_shapes)-1):
linear_functions.append(torch.nn.Linear(
self.layer_shapes[i], self.layer_shapes[i+1]))
self.linear_functions = linear_functions
def parameters(self):
parameters = list()
for function in self.linear_functions:
parameters = parameters+list(function.parameters())
return parameters
def forward(self, x):
y = x
for i in range(len(self.layer_shapes)-1):
assert y.shape[1] == self.layer_shapes[i]
y = self.activation_functions[i](self.linear_functions[i](y))
return y
data:
import matplotlib.pyplot as plt
import torch
import torchvision
import ai.neural_network as nnet
batch_size = 30
epochs = 500
learning_rate = 0.001
train_set = torchvision.datasets.MNIST(root = ‘/home/carson/Desktop/Archive/Computing/Projects/Python/Data’,
train=True,
transform=torchvision.transforms.ToTensor(),
download=True)
test_set = torchvision.datasets.MNIST(root = ‘/home/carson/Desktop/Archive/Computing/Projects/Python/Data’,
train=False,
transform=torchvision.transforms.ToTensor(),
download=True)
train_loader = torch.utils.data.DataLoader(dataset=train_set, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_set, batch_size=batch_size, shuffle=False)
model = nnet.NNet([784, 16, 10], [torch.nn.Tanh(), torch.nn.Softmax(dim=1)])
loss_function = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
training:
loss_items = list()
for t in range(epochs):
for i, (images, labels) in enumerate(train_loader):
encoder = nnet.encoding_function(10)
labels = encoder(labels)
images = images.reshape(-1,28*28)
outputs = model(images)
loss = loss_function(outputs, labels)
if i%1000 == 0:
loss_items.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
plot it:
plt.figure(figsize=(15,5))
plt.plot(loss_items)
test it:
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, 28*28)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
results:
So it came up 90% accurate for me which I felt was good enough for this network.
I wanted to save it, but it says
model.state_dict() => OrderedDict()
is empty
I haven’t found anything about this yet, so I was sondering if anybody knew off the back how I could fix this. I do have the parameters in a list, so there is that. Not sure if I can manually set those with any fresh network.
Also, I’m new to pytorch, like started two days ago. So if there is any recommendation for doing something in a better way, please let me know
|
st99522
|
Solved by InnovArul in post #2
Go through this post:
|
st99523
|
Go through this post:
The difference in usage between nn.ModuleList and python list
I can’t figure out what the purpose of nn.ModuleList is because as far as I know, list can be used in most scenarios I come up with.
For example, for the newtork structure below,
def __init__(self):
super(MyNN, self).__init__()
fcs = [nn.Sequential(
nn.Linear(fc_input_size, fc_hidden_size),
nn.ReLU(),
nn.Linear(fc_hidden_size,num_classes)
) for fc_hidden_size in fc_hidden_sizes]
#self.network = nn.ModuleList(fcs)
self.network = fcs
I don’t see the difference between …
|
st99524
|
model(input_data) or model.forward(input_data) is used to get the logits for all the classes.
My ‘model’ is a CNN and has final fc layer with out_features=200. ‘input_data’ is a tensor of size ([1, 160, 3, 224, 224]).
logits = model(input_data) should produce the logits for 200 classes, but ‘logits’ is of size ([10, 1]).
I don’t see where the number 10 is being set - I don’t use it anywhere in my code.
Any help fixing this would be greatly appreciated.
Thank you,
|
st99525
|
Solved by Sophia_Wright in post #2
I solved it, the problem was with how the output probabilities were being averaged.
|
st99526
|
I solved it, the problem was with how the output probabilities were being averaged.
|
st99527
|
I have been troubled by the missing of parameters after I did concatenation. I have read a similar post Model.named_parameters() will lose some layer modules 4, but the cause of my problem is different.
The Pytorch version is 0.3.1.post2.
The concatenation is as follows:
x = Variable(torch.cat((x.data, max_val), 1))
If I comment it out, the make_dot from torchviz shows all the parameters of the neural network. But if I execute the above line, most of the parameters are cut off and only the parameters of the last layer are shown in the diagram. Even if I make max_val a zero tensor (of the same size), the same cut off happens. The cut off caused a severe degradation in performance (prediction accuracy, the code not shown here) when applying the optimizer. Any hint? The code is below. Thanks.
%reload_ext autoreload
%autoreload 2
import os, re, math, copy, datetime, sys, traceback
import numpy as np
import scipy.signal as signal
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.optim import lr_scheduler
import GPUtil
import pdb
gpu_avail = GPUtil.getAvailable()
if gpu_avail == []:
print ('There are no free GPUs; using CPU.')
use_gpu = False
else:
use_gpu = True
num_samples = 2000
numCats = 10
batch_size = 256
class BnLayer2(nn.Module):
def __init__(self, ni, nf, stride=2, kernel_size=(3,3)):
super().__init__()
self.conv1 = nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride,
bias=False, padding=(1,1))
self.bn1 = nn.BatchNorm2d(nf)
self.conv2 = nn.Conv2d(nf, nf, kernel_size=kernel_size, stride=stride,
bias=False, padding=(1,1))
self.bn2 = nn.BatchNorm2d(nf)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
return x
class SimpleNet(nn.Module):
def __init__(self, layers, c, input_shape, p=0.2):
super().__init__()
self.input_shape = input_shape
self.conv1 = nn.Conv2d(1, layers[0], kernel_size=(3,3), stride=1, padding=(1,1))
self.layers = BnLayer2(layers[0], layers[1])
#self.out = nn.Linear(layers[-1] + 1, c) # with concatenation
self.out = nn.Linear(layers[-1], c) # without concatenation
self.drop = nn.Dropout(p)
def do_sth(self, x):
max_x = torch.max(x, 1)
return max_x
def forward(self, x):
x_init = x
x = x.view(-1,*self.input_shape)
x = F.relu(self.conv1(x))
x = self.layers(x)
x = F.adaptive_max_pool2d(x, 1)
max_x = self.do_sth(x)
max_val = torch.FloatTensor(max_x[0].data)
max_val = max_val[:, None, :, :] * 0
x = Variable(torch.cat((x.data, max_val), 1)) # concatenation causes parameters cut off
x = x.view(x.size(0), -1)
x = self.drop(x)
return F.log_softmax(self.out(x), dim=-1)
model = SimpleNet([10,13], numCats, (1,2,num_samples), p=0.20) # p = dropout
from graphviz import Digraph
from torchviz import make_dot
x=Variable(torch.randn(batch_size,1,2,num_samples))
y=model(x)
dot = make_dot(y.mean(),params=dict(model.named_parameters()))
dot.attr(size="140,140")
dot
The neural network without concatenation:
without_cat.png1367×1706 136 KB
The neural network with concatenation (only the final layer is kept):
with_cat.png947×733 34.3 KB
|
st99528
|
Hi,
First, you should upgrade your version of pytorch
Second, .data should not be used anymore and should never be used in a network’s forward pass if you want gradients.
What it does (in a very unsafe way) is loose track of the history of a tensor. In you case, the new x is not linked to the original one. And so whatever you do with the new x won’t compute gradients for the old one.
You should remove the .data (and in other places in your code as well!).
|
st99529
|
Thanks albanD! I upgraded pytorch to 0.4.1.post2. However, my Jupyter notebook still uses the old version 0.3.1.post2. Below are the details.
1. I cloned a new virtual environment where I used conda to do the pytorch upgrade:
conda install pytorch=0.4.1 -c pytorch
2. Discrepancy between the version testing results in the new virtual environment
I activated the new virtual environment, and running the following command line
python -c "import torch; print(torch.__version__)"
gave output: 0.4.1.post2
But in Jupyter notebook:
import torch
print(torch.__version__)
giving output: 0.3.1.post2
Did I miss anything? Thanks.
Note: A new topic was started on this particular version problem: Upgrading pytorch does not change which version Jupyter notebook uses
|
st99530
|
Just found a solution …
Inside the web browser that shows the Jupyter window,
select Kernel from the top menu
select Change Kernel
select the new kernel, in my case Python [conda env: new_env_name]
Continuing … to get the right graph, besides removing “Variable”, I also need to change the input argument of make_dot() …
The modified code is:
%reload_ext autoreload
%autoreload 2
import os, re, math, copy, datetime, sys, traceback
import numpy as np
import scipy.signal as signal
import torch
#from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.optim import lr_scheduler
import GPUtil
import pdb
gpu_avail = GPUtil.getAvailable()
if gpu_avail == []:
print ('There are no free GPUs; using CPU.')
use_gpu = False
else:
use_gpu = True
num_samples = 2000
numCats = 10
batch_size = 256
class BnLayer2(nn.Module):
def __init__(self, ni, nf, stride=2, kernel_size=(3,3)):
super().__init__()
self.conv1 = nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride,
bias=False, padding=(1,1))
self.bn1 = nn.BatchNorm2d(nf)
self.conv2 = nn.Conv2d(nf, nf, kernel_size=kernel_size, stride=stride,
bias=False, padding=(1,1))
self.bn2 = nn.BatchNorm2d(nf)
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
return x
class SimpleNet(nn.Module):
def __init__(self, layers, c, input_shape, p=0.2):
super().__init__()
self.input_shape = input_shape
self.conv1 = nn.Conv2d(1, layers[0], kernel_size=(3,3), stride=1, padding=(1,1))
self.layers = BnLayer2(layers[0], layers[1])
self.out = nn.Linear(layers[-1] + 1, c) # with concatenation
#self.out = nn.Linear(layers[-1], c) # without concatenation
self.drop = nn.Dropout(p)
def do_sth(self, x):
max_x = torch.max(x, 1)
return max_x
def forward(self, x):
x_init = x
x = x.view(-1,*self.input_shape)
x = F.relu(self.conv1(x))
x = self.layers(x)
x = F.adaptive_max_pool2d(x, 1)
max_x = self.do_sth(x)
max_val = torch.FloatTensor(max_x[0].data)
max_val = max_val[:, None, :, :] * 0
#x = Variable(torch.cat((x.data, max_val), 1)) # concatenation causes parameters cut off
x = torch.cat((x.data, max_val), 1)
x = x.view(x.size(0), -1)
x = self.drop(x)
return F.log_softmax(self.out(x), dim=-1)
model = SimpleNet([10,13], numCats, (1,2,num_samples), p=0.20) # p = dropout
from graphviz import Digraph
from torchviz import make_dot
#x=Variable(torch.randn(batch_size,1,2,num_samples))
x=torch.randn(batch_size,1,2,num_samples, requires_grad=True)
y=model(x)
#dot = make_dot(y.mean(),params=dict(model.named_parameters())) # this causes KeyError with pytorch 0.3.1
dot = make_dot(y)
dot.attr(size="140,140")
dot
The correct graph is:
correct_neural_net_with_pytorch_0_4_1.png865×1543 48.1 KB
Cheers!
|
st99531
|
My pytorch was 0.3.1.post2, and it caused some problems to concatenation. I was advised to upgrade it. See Model parameters were cut off after concatenation 1
I upgraded it to a newer version 0.4.1.post2. Python command showed the upgrade was successful. However, my Jupyter notebook still used the old version 0.3.1.post2. Below are the details.
1. I cloned a new virtual environment where I used conda to do the pytorch upgrade:
conda install pytorch=0.4.1 -c pytorch
2. Discrepancy between the version testing results in the new virtual environment
I activated the new virtual environment, and running the following command line
python -c "import torch; print(torch.__version__)"
gave output: 0.4.1.post2
But in Jupyter notebook:
import torch
print(torch.__version__)
giving output: 0.3.1.post2
In case there was some stale configuration for Jupyter, I updated Jupyter by “conda update jupyter”. But that did not help.
Did I miss anything? Thanks.
|
st99532
|
Just found a solution …
Inside the web browser that shows the Jupyter window,
select Kernel from the top menu
select Change Kernel
select the new kernel, in my case Python [conda env: new_env_name]
Cheers!
|
st99533
|
I haven’t found any list of recommendations on the docs or discussion about the best order to operating on tensors before feeding them to the network.
I ask because I got my DataSet and DataLoader (with a padding function call) working well yesterday. However, I was shocked at how long it takes to build up a batch.
DataSet
Opening each HDF5 file, extracting the multiple input and one output numpy arrays and converting to tensors, takes about 0.3sec per sample (file are average 25MB). I only have 48GB of ram, so I can’t take on too many workers if the batch size is decent. However, the workers are barely taxing the SSD.
Operations include:
loading each of the 7 ndarrays, transposing, and converting to tensors of the correct type. (not setting contiguous or pinning here)
storing each tensor inside a dict, which is returned
DataLoader
Collate_fn operations (which take about 0.05-0.2 sec per sample):
Taking the list of dicts, getting the maximum dimension used to pad those samples
enumerating over the batch to build up a list for each tensor “type” (input_num, output, weights, etc), while simultaneously padding each tensor before it is added to the list
stacking each list
Finally, I have the DataLoader with pin_memory=True, and I copy the tensors to the GPU inside the training batch enumerator.
None of these times seem really large, but when you’re talking batch sizes of 100 samples it works out to almost 40 seconds. Does anything jump out as room for improvement, as other than the transpose, padding, and stacking, I’m doing no other operations on the data itself.
|
st99534
|
Hi,
I checked https://pytorch.org/docs/master/nn.html?highlight=layernorm#torch.nn.LayerNorm 645 but it’s not very clear if normalized_input should be something like (x - E[x])/(V[X] + e) or normalized by dividing the last dimension by the euclidian norm or if we just have to give a tensor x without any normalization operation.
What is expected ?
Thank you !
|
st99535
|
After using pyinstaller to package the py file which is consist of PyTorch into an exe file. Double-click exe,it can’t run, and there is failed to execute script. Have you met this situation? How to solve it?
|
st99536
|
I have been trying to install the latest PyTorch from source on Win10, and have yet make it work. At least a couple things are going wrong:
It cannot find MKL or BLAS, which I know is included in Anaconda: I can find the libraries manually. I’m afraid I’m not familiar with CMake, and so I’m not quite sure how to add them. I tried setting MKL_INCLUDE and MKL_LIBRARY to no avail.
Caffe2 fails to compile because it cannot find a header file for ATen. Here’s the tail of the log:
Build FAILED.
"C:\Users\macolli\Source\pytorch\build\INSTALL.vcxproj" (default target) (1) ->
"C:\Users\macolli\Source\pytorch\build\ALL_BUILD.vcxproj" (default target) (3) ->
"C:\Users\macolli\Source\pytorch\build\caffe2\AlgorithmsTest.vcxproj" (default target) (4) ->
"C:\Users\macolli\Source\pytorch\build\c10\c10.vcxproj" (default target) (5) ->
(ClCompile target) ->
c:\users\macolli\source\pytorch\c10\c10_dummy.cpp(4): warning C4273: 'c10::HasC10': inconsistent dll linkage [C:\Users\macolli\Source\pytorch\build\c10\c10.vcxproj]
"C:\Users\macolli\Source\pytorch\build\INSTALL.vcxproj" (default target) (1) ->
"C:\Users\macolli\Source\pytorch\build\ALL_BUILD.vcxproj" (default target) (3) ->
"C:\Users\macolli\Source\pytorch\build\caffe2\AlgorithmsTest.vcxproj" (default target) (4) ->
"C:\Users\macolli\Source\pytorch\build\caffe2\caffe2.vcxproj" (default target) (6) ->
"C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj" (default target) (17) ->
(ClCompile target) ->
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\DeviceId.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\DispatchKey.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\layoutid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/IdWrapper.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\LayoutId.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\KernelRegistration.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\OpSchema.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\Dispatcher.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\DispatchTable.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
c:\users\macolli\source\pytorch\caffe2\core\dispatch\deviceid.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\core\dispatch\OpSchemaRegistration.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\core\dispatch\dispatch.vcxproj]
"C:\Users\macolli\Source\pytorch\build\INSTALL.vcxproj" (default target) (1) ->
"C:\Users\macolli\Source\pytorch\build\ALL_BUILD.vcxproj" (default target) (3) ->
"C:\Users\macolli\Source\pytorch\build\caffe2\utils\c10_utils_cpu.vcxproj" (default target) (40) ->
c:\users\macolli\source\pytorch\caffe2\utils\array.h(41): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\utils\Array.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\utils\c10_utils_cpu.vcxproj]
c:\users\macolli\source\pytorch\caffe2\utils\typelist.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\utils\TypeList.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\utils\c10_utils_cpu.vcxproj]
c:\users\macolli\source\pytorch\caffe2\utils\typetraits.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\utils\TypeTraits.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\utils\c10_utils_cpu.vcxproj]
c:\users\macolli\source\pytorch\caffe2\utils\typelist.h(3): fatal error C1083: Cannot open include file: 'ATen/core/C++17.h': No such file or directory (compiling source file C:\Users\macolli\Source\pytorch\caffe2\utils\Metaprogramming.cpp) [C:\Users\macolli\Source\pytorch\build\caffe2\utils\c10_utils_cpu.vcxproj]
1 Warning(s)
12 Error(s)
Time Elapsed 00:05:52.82
This file exists in pytorch/aten/src/ATen/core, but nowhere else.
Thanks,
Marcus
|
st99537
|
The MKL included in Anaconda is the dynamic version. However, we use the static version during build. And here’s how we enable MKL in CI.
REM Make sure you have 7z and curl installed.
REM Download MKL files
curl https://s3.amazonaws.com/ossci-windows/mkl_2018.2.185.7z -k -O
7z x -aoa mkl_2018.2.185.7z -omkl
REM Setting essential environment variables
set "CMAKE_INCLUDE_PATH=%cd%\\mkl\\include"
set "LIB=%cd%\\mkl\\lib;%LIB%"
Maybe an include dir is missing in the command. Could you please show me the full log?
|
st99538
|
Thanks Peter! It’s picking up MKL now, so that’s progress. Trying to figure out how/where to post the install logs…
|
st99539
|
@peterjc123 here are the logs: https://gist.github.com/mdc713/679d525e9b2ecdcd1168f2aab675edc8 2
I couldn’t add a second file without crashing my browser, so the (small) contents of stderr are just in a comment at the bottom. Thank you!
|
st99540
|
It’s weird since I saw /IC:\Users\macolli\Source\pytorch\aten\src in the command line. Is your clone complete?
|
st99541
|
It’s totally weird. I verified that the file it is looking for (pytorch/aten/src/ATen/core/C++17.h) is there, and I can open it.
|
st99542
|
How to implement dropout if I’m using LSTMCell instead of LSTM?
Let’s stick to the sine-wave example because my architecture is similar:
github.com
pytorch/examples/blob/master/time_sequence_prediction/train.py 26
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Sequence(nn.Module):
def __init__(self):
super(Sequence, self).__init__()
self.lstm1 = nn.LSTMCell(1, 51)
self.lstm2 = nn.LSTMCell(51, 51)
self.linear = nn.Linear(51, 1)
def forward(self, input, future = 0):
outputs = []
h_t = torch.zeros(input.size(0), 51, dtype=torch.double)
c_t = torch.zeros(input.size(0), 51, dtype=torch.double)
This file has been truncated. show original
If I try to update weights by accessing them directly
self.lstmCell_1 = nn.LSTMCell(self.input_features, self.hidden_features)
self.dropout = nn.Dropout(p=0.1, inplace=True)
...
self.dropout(self.self.lstmCell_1.weights_ih)
it results in an error.
I don’t want to implement my own LSTMCell, neither do I want to use LSTM, because I need predictions to be made further in time, not just the single next value, therefore I need to control the flow of data between LSTMCell units like in the sine-wave example.
Any ideas?
|
st99543
|
Or maybe it is possible to realize the same sine-wave predictor with just LSTM without going into data flow control of LSTMCell?
|
st99544
|
I want to use create multiple-hot vector.
I tried to use scatter_ function of Tensor.
It works fine for the fixed length of indices.
batch_size = 4
dim = 7
idx = torch.LongTensor([[0,1],[2,3],[0,4],[0,5]])
hot_vec = hot_v = torch.zeros(batch_size, dim)
hot_vec.scatter_(1, idx, 1.0)
result
1 1 0 0 0 0 0
0 0 1 1 0 0 0
1 0 0 0 1 0 0
1 0 0 0 0 1 0
But my data does not have the same number of index
for
idx_v = torch.LongTensor( [[0], [2,3], [0,1,4], [0,5]] )
I want the hot vector like the below.
1 0 0 0 0 0 0
0 0 1 1 0 0 0
1 1 0 0 1 0 0
1 0 0 0 0 1 0
What can I use to make the vector ?
|
st99545
|
Not really an nice solution, but if you fill the longtensor data that is shorter than the max index length with repeats, it will work because it will make them the same size. Example from yours modified:
idx = torch.LongTensor( [[0,0,0], [2,2,3], [0,1,4], [0,0,5]])
It will work, but is pretty hacky. I’m sure you could write something to fill the short indices with repeats until it reaches the same length as the longest index array. Maybe someone who knows better can explain if there’s a more elegant workaround.
|
st99546
|
Just stumbled across this old post when looking for something else, but variable length scatter is basically creating a sparse tensor:
>>> idx = torch.LongTensor([[0, 0], [1, 2], [1 ,3], [2, 0], [2, 1], [2 ,4], [3, 0], [3 ,5]])
>>> val = torch.ones(len(idx))
>>> hot_vec = torch.sparse.FloatTensor(idx.t(), val, torch.Size([4, 7])
>>> hot_vec.to_dense()
tensor([[ 1., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 0., 0., 0.],
[ 1., 1., 0., 0., 1., 0., 0.],
[ 1., 0., 0., 0., 0., 1., 0.]])
|
st99547
|
when i use cpu and my labels are (1, 2, 3, 4, 5), it occured: ‘Assertion cur_target >= 0 && cur_target < n_classes’ failed.', i know pytorch limit us use lable (0 to n) that if we want to classify n + 1 categories,so it run error with cpu :'Assertioncur_target >= 0 && cur_target < n_classes’ failed.’, but when i use gpu to run it, it just like this limitation disappeared?, my labels are (1, 2, 3, 4, 5), and it works!, how werid, anybody can tell me why? i’m appretiate u…
|
st99548
|
The labels should be 0 <= label < n_classes for CUDA, too.
What happens is that CUDA doesn’t report errors quite as diligently due to its asynchronous nature.
Best regards
Thomas
|
st99549
|
I have a line of code as follow:
mu, log_scale = torch.unsqueeze(output[:, 0, :], dim=1), torch.unsqueeze(output[:, 1, :], dim=1)
The output is 3 dimensions tensor.
Please help me convert it to equivalent tensorflow code. I’m newbie of both torch and tensorflow.
Thank for your helps.
|
st99550
|
Solved by kaiyuyue in post #2
In TF, the tf.expand_dims() is equivalent to the torch.unsqueeze().
|
st99551
|
I am a developer at allegro.ai. I am developing an application which runs client machine-learning code which uses pytorch.
Is there some sort of REST API that can be queried for the lookup table in get started mapping platform information (OS, cuda version, etc.) to wheel URL?
Some background:
To make the client code cross-platform, the application searches “pytorch” in the client code’s requirements (requirements.txt) and replaces it with the correct URL according to the table.
Currently, the table is hard-coded, which is obviously suboptimal as it needs to be manually updated.
|
st99552
|
Is it possible to obtain somewhat like R-op in pytorch (jacobian times vector product)?
See e.g. theano documenation http://deeplearning.net/software/theano/tutorial/gradients.html#r-operator 28
|
st99553
|
Hi,
The backward engine in pytorch only allows you to perform L-op using backward mode AD.
R-op is tricky for neural nets when using backward mode AD because you don’t want to compute the full Jacobian for memory size reasons. You would need forward mode AD to implement that efficiently which is not implemented.
I am not sure how hard it would be to do a forward mode AD engine for pytorch. But definitely non trivial.
|
st99554
|
Hi:
Is there any example of L-op implementation in Pytorch?
It seems there is a hope on R-op in Pytorch because
we can implement R-op using twice L-op, as in here 23.
|
st99555
|
In fact, @PiotrSokol was kind enough to share his implementation:
[Adding functionality] Hessian and Fisher Information vector products autograd
Hi,
I implemented Hessian and Fisher Information matrix (FIM) vector products and was wondering if there’d be interest in adding this functionality. The FIM products are optimized, in the sense that they analytically compute the Hessian matrix of the logarithm of the loss wrt. the output layer for a set of commonly used losses.
Best,
P.
Edit: Tagging you in
@smth, @apaszke
Editing for posterity since no one wants to discuss how to submit this PR.
import numpy as np
import torch
def _chec…
Best regards
Thomas
|
st99556
|
I load the dataset with the following transformations:
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
transform = transforms.Compose([
transforms.Resize((240, 240), interpolation=0),
transforms.ToTensor(),
normalize
]),
Then when I try to convert the resulting tensor back to a PIL Image I get the following:
trans = transforms.ToPILImage(mode='RGB')
plt.imshow(trans(img.squeeze()))
plt.show()
Screenshot from 2018-09-28 10-25-14.jpg552×515 185 KB
Clearly, the image is not as it should be. Can anyone let me know what’s going on?
Thanks.
|
st99557
|
These artifacts are caused by the normalization.
If you want to get the original image back, you would need to “denormalize” your tensor again:
img = Image.open('PATH')
x = transform(img)
z = x * torch.tensor(std).view(3, 1, 1)
z = z + torch.tensor(mean).view(3, 1, 1)
img2 = transforms.ToPILImage(mode='RGB')(z)
plt.imshow(img2)
|
st99558
|
Hello,
I am new to Pytorch and I am trying to fit a resnet like model on CIFAR100 dataset.
but while training, I keep getting this error
err.PNG1701×493 54.6 KB
This happens during training, mostly around at epoch 10~15
The code actually worked fine until yesterday.
I first thought this is some kind of driver problem so I tried reinstalling my graphics driver and cuda.
Is there anyone who had the same problem?
How do you solve it?
I am using pytorch 0.4.1
GTX 1060 with CUDA 9
|
st99559
|
Hello, all.
I have 3 networks and I want to use 'p.requires_grad'
then, Can I use like this?
or Is there any more fancy codes?
for p in network1.parameters():
p.requires_grad = True
for p in network2.parameters():
p.requires_grad = True
for p in network3.parameters():
p.requires_grad = True
|
st99560
|
That sounds reasonable to me. You can refer to documentation here - https://pytorch.org/docs/stable/notes/autograd.html 73
|
st99561
|
I got non-deterministic results when I run the RNN model with multi-layers and dropout on GPU. The LSTM layer is defined by following line:
self.enc_rnn = nn.LSTM(input_dim, self.rnn_dim, self.num_layers, bidirectional=True, dropout=self.dropout_p)
I have setup the seed and device with following lines before training:
torch.cuda.set_device(0)
np.random.seed(1234)
torch.manual_seed(1234)
torch.cuda.manual_seed(1234)
torch.cuda.manual_seed_all(1234)
I can get consistent result when the self.num_layers=1 and dropout is non-zero, or self.num_layer > 1 and dropout=0. However, the model will output non-deterministic result when self.num_layer > 1 and dropout is non-zero. Do I still miss something to get the deterministic result?
Thanks
|
st99562
|
I have a pretty large embedding matrix (pretrained and frozen) and I don’t want to copy it to each GPU when using DataParallel.
My ideal situation is the embedding matrix is on CPU, the embedded input is pinned, and the embedded input is sent to their respective GPUs when using DataParallel.
Is this possible? Or reasonable? I’m kind of at loss at the right way to handle this.
|
st99563
|
Posting a couple links that might help figure this out:
Example custom dataloader with pin_memory on individual examples or batches:
github.com
Cadene/vqa.pytorch/blob/master/vqa/lib/dataloader.py 13
import torch
import torch.multiprocessing as multiprocessing
from .sampler import SequentialSampler, RandomSampler
import collections
import math
import sys
import traceback
import threading
if sys.version_info[0] == 2:
import Queue as queue
else:
import queue
class ExceptionWrapper(object):
"Wraps an exception plus traceback to communicate across threads"
def __init__(self, exc_info):
self.exc_type = exc_info[0]
self.exc_msg = "".join(traceback.format_exception(*exc_info))
This file has been truncated. show original
smth mentioning that DataParallel tries to use async:
Yes, DataParallel will try to use async=True by default.
DataParallel model and pin_memory() 12
|
st99564
|
I tried a few different settings. It seems the easiest thing to do is to ignore the pin_memory flag and embed everything on the CPU before calling DataParallel.
More or less this:
embed = torch.nn.Embedding.from_pretrained(embeddings, freeze=True)
model = Model()
model.cuda()
x = torch.LongTensor(batch_size, dim).random_(0, vocab_size-1)
# If you pin at this point, doesn't impact performance.
emb = embed(x)
# If you pin at this point, slightly slowed performance.
out = torch.nn.parallel.data_parallel(model, (emb, ))
Here’s some example code I used to try various settings:
gist.github.com
https://gist.github.com/mrdrozdov/3bcb412ff60151f0cb6caf95d0fcccaa 10
demo_embeddings.py
import argparse
import json
import torch
import torch.nn as nn
from tqdm import tqdm
class Model(nn.Module):
This file has been truncated. show original
results.txt
# Embeddings on Each GPU / Pin Memory before embedding
python demo_embeddings.py --pin_early --embedding_in_model
time: > 30m
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.130 Driver Version: 384.130 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
This file has been truncated. show original
|
st99565
|
Using pinned memory for large embedding memory is not recommended as well, because pinned memory is page-locked and not pre-emptible.
|
st99566
|
I fine-tuned the pre-training ResNet101 model and saved it. The code looks like this:
torch.save(model.state_dict(), save_point+‘model1.pkl’)
But when I reloaded, there was a problem.like this:
model_ft = ResNet()
myresnet = model_ft.load_state_dict(torch.load("./checkpoint/model1.pkl"))
eorr:
Traceback (most recent call last):
File “feature-map.py”, line 68, in
model_ft = ResNet()
NameError: name ‘ResNet’ is not defined
Why is this happening, what should I do?
|
st99567
|
How did you define the class ResNet?
Apparently the class definition is missing. You have to import it from the original file it was defined.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.