id
stringlengths
3
8
text
stringlengths
1
115k
st47568
Besides running your “stress test” for a longer period of time, I don’t know if there are many more tests. If possible, you could try to swap parts of the system, e.g. the PSU, GPU, RAM etc. one by one from another system and check, if it’s still failing. Also, maybe switching the PCIe port could also help. A defect in the PCIe connection would usually just drop the GPU, but hardware defects are not always “well behaved”.
st47569
Did you check your GPU temperature? I met your problem these days.Finally I checked it out. In terminal, watch -n 0.5 nvidia-smi -q -i 0,1 -d TEMPERATURE Then,start your train. If GPU Current Temp > GPU Shutdown Temp, The system will crash
st47570
Hi, everyone, I wonder if there is a function in Pytorch like “scipy.integrate.dblquad” to calculate the double integration of a given function. For example, given f(x,y)=2x+2y and we calculate ∫∫f(x,y)dxdy with pytorch Thanks
st47571
Hi, I don’t think we have such function no. Note that if you don’t need gradients through that computation, you can just translate the Tensor to numpy and use the corresponding scipy function.
st47572
Hi, Thanks , for now, we program a Gaussian integral method with torch for the calculation.
st47573
I’m writing a network where one parameter (I used register_buffer) is expected to be updated if the model is under model.train(), and not to change if is under model.eval(). So I need a (boolean) criterion such that in the forward function, the parameter will be updated based on whether the model is under train or eval. Is there any function to get this value? Thanks!
st47574
Use the training attribute. its True when in train mode and False when in eval mode.
st47575
Hi, I’m trying to use two optimizers to update model parameters. The specific way that I’m going to update a model is like following. First, let’s say the initial model param is A. And A is saved for later. With data D1, A is updated to B. With data D2, B is updated to C. Now with A I saved, I want to update A to E with the gradient (A-C). So following is what I coded for this idea. But I’m not sure if this can cause any problems. And please tell if there is any better way to implement this. Thanks! import copy import torch import torch.nn as nn class custom_model(nn.Module): def __init__(self,): super(custom_model, self).__init__() self.fc = nn.Linear(5, 2) def forward(self, x): return self.fc(x) # model model = custom_model() model.train() # data data1 = torch.randn(1, 5) label1 = torch.tensor([1], dtype=torch.int64) data2 = torch.randn(1, 5) label2 = torch.tensor([0], dtype=torch.int64) # optimizer optimizer1 = torch.optim.SGD(model.parameters(), lr=0.001) optimizer2 = torch.optim.SGD(model.parameters(), lr=1.0) # optimizer2 = torch.optim.Adam(model.parameters(), lr=1.2, # weight_decay=0) # loss criterion = nn.CrossEntropyLoss() # Save the initial weight weight_before = copy.deepcopy(model.state_dict()) print('- before first update :') print('model.fc.weight :\n', model.fc.weight.data) print('model.fc.weight.grad :\n', model.fc.weight.grad) print() # first update output = model(data1) # print('output :', output.shape) # print('label1 :', label1.shape) loss = criterion(output, label1) optimizer1.zero_grad() loss.backward() optimizer1.step() # second update output = model(data2) loss = criterion(output, label2) optimizer1.zero_grad() loss.backward() optimizer1.step() weight_after = copy.deepcopy(model.state_dict()) print('- after second update :') print('model.fc.weight :\n', model.fc.weight.data) print('model.fc.weight.grad :\n', model.fc.weight.grad.data) print() model.load_state_dict(weight_before) print('- after load_state_dict :') print('model.fc.weight :\n', model.fc.weight.data) print('model.fc.weight.grad :\n', model.fc.weight.grad.data) print() optimizer2.zero_grad() for key, param in model.named_parameters(): param.grad = weight_before[key] - weight_after[key] print('- after load gradient :') print('model.fc.weight :\n', model.fc.weight.data) print('model.fc.weight.grad :\n', model.fc.weight.grad.data) print() optimizer2.step() print('- after final update :') print('model.fc.weight :\n', model.fc.weight.data) print('model.fc.weight.grad :\n', model.fc.weight.grad.data) print() - before first update : model.fc.weight : tensor([[ 0.1450, -0.4029, 0.1476, 0.4165, -0.4402], [ 0.0265, 0.2699, -0.0318, 0.0279, -0.1861]]) model.fc.weight.grad : None - after second update : model.fc.weight : tensor([[ 0.1454, -0.4036, 0.1477, 0.4166, -0.4398], [ 0.0261, 0.2705, -0.0319, 0.0279, -0.1864]]) model.fc.weight.grad : tensor([[-0.0947, 0.0916, -0.3051, -0.0305, -0.0133], [ 0.0947, -0.0916, 0.3051, 0.0305, 0.0133]]) - after load_state_dict : model.fc.weight : tensor([[ 0.1450, -0.4029, 0.1476, 0.4165, -0.4402], [ 0.0265, 0.2699, -0.0318, 0.0279, -0.1861]]) model.fc.weight.grad : tensor([[-0.0947, 0.0916, -0.3051, -0.0305, -0.0133], [ 0.0947, -0.0916, 0.3051, 0.0305, 0.0133]]) - after load gradient : model.fc.weight : tensor([[ 0.1450, -0.4029, 0.1476, 0.4165, -0.4402], [ 0.0265, 0.2699, -0.0318, 0.0279, -0.1861]]) model.fc.weight.grad : tensor([[-3.8286e-04, 6.3995e-04, -1.5891e-04, -5.3495e-05, -3.8928e-04], [ 3.8285e-04, -6.3995e-04, 1.5890e-04, 5.3499e-05, 3.8925e-04]]) - after final update : model.fc.weight : tensor([[ 0.1454, -0.4036, 0.1477, 0.4166, -0.4398], [ 0.0261, 0.2705, -0.0319, 0.0279, -0.1864]]) model.fc.weight.grad : tensor([[-3.8286e-04, 6.3995e-04, -1.5891e-04, -5.3495e-05, -3.8928e-04], [ 3.8285e-04, -6.3995e-04, 1.5890e-04, 5.3499e-05, 3.8925e-04]])
st47576
I want to accumulate the gradients before I do a backward pass. So wondering what the right way of doing it is. According to this article 654 it’s (let’s assume equal batch sizes): model.zero_grad() # Reset gradients tensors for i, (inputs, labels) in enumerate(training_set): predictions = model(inputs) # Forward pass loss = loss_function(predictions, labels) # Compute loss function loss = loss / accumulation_steps # Normalize our loss (if averaged) loss.backward() # Backward pass if (i+1) % accumulation_steps == 0: # Wait for several backward steps optimizer.step() # Now we can do an optimizer step model.zero_grad() whereas I expected it to be: model.zero_grad() # Reset gradients tensors loss = 0 for i, (inputs, labels) in enumerate(training_set): predictions = model(inputs) # Forward pass loss += loss_function(predictions, labels) # Compute loss function if (i+1) % accumulation_steps == 0: # Wait for several backward steps loss = loss / accumulation_steps # Normalize our loss (if averaged) loss.backward() # Backward pass optimizer.step() # Now we can do an optimizer step model.zero_grad() loss = 0 where I accumulate the loss and then divide by the accumulation steps to average it. Secondary question, if I am right, would you expect my method to be quicker considering I only do the backward pass every accumulation steps? This is a crosspost from SO 88.
st47577
Hi, This has been discussed in details in this post 7.8k. Let me know if you have further questions !
st47578
Thanks for this. Could you see if the logic in my understanding below is correct? Suppose that in my case accumulation_steps = 10. Therefore with my second code block, I would be creating the graph ten times, therefore would require ten times the memory. However, what I’m not 100% sure is, is this 10 times the memory to hold the parameters, or 10 times the parameters plus the intermediate values calculated in each batch? The second question is, isn’t loss.backward() the most compute intensive step, since this is where gradients are calculated. So provided that I can hold 10 graphs in memory, wouldn’t this option be the fastest?
st47579
Hi, It’s never 10 times the parameters. It’s only 10times the intermediary states. The amount of work in both case is the same. The difference will be that you call a single backward, but the graph it backward through is 10 times bigger. So compute wise it will be the same.
st47580
Hi, If I use T5 language model, there isn’t any batch-norm layer inside, should I use averaged loss then? Or I can just use loss.backward() on every iteration and opt.step() opt.zero_grad() when iteration % accumulation_steps == 0 ?
st47581
Hi I have multiple iterative datasets with different size and I want to join them in a way that each datasets is sampled equally, so smaller datasets more, larger one less, could you tell me how to implement this in pytorch? thanks
st47582
Sorry I don’t really get ur question. What exactly do you mean by different sizes? R u insinuating that there r multiple data sets and that the number of data points in each vary? Also what exactly do u mean by sampled equally? Sorry for replying u with so many questions
st47583
Hi there, I finally found the response to my question here Train simultaneously on two datasets 11 thanks.
st47584
this the first time I post here, I am new in Pytorch, I am trying to train my first image recognition with MNIST. I noted when I don’t use transforms.Normalize((0.5,), (0.5,)) , The NN wights don’t change, and the gradient remains zero, but when I use the normalization the wights are updated and the gradient change, why is that? transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)), ]) mnist_train = datasets.MNIST("./", train=True, download=True, transform=transform) train_loader = DataLoader(mnist_train, batch_size=batch_size, shuffle=False) input_size=784 hidden_size=100 output_size=10 network = nn.Sequential( nn.Linear(input_size, hidden_size), # First layer (hidden)of the network takes the entire image and reduces it to 100 dimensions nn.ReLU(), nn.Linear(hidden_size, output_size), # The second layer(output) takes those 100 dimensions and reduces them into estimeated values for each digit nn.Softmax(dim=1) ) images, labels = next(iter(train_loader)) images = images.view(-1,784) labels=torch.eye(10)[labels] output = network(images) los_fun=nn.MSELoss() loss = los_fun(output, labels) #calculate the loss print('Before backward pass: \n', network[0].weight.grad) loss.backward() # to calculate gradients of parameter print('After backward pass: \n',network[0].weight.grad) optimizer = optim.SGD(network.parameters(), lr=0.01, momentum=0.9) print('Initial weights - ', network[0].weight) images, labels = next(iter(train_loader)) images = images.view(-1,784) Clear the gradients, do this because gradients are accumulated optimizer.zero_grad() Forward pass output = network(images) labels=torch.eye(10)[labels] loss = los_fun(output, labels) the backward pass and update weights loss.backward() print(‘Gradient -’, network[0].weight.grad)
st47585
What transforms.Normalize((0.5,), (0.5,)) does ; (X - mean(X) )/ std(X) Where X is image data Mean (X) mean pixel value of X std(X) standard deviation of X The normalize function normalizes your data to be with the range of (-1, 1) So using values 0.5 as mean and standard deviation means that your dataset has been scaled to range (0, 1). If your dataset is not scaled to range (0, 1) before normalize, the u either scale them by dividing the raw image by 255 or setting ur mean and std in normalize function to 255/2. After the loss.backward() you school also call the optimizer.step() function those are what the backward propagation and weight update consists of. If u did that then: As for why your gradients don’t change without the normalize, this is the 1st time I’m hearing such Does it change but the change is very minute and insignificant or it doesn’t change at all?
st47586
It is straightforward to do the following and wrap a Gaussian into an Independent. So if we are given a loc = [batch_size, event_shape] scale = [batch_size] loc = torch.zeros(5, 3, 2) scale = torch.ones(2) normal = Normal(loc, scale) normal.batch_shape, normal.event_shape (torch.Size([5, 3, 2]), torch.Size([])) ind = Independent(normal, 1) ind.batch_shape, ind.event_shape (torch.Size([5, 3]), torch.Size([2])) This Independent distribution is identical to a MultivariateNormal defined as: mvn = MultivariateNormal(mu, torch.diag(scale)) But, what if I have the following: mu = torch.zeros(5, 2) log_sigma = torch.ones(5, 2) Independent(Normal(loc=mu, scale=torch.exp(log_sigma)), 1) This works fine, however how to use MultivariateNormal is not clear: mvn = MultivariateNormal(mu, ???) Is it possible to use MultivariateNormal and get the same distribution? How do I provide the covariance_matrix argument given log_sigma of shape [batch_size, event_shape] EDIT: mu = torch.zeros(5, 2) log_sigma = torch.ones(5, 2) cov = torch.stack([torch.diag(sigma) for sigma in torch.exp(log_sigma)]) mvn = MultivariateNormal(mu, cov) => would this result in an equivalent to Independent(Normal(loc=mu, scale=torch.exp(log_sigma)), 1) ??
st47587
I have the following frames form a video as images [batch_size=100,channels=2, image_height=64, image_width=64], a single batch consist of a sequence with 100 frames. I want to predict 1 frame ahead using a vanilla LSTM, I have transformed my input sequence as follows [batch_size, channels* image_height, image_width]. How should I transform my data to be able to train such an architecture?
st47588
I want to realize this one using my own dataset, and my picture is like this ,but the image can not loaded in . https://github.com/msminhas93/DeepLabv3FineTuning 2 .How does the image convert into mask? is there any format? my dataset and the annotated road crack image database that used in the model:
st47589
May the reason be that only 4 images can not be divided into the train and val dataset in the network?
st47590
Hi. So, you need to change your dataloader from that GitHub repository as below to make it work with the VOC segmentation dataset. Look for the Update in code comments. import torch import torchvision from torch.utils.data import Dataset from PIL import Image import glob import numpy as np class SegmentationDataset(Dataset): """Segmentation Dataset""" def __init__(self, root_dir: str, image_dir: str, mask_dir: str, transform=None, seed: int = None, fraction: float = None, subset: str = None, imagecolormode: str = 'rgb', maskcolormode: str = 'rgb'): """ Args: root_dir (str): dataset dir path image_dir (str): input image dir name mask_dir (str): mask image dir name transform: PyTorch data transform seed (int): random seed for reproducibility fraction (float): dataset train/test split percentage subset (str): subset from existing dataset imagecolormode (str): input image color mode maskcolormode (str): input mask color mode """ self.color_dict = {'rgb': 1, 'grayscale': 0} assert (imagecolormode in ['rgb', 'grayscale']) assert (maskcolormode in ['rgb', 'grayscale']) self.imagecolorflag = self.color_dict[imagecolormode] self.maskcolorflag = self.color_dict[maskcolormode] self.root_dir = root_dir self.transform = transform if not fraction: # UPDATE: Get the Segmentation Masks Before Images self.mask_names = sorted( glob.glob(os.path.join(self.root_dir, mask_dir, '*'))) # UPDATE: Get images with the names in the mask_names list but with updated path and '.jpg' extension self.image_names = sorted( os.path.join(self.root_dir, image_dir, fname.split('/')[4].split('.png')[0] + '.jpg') for fname in self.mask_names) else: assert (subset in ['Train', 'Test']) self.fraction = fraction # UPDATE: Get the Segmentation Masks Before Images self.mask_list = np.array( sorted(glob.glob(os.path.join(self.root_dir, mask_dir, '*')))) # UPDATE: Get images with the names in the mask_names list but with updated path and '.jpg' extension self.image_list = np.array( sorted(os.path.join(self.root_dir, image_dir, fname.split('/')[4].split('.png')[0] + '.jpg') for fname in self.mask_list)) if seed: np.random.seed(seed) indices = np.arange(len(self.image_list)) np.random.shuffle(indices) self.image_list = self.image_list[indices] self.mask_list = self.mask_list[indices] if subset == 'Train': self.image_names = self.image_list[:int( np.ceil(len(self.image_list) * (1 - self.fraction)))] self.mask_names = self.mask_list[:int( np.ceil(len(self.mask_list) * (1 - self.fraction)))] else: self.image_names = self.image_list[int( np.ceil(len(self.image_list) * (1 - self.fraction))):] self.mask_names = self.mask_list[int( np.ceil(len(self.mask_list) * (1 - self.fraction))):] def __getitem__(self, idx): """ Args: idx (int): index of input image Returns: dict: image and mask image """ img_name = self.image_names[idx] mask_name = self.mask_names[idx] image = Image.open(img_name) mask = Image.open(mask_name) sample = {'image': image, 'mask': mask} if self.transform: sample = self.transform(sample) return sample def __len__(self): """ Returns: length of dataset """ return len(self.image_names) Now you can call the above dataset class as follows: dataset = SegmentationDataset(root_dir='./VOCdevkit/VOC2012/', image_dir='JPEGImages', mask_dir='SegmentationClass', seed=100, fraction=0.1, subset='Train') and everything should work. You can test the image/mask pairs using the following code: import matplotlib.pyplot as plt for i,data in enumerate(dataset): image, mask = data['image'], data['mask'] show_image_mask(image, mask) if i > 5: break Hope this helps
st47591
I think the image has loaded in but the train and test not has been spited out, since the train not begin by running the command and nothing logged in log.csv. Can you give me some guidance? 151410×425 44.6 KB
st47592
It seems that if I change imageFolder to image_dir in SegDataset it gives me TypeError of init (), but SegDataset can not works well alone if I define imageFolder, I am confusing…
st47593
Hello, I did FNN for 4 class classifications. How is it possible to calculate confusion matrix?
st47594
Solved by ptrblck in post #9 To calculate the confusion matrix you need the class predictions. Currently it looks like pred contains the logits or probabilities for two classes. Try to call torch.argmax(pred, 1) to get the predicted classes. Here is a small example: output = torch.randn(1, 2, 4, 4) pred = torch.argmax(output…
st47595
You could use the scikit-learn implementation 3.2k. Just get your predictions and targets using .numpy(). Alternatively you could of course calculate the conf matrix manually, if you don’t want to install/use scikit-learn.
st47596
I applied scikit-learn implementation, but output from FNN tend to 0. As a result my confusion matrix looks weird. for epoch in range (num_epochs): out = model(input_train).to(device) _, pred = out.max(1) total += target_train.size(0) correct += (pred == target_train).sum().item() print(input_train) print(pred) loss = loss_func(out,target_train) counter +=1 print('loss train', "Epoch N", counter,loss.data[0]) model.zero_grad() loss.backward() opt.step() print('Accuracy of the network on train dataset: {} %'.format(100 * correct / total)) conf_matrix = metrics.confusion_matrix(pred, y) [[530783 0 0 0] [ 8097 0 0 0] [ 20079 0 0 0] [ 16682 0 0 0]] Where can be an error?
st47597
It looks like your model does not learn anything useful. Since your classes are imbalanced, you could try to use a weighted loss function or the WeightedRandomSampler 403.
st47598
But I have to find confusion matrix for multi class image segmentation problem of high resolution images i.e. 1024x2048. Copying tensors from gpu to cpu i.e. numpy and then calculating confusion matrix is really time consuming. I found this 118 but it is only of binary classification, not sure how to scale it to multi class.
st47599
@ptrblck I did use the scikit-learn implementation to calculate the confusion matrix. The snippet is like this. with torch.no_grad(): for i, data in enumerate(test_loader, 0): # get the inputs t_image, mask = data t_image, mask = Variable(t_image.to(device)), Variable(mask.to(device)) output = model(t_image) pred = torch.exp(output) conf_matrix = confusion_matrix(pred, mask) print(conf_matrix) I am wondering why I am getting this error , what do you think? is it related to the shape of pred or input? File "C:\Users\Neda\Anaconda3\lib\site-packages\sklearn\metrics\classification.py", line 88, in _check_targets raise ValueError("{0} is not supported".format(y_type)) ValueError: unknown is not supported
st47600
Probably scikit doesn’t recognize the format of your inputs to confusion_matrix. Could you print the shapes and some values of pred and mask? I guess flattening both inputs should work.
st47601
@ptrblck the shape of inputs are t_image: (1, 1, 240, 320), pred: (1, 2, 240, 320), mask: (1, 240, 320).
st47602
To calculate the confusion matrix you need the class predictions. Currently it looks like pred contains the logits or probabilities for two classes. Try to call torch.argmax(pred, 1) to get the predicted classes. Here is a small example: output = torch.randn(1, 2, 4, 4) pred = torch.argmax(output, 1) target = torch.empty(1, 4, 4, dtype=torch.long).random_(2) confusion_matrix(pred.view(-1), target.view(-1))
st47603
I have an idea but don’t know whether it works. change pred and target into one_hot format on gpus TP = pred * target FP = pred * (1-target) FN = (1-pred) * target TN = (1-pred) * (1-target)
st47604
@ptrblck Hello, May I know how to create a confusion matrix for YOLOv3. For a 3 class classification
st47605
I don’t know what kind of classification output YOLOv3 returns, but for a multi-class classification the linked sklearn.metrics.confusion_matrix should work, while for a multi-label classification you could use sklearn.metrics.multilabel_confusion_matrix 130.
st47606
def ap_per_class(tp, conf, pred_cls, target_cls): “”" Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics 14. # Arguments tp: True positives (nparray, nx1 or nx10). conf: Objectness value from 0-1 (nparray). pred_cls: Predicted object classes (nparray). target_cls: True object classes (nparray). # Returns The average precision as computed in py-faster-rcnn. “”" # Sort by objectness i = np.argsort(-conf) tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] # Find unique classes unique_classes = np.unique(target_cls) # Create Precision-Recall curve and compute AP for each class pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898 s = [unique_classes.shape[0], tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95) ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s) for ci, c in enumerate(unique_classes): fig, ax = plt.subplots(1, 1, figsize=(5, 5)) i = pred_cls == c n_gt = (target_cls == c).sum() # Number of ground truth objects n_p = i.sum() # Number of predicted objects if n_p == 0 or n_gt == 0: continue else: # Accumulate FPs and TPs fpc = (1 - tp[i]).cumsum(0) tpc = tp[i].cumsum(0) # Recall recall = tpc / (n_gt + 1e-16) # recall curve r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases # Precision precision = tpc / (tpc + fpc) # precision curve p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score # AP from recall-precision curve for j in range(tp.shape[1]): ap[ci, j] = compute_ap(recall[:, j], precision[:, j]) # Plot ax.plot(recall, precision) ax.set_xlabel('Recall') ax.set_ylabel('Precision') ax.set_xlim(0, 1.01) ax.set_ylim(0, 1.01) fig.tight_layout() # Compute F1 score (harmonic mean of precision and recall) fig.savefig(f'PR_curve_{c}.png', dpi=300) f1 = 2 * p * r / (p + r + 1e-16) print(ap) return p, r, ap, f1, unique_classes.astype('int32') Thank you for the response, but may I request to have a look at this snippet and can request you to say where the line of code multilabel_confusion_matrix fits in. @ptrblck
st47607
multilabel_confusion_matrix expects the multi-label target as well as the predicted classes as the inputs. Based on your code snippet I guess target_cls and pred_cls would be the corresponding tensors.
st47608
Hello,bro.Does Mr.ptrblck’s reply work?I have problem about Confusion-Matrix too.And I’m going to calculate yolo’s accuracy.Waiting for your reply.<3
st47609
Hi, I created a virtual environment and wanted to install the current latest stable version (1.7) with the following command: pip install torch==1.7.0+cu110 torchvision==0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html 2 When I check the version, it seems that 1.4.0 is installed: import torch >>> print(torch.__version__) 1.4.0 Does anyone know why the 1.7.0 version is not installed? This is the output from the installation procedure: Installing collected packages: torch, torchvision Found existing installation: torch 1.7.0+cu101 Uninstalling torch-1.7.0+cu101: Successfully uninstalled torch-1.7.0+cu101 Found existing installation: torchvision 0.8.1+cu101 Uninstalling torchvision-0.8.1+cu101: Successfully uninstalled torchvision-0.8.1+cu101 Successfully installed torch-1.7.0+cu110 torchvision-0.8.1+cu110 If I try to install it in conda environment (using conda install), the versions match.
st47610
I guess you might have multiple PyTorch installations in your current environment, so before installing the latest 1.7.0 version you should uninstall the older ones.
st47611
Hello everyone, I built a simple model and I want to know the number of its parameters using torchsummary, but I got an error: “AttributeError: ‘int’ object has no attribute 'numpy” class LinearRegression(nn.Module): def __init__(self, in_features: int, out_features: int, bias: bool = True): super().__init__() self.weights = nn.Parameter(torch.randn((in_features,out_features),requires_grad=True)) self.bias = bias if bias: self.bias_term = nn.Parameter(torch.rand((out_features),requires_grad=True)) def forward(self, x): x = x@ self.weights if self.bias: x += self.bias_term return x from torchsummary import summary linear_regression = LinearRegression(2, 1) summary(model=linear_regression,input_size=(4,2),device='cpu') Please tell me what am I doing wrong?
st47612
Solved by ptrblck in post #2 This seems to be a known issue in pytorch-summary and based on this issue it seems torch-summary is better maintained now.
st47613
This seems to be a known issue in pytorch-summary 57 and based on this issue 90 it seems torch-summary 157 is better maintained now.
st47614
I have about 8000 sentences and i try to calculate their representation with transformer. I firstly fed the 8000 sentences into the transformer at the same time but it reported “CUDA out of memory”. Then i fed 32 sentences into transformer one time to recurrently process these sentences, but again it reported this error: I only post code of this part below(note sentidx is a tensor of shape 8000*47,batch_size = 32, self.emb is the nn.Embedding module. self.encoder is the standard transformer module provided by torch.nn. When k=54, it will report CUDA out of memory. Does anyone have suggenstion? error1099×182 5.72 KB
st47615
After I initialize my model, I want to train it separately for different datasets sets (X1,Y1), (X2,Y2), …, (X50,Y50), and so on. My naive way to do it is to train it for Y1, save the weights, then re-initialize and train it for Y2, save those weights, and repeat for each dataset (X, Y). But the model is exactly the same each time, so I feel like there should be some way to take advantage of pytorch’s optimized GPU-parallelized autograd to train for all these different labels Yi at the same time, than doing it one at a time. How can I most efficiently use Pytorch for this task?
st47616
I am trying to train it separately. So I have one set of parameters P1 trained on (X1, Y1), another set of parameters P2 trained on (X2, Y2), and so on.
st47617
Y exactly do u want to train it separately? Do u plan on storing these set of weights individually?
st47618
I have 1 GPU. Yes I am storing each set of trained weights (P1 for (X1, Y1), P2 for (X2, Y2), etc.) separately.
st47619
Well u can do it the normal way and just set batch size to 1 (setting batch size to 1 will only feed the network one feature target pair at a time) then u create another for loop that trains on that single data point for n number of cycles, then u write a function that saves each weight to a different file in a folder, and another function that resets the weights for another data point. If u want to keep track of which weight belongs to which data point then u don’t need to shuffle ur dataset.
st47620
As I said I am already training one dataset (Xi, Yi) at a time, saving the parameters Pi, re-initializing, and doing it again for (Xi+1, Yi+1) and so on. My question was, since it’s the same model and loss function and optimizer each time, is there an efficient way for me to train on these different datasets at the same time, like I train on multiple examples within one dataset at the same time via mini batches. Except, instead of averaging the gradients like a minibatch, I want to keep multiple sets of parameters Pi, one for each dataset (Xi, Yi), and only update Pi with the gradients associated with the examples in the minibatch that come from (Xi, Yi).
st47621
Hmmm🤔 If u are looking for a more efficient way to do this well… , but I mean u can try out what i said in my previous answer coz that’ll also save and update parameters Pi for (xi, yi) and Pi+1 for (xi+1, yi+1) and so on. What I can suggest u do to make things faster: Use the garbage collector to empty redundant variables Share the work amongst different gpus (but u said u have only 1 so u should consider cloud service) Prototype the implementation in python and do the main implementation in C++ then u can run inference in python
st47622
you can keep a copy of your model’s weights and optimizer’s weights for each of your datasets and alternatively switch back and forth between these two sets of weights as you train on your two separate datasets. But this is a confusing way to train…
st47623
With one GPU, if your script uses <50% of GPU memory, your best bet to increase GPU utilization is launching multiple scripts (processes). In-process parallelization, using multiple cuda streams with replicated model modules may work but it is hard to write this correctly (in a nutshell, you must avoid blocking cuda operations [like copy() and item()], or use python threads) And there is no way to do a tensor level parallelization on multiple input+parameter sets.
st47624
What He/She wants to do is to train on each single data point in the dataset and save the parameters for each of those data points Like for each data point pair (Xi, Yi), it should have its own parameter Pi. Sth like that
st47625
Hi guys, I tried to use “deepcopy”, but It changed the parameters(gradients), while I did not want to change it. The goal is P[1].grad be updated when Itr%2 is zero and save as gradient of Net_Kfast. And when Itr%2 is not zero, I want the P[1].grad remain the same… #Preformatted text for P in zip(net.parameters(), Net_Kfast.parameters(), *net_parameters): temp = 0 for p in P[2:]: temp += p.grad/len(Participated_Workers) P[0].grad = temp if Itr%2 == 0: P[1].grad = copy.deepcopy(temp) ```
st47626
I have been using this code to count the number of images in each class for my dataset, but it’s extremely slow. Is there a better more efficient way to get the number of images in each class? def count_classes(dataset): class_counts = dict(Counter(sample_tup[1] for sample_tup in dataset)) return dict(sorted(class_counts.items()))
st47627
hi, i currently have a model that intakes a tensor N x C x H x W and a label tensor N x L. In the forward method, I want to first use different net for different label and then combine them together for other layers. so i current have some code like: def forward(self, data): for i in range(label_types_num): idx = get_label_idx(i) # get all the index that has this label group_data = data[idx, :] o = self.seperate_nets[i](group_data) output_tensor[idx, :] = o # then output_tensor is passed to other layers... Just wondering is there a way to parallel do the for loop?
st47628
Solved by LeviViana in post #2 I think you could use torch.distributed.launch. This snippet may be useful to you to get a better grasp on how torch.distributed.launch works.
st47629
I think you could use torch.distributed.launch. This snippet 849 may be useful to you to get a better grasp on how torch.distributed.launch works.
st47630
hi, i take a look at that snippet, and it seems for me that the distribution is done by distributing data onto different GPUs (correct me if i’m wrong). However, here I would like some solutions that parallel the for loop in a single GPU case since each ‘data’ in my code itself is already in a single GPU when calling the forward.
st47631
If you analyze more carefully the snippet, you will notice that torch.distributed.launch launches CPU threads. Indeed, you can leverage this to run a model on multiple GPUs (one per thread), but you can do much more, like running multiple threads for one GPU. One limitation of doing this is that, as far as I can tell, the threads don’t share memory, which means that if you launch 10 threads on the same GPU, it will allocate 10x more memory.
st47632
thank you so much! that makes sense, i’ll try to find a balance between memory and speed for my model.
st47633
Is there any concrete solution to this? An example solution would be very helpful, as the suggested post does not make this use-case explicit.
st47634
I am brand-new to PyTorch and trying to get up to speed. I installed PyTorch on a 64 bit virtual machine running CentOS 7.5. Host processor is AMD 4 core Phenom IIx4 945. Python 3.6.8 Gcc 4.8.5 20150603 No GPU Installation instruction (from website) pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html 6 In the third section of the “60 minute blitz tutorial”, following all the instructions, I entered: out.backward(torch.randn(1, 10)) And got a core dump. out.backward(torch.randn(1,10)) Illegal instruction (core dumped) Having the tutorial crash looks really bad ;^) Also interfering with my goal to learn PyTorch! I’d appreciate help with this. Thanks.
st47635
That’s indeed a bad first experience Could you run the code in a terminal and try to get the stack trace via: $ gdb --args python my_script.py ... Reading symbols from python...done. (gdb) run ... (gdb) backtrace ...
st47636
In fact I was running the tutorial in a terminal on my local VM. Here’s the beginning of the gdb backtrace. Let me know if you want the whole thing. (I apologize in advance if this should be in a code-block. I don’t see how to do this.) Thanks! [New Thread 0x7fffd736d700 (LWP 14775)] [New Thread 0x7fffd6b6c700 (LWP 14776)] Program received signal SIGILL, Illegal instruction. [Switching to Thread 0x7fffd736d700 (LWP 14775)] 0x00007fffe2ceffc1 in void mkldnn::impl::cpu::(anonymous namespace)::kernel_mxn<float, true, false>(int, float const*, long, float const*, long, float*, long, float, float) () from /home/goldin/.pyVirtual/lib/python3.6/site-packages/torch/lib/libtorch.so Missing separate debuginfos, use: debuginfo-install bzip2-libs-1.0.6-13.el7.x86_64 glibc-2.17-222.el7.x86_64 keyutils-libs-1.5.8-3.el7.x86_64 krb5-libs-1.15.1-18.el7.x86_64 libcom_err-1.42.9-11.el7.x86_64 libffi-3.0.13-18.el7.x86_64 libgcc-4.8.5-28.el7.x86_64 libselinux-2.5-12.el7.x86_64 libstdc+±4.8.5-28.el7.x86_64 openssl-libs-1.0.2k-12.el7.x86_64 pcre-8.32-17.el7.x86_64 python3-libs-3.6.8-10.el7.x86_64 xz-libs-5.2.2-1.el7.x86_64 zlib-1.2.7-17.el7.x86_64 (gdb) backtrace #0 0x00007fffe2ceffc1 in void mkldnn::impl::cpu::(anonymous namespace)::kernel_mxn<float, true, false>(int, float const*, long, float const*, long, float*, long, float, float) () from /home/goldin/.pyVirtual/lib/python3.6/site-packages/torch/lib/libtorch.so #1 0x00007fffe2cf02d9 in void mkldnn::impl::cpu::(anonymous namespace)::block_ker<float, true, false>(int, int, int, float const*, long, float const*, long, float*, long, float, float, float*, bool) () from /home/goldin/.pyVirtual/lib/python3.6/site-packages/torch/lib/libtorch.so #2 0x00007fffe2cf4287 in mkldnn_status_t mkldnn::impl::cpu::ref_gemm(char const*, char const*, int const*, int const*, int const*, float const*, float const*, int const*, float const*, int const*, float const*, float*, int const*, float const*)::{lambda(int)#2}::operator()(int) const () from /home/goldin/.pyVirtual/lib/python3.6/site-packages/torch/lib/libtorch.so
st47637
Thanks for the stack trace! Based on the stack trace, if seems mkldnn got an illegal instruction. If I recall correctly, I’ve seen this issue on older CPUs, which didn’t support SSE2. However, after quickly googling the specs of your CPU, it seems SSE is supported. I’m not that experienced in AMD CPUs, so let’s wait for other opinions on this error and if it’s in fact even related to the chip. PS: you can add code snippets by wrapping them into three backticks ```
st47638
An update: – Created an Ubuntu-based VM on the same physical host (AMD-based) and installed PyTorch via Anaconda --> still crashes – Moved this VM to a different host machine with a four core i3 Intel CPU --> problem goes away. This suggests the problem is related to the underlying hardware. Not a pretty conclusion. Anyway, thanks for your help.
st47639
I am trying fine-tuning pre-trained model using my own dataset, but the model does not function well, is there any way? I have been trying these days but I can not product it out, can you give me some help? 161490×768 103 KB
st47640
Yes, you could use the pip install command from here 4 in the notebook. Note that your Colab notebook should already have PyTorch preinstalled.
st47641
In the middle of training on the first epoch, my process was killed. Going into /var/log/syslog, I read: Out of memory: Killed process 70837 (python), which seems to be the reason why SIGKILL was called. Meanwhile, I have tested that if I change my batch size from 16 to 8, training can run to full completion. This leads me to the belief that my RAM usage is increasing per iteration, but resetting per epoch. What could be the reason for this, and what should I do to fix this? Here are notable snippets of my code: model.train() for t in range(num_of_epochs): for step in range(num_of_batches): length_data, input, target = loader.get_a_batch() # Get a batch of data from my custom dataloader class if torch.cuda.is_available(): input = input.cuda() target = target.cuda() model.zero_grad() output = model(input) loss = loss_func(target, output, length_data) # Read below for specific code snippet optimizer.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm(model.parameters(), grad_clip_val) optimizer.step() loss = float(loss.item()) if loss < best_loss: torch.save(model.state_dict(), ...) best_loss = loss where def loss_func(target, output, length_data): loss_fn = torch.nn.MSELoss() sum_loss = 0.0 for i in range(len(length_data)): length = length_data[i] sum_loss += loss_fn(target[i, 0:length, :], output[i, 0:length, :]) return sum_loss Reading on previous discussions, I feel like my problem might come from loss_func where I am summing the losses. However, I feel like the way that I am current doing is necessary for the backpropagation. Would anyone have any advice? Thank you. Note: My model is an RNN dealing with variable-sized input, which is why you see some of the formatting above.
st47642
How significant is adding relu to fully connected layers? Is it necessary or how the performance of a model is affected by adding relu to Fc layers?
st47643
Solved by ptrblck in post #2 Without activation functions your stacked linear layers can be seen as a single linear mapping and your model might thus fail easily. This chapter in the DeepLearningBook explains more about activation functions and uses the XOR example.
st47644
Without activation functions your stacked linear layers can be seen as a single linear mapping and your model might thus fail easily. This chapter 2 in the DeepLearningBook explains more about activation functions and uses the XOR example.
st47645
I am training BERT model for sentiment analysis, with train data size 80k, but getting out of memory error for batch size 128,256 and above. Here is the stack trace, /usr/local/lib/python3.6/dist-packages/transformers/modeling_bert.py in forward(self, hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, output_attentions) 337 encoder_hidden_states, 338 encoder_attention_mask, –> 339 output_attentions, 340 ) 341 attention_output = self.output(self_outputs[0], hidden_states) /usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 725 result = self._slow_forward(*input, **kwargs) 726 else: –> 727 result = self.forward(*input, **kwargs) 728 for hook in itertools.chain( 729 _global_forward_hooks.values(), /usr/local/lib/python3.6/dist-packages/transformers/modeling_bert.py in forward(self, hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, output_attentions) 257 # Take the dot product between “query” and “key” to get the raw attention scores. 258 attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) –> 259 attention_scores = attention_scores / math.sqrt(self.attention_head_size) 260 if attention_mask is not None: 261 # Apply the attention mask is (precomputed for all layers in BertModel forward() function) RuntimeError: CUDA out of memory. Tried to allocate 844.00 MiB (GPU 0; 15.90 GiB total capacity; 14.36 GiB already allocated; 377.88 MiB free; 14.63 GiB reserved in total by PyTorch) Can someone please suggest on how to resolve this. I am using Colab GPU, is there any limit on size of training data for GPU with 15gb RAM? Thanks
st47646
Anamika_Singh: I am using Colab GPU, is there any limit on size of training data for GPU with 15gb RAM? Yes, there would always be an upper limit, which fits on your GPU (and of course also system RAM). You might need to lower the batch size for the particular GPU you are using, if you are running out of memory.
st47647
I am doing the weightedrandomsampler on my dataset. I am using it to create the training data, can someone tell me what I am doing wrong Code and Error image969×832 50.5 KB
st47648
I don’t think the WeightedRandomSampler creates the error, but your pandas.DataFrame raises a KeyError so you should check how this DataFrame is called and make sure the keys are valid. PS: it’s better to post code snippets by wrapping them into three backticks ```, which would make debugging easier.
st47649
Hello all. my prediction tensor (output of a CNN size of BxCxHxW) has to in range [0,1]. However, the prediction tensor sometime in the range smaller than 0 or bigger than 1. Do we have any torch function to cutting the negative value and bigger than one, so that the range of tensor will be in [0,1] if x< 0 --> x=0 if x>1 -->x=1 This is my solution x = torch.clamp(x, min=0, max=1)
st47650
clamp or sigmoid should work depending if you want a hard “cut” or want to use a smooth function.
st47651
It seems the call from torch.utils.data import * is broken in v1.7 while working in v1.6. Is this desired? >>> print(torch.__version__) 1.7.0 >>> from torch.utils.data import * Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'torch.utils.data' has no attribute 'BatchSamplerDistributedSamplerDataset'
st47652
This PR 34 unfortunately broke the star import by forgetting to add commas between the class names. However, it’s already fixed in the nightly binaries so you could update if you need to use this way of importing the classes. Note that importing or using the classes directly e.g. via: from torch.utils.data import BatchSampler would still work.
st47653
Hi all, How to multiply two tensors with A ~> torch.Size([4]) and B ~> torch.Size([3, 1]) Any help will be appreciated.
st47654
How should the multiplication take place, i.e. which value of A should be multiplied with which value(s) of B? An elementwise multiplication isn’t possible, as both tensors have a different number of elements so I guess you would like to apply some kind of matrix multiplication?
st47655
How many fully connected layers should be added to a model? Does it depend on input size to fully connected layer?If so, how do we decide?What if the input size of fully connected layer is very high ., say 401408 (in my case)?
st47656
I was training a model on two 11G memory GPUs, and the memory consumption is about 10.3 G per GPU observed by nvidia-smi. After I upgrade PyTorch to 1.7, this project could not be run any more and encountered CUDA out of memory. So does PyTorch1.7 need more memory? Besides, my CUDA version is 10.2.
st47657
That’s strange. I tested on another two GPUs now and everything is OK. Since the two GPUs which I meet the problem is training now with PyTorch 1.4. After the training is over, I’ll test whether the problem occurs by accident.
st47658
I noticed too that with 1.7 I can run twice less threads than I used to to with 1.6 I’m curious about any explanation for that. Could the default precision on Cuda 11 be float64 or something like that?
st47659
What kind of threads do you mean? Julien_Maille: Could the default precision on Cuda 11 be float64 or something like that? No, that’s not the case.
st47660
The loss function is a combination of Mean Sqaured error loss and cross-entropy loss. When i am training my model, there is a finite loss but after some time, the loss is NaN and continues to be so. When I am training my model just on a single batch of 10 images, the loss is finite most of the times, but sometimes that is also NaN. Please suggest a possible solution. Thanks in advance
st47661
Usually, the gradients become NaN first. The first two things to look at are a reduced learning rate and possibly gradient clipping. Best regards Thomas
st47662
Hi @tom Thanks for your reply. Can you also suggest how can I check if the gradients are becoming NaN first and also how can I ensure gradient clipping with a SGD or AdaGrad Optimizer. Thanks
st47663
I tried doing it. But how should I decide the mean and standard deviation for the operation? Thanks
st47664
You could use a normalization layer 2.2k. Alternatively, you can try dividing by some constant first (perhaps equal to the max value of your data?) The idea is to get the values low enough that they don’t cause really large gradients.
st47665
Have you tried the suggestions from this thread and is nothing working? If so, when do you see the first NaN value? Could you additionally check out input for NaN values?
st47666
Thanks for reply, none of the suggestion in this thread worked for me. Finally, I have solved my issue by your suggestion in another thread Getting Nan after first iteration with custom loss 3.5k .
st47667
Here is a way of debuging the nan problem. First, print your model gradients because there are likely to be nan in the first place. And then check the loss, and then check the input of your loss…Just follow the clue and you will find the bug resulting in nan problem. There are some useful infomation about why nan problem could happen: 1.the learning rate 2.sqrt(0) 3.ReLU->LeakyReLU