sub
stringclasses
4 values
title
stringlengths
3
304
selftext
stringlengths
3
30k
upvote_ratio
float64
0.07
1
id
stringlengths
9
9
created_utc
float64
1.6B
1.65B
pytorch
Square aliasing when converting padding conv2d Tensorflow to Pytorch
I'm trying to convert a Tensorflow program to Pytorch. It's deepdream with Laplacian normalisation from this [website](https://programmer.help/blogs/deep-dream-model-and-implementation.html). It seems to work except that when I use Laplacian Normalisation the output has these rectangular bands that I think come from the padding operation. Also the outputs do not quite match up. How can I convert operation such as: >tf.nn.conv2d(img, k5x5, \[1, 2, 2, 1\], 'SAME') and >tf.nn.conv2d\_transpose(lo, k5x5 \* 4, tf.shape(img), \[1, 2, 2, 1\]) to Pytorch? There might be other difference too. I've uploaded my full attempt [here](https://pastebin.com/Adsq19Kp)
1
t3_qwqx3h
1,637,245,715
pytorch
Hey, I'm trying to install Pytorch to my venv but it doesn't work. I've already installed numpy and opencv. Any Ideas why it happens?
nan
0.8
t3_qw6zzm
1,637,177,522
pytorch
Efficient way to get "neuron-edge-neuron" values in a neural network
I'm working on a visual networks project where I'm trying to plot several node-edge-node values in an interactive graph. I have several neural networks (this is one example): import torch import torch.nn as nn import torch.optim as optim class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.fc1 = nn.Linear(1, 2) self.fc2 = nn.Linear(2, 3) self.fc3 = nn.Linear(3, 1) def forward(self, x): x1 = self.fc1(x) x = torch.relu(x1) x2 = self.fc2(x) x = torch.relu(x2) x3 = self.fc3(x) return x3, x2, x1 net = Model() How can I get the node-edge-node (neuron-edge-neuron) values in the network in an efficient way? Some of these networks have a large number of parameters. Note that for the first layer it will be input-edge-neuron rather than neuron-edge-neuron. I tried saving each node values after the fc layers (ie x1,x2,x3) so I won't have to recompute them, but I'm not sure how to do the edges and match them to their corresponding neurons in an efficient way. The output I'm looking for is a list of lists of node-edge-node values. For example, in the above network from the first layer I will have 2 triples (1x2), from the 2nd layer I will have 6 of them (2x3), and in the last layer I will have 3 triples (3x1). The issue is matching nodes (ie neurons) values (one from layer n-1 and one from layer n) with the corresponding edges in an efficient way.
1
t3_qvra5u
1,637,124,454
pytorch
New paper out in Chaos, Solitons & Fractals: Forecasting of noisy chaotic systems with deep neural networks Project developed in PyTorch/Keras/Sklearn
nan
0.81
t3_qvjg6z
1,637,100,319
pytorch
Training time for IWSLT'14 De-En (Transformer)
Hi guys, I'm an ungrad student working in an NLP lab at my uni. I'm researching about NMT, and was told to replicate the implementation of the **Germany-to-English translation model** of fairseq ([link](https://github.com/pytorch/fairseq/blob/main/examples/translation/README.md#training-a-new-model)). I'm running it on colab free, with the K80 GPU and very limited memory. I copied and executed the code from the repo, and get about **15 min/epoch**, which made me can never complete training since the session always is timed out before I reach the final epoch. However, my advisor told me that it only takes **2-3 hrs** training on colab, so I want to double check the training time, because I really can't find what could go wrong. Thank you all. Cheers\~
1
t3_quiild
1,636,988,931
pytorch
How to install cuda version of pytorch with conda on WSL2?
Hi guys, I'm trying to install pytorch via conda on WSL2. I have done the necessary setup for WSL2 and the latest Nvidia WSL drivers. However when I try to install pytorch via conda as per the usual command `conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch` I keep getting the cpu-only version of pytorch. pytorch 1.10.0 py3.9_cpu_0 pytorch pytorch-mutex 1.0 cpu pytorch torchaudio 0.10.0 py39_cpu [cpuonly] pytorch torchvision 0.11.1 py39_cpu [cpuonly] pytorch Would anyone know how to get conda to pull the right packages? Thanks!
1
t3_qu822q
1,636,950,591
pytorch
A rather simple guide to start using PyTorch
PyTorch documentations in my opinion are too long and even scary for beginners. I decided to take the things I believe are important to make a very simple deep network and write a guide about it: [https://taying-cheng.medium.com/all-you-need-to-know-about-pytorch-a0ba3af897fa](https://taying-cheng.medium.com/all-you-need-to-know-about-pytorch-a0ba3af897fa)
0.94
t3_qtpivr
1,636,895,469
pytorch
[Linear Regression]
i tried to build a linear regression model with Pytorch with 1 input and 1 output but why is my loss function so big. This is my code: X_train # torch.Size([100, 1]) y_train # torch.Size([100, 1]) class LinearRegression(nn.Module): def __init__(self, input_dim, output_dim): super(LinearRegression, self).__init__() self.linear = nn.Linear(input_dim, output_dim) def forward(self, x): out = self.linear(x) return out input_size = X_train.shape[1] output_size = y_train.shape[1] model = LinearRegression(input_size, output_size) criterion = nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) num_epochs = 500 losses = [] for epoch in tqdm(range(num_epochs), desc="Training"): inputs = X_train target = y_train # forward out = model(inputs) loss = criterion(out, target) # backward optimizer.zero_grad() loss.backward() optimizer.step() #losses.append(loss.item()) if (epoch+1) % 50 == 0: params = list(model.parameters()) W = params[0].item() b = params[1].item() print(f'Epoch[{epoch+1}/{num_epochs}]\t loss: {loss.item():.4f}\t W: {W:.4f}\t b: {b:.4f}') losses.append(loss.item()) And this is my output : Epoch[50/500] loss: 1019.8797 W: 1.8125 b: 22.3726 Epoch[100/500] loss: 876.2048 W: 1.8125 b: 30.3922 Epoch[150/500] loss: 857.1508 W: 1.8125 b: 33.3127 Epoch[200/500] loss: 854.6238 W: 1.8125 b: 34.3763 Epoch[250/500] loss: 854.2888 W: 1.8125 b: 34.7636 Epoch[300/500] loss: 854.2443 W: 1.8125 b: 34.9047 Epoch[350/500] loss: 854.2385 W: 1.8125 b: 34.9560 Epoch[400/500] loss: 854.2375 W: 1.8125 b: 34.9747 Epoch[450/500] loss: 854.2375 W: 1.8125 b: 34.9815 Epoch[500/500] loss: 854.2375 W: 1.8125 b: 34.9840 Can anyone help me ? Thank you
0.71
t3_qtdth9
1,636,849,460
pytorch
Best scheme to evaluate dataset after training is done
I've built a logistic regression model with using torch (one linear layer and a sigmoid layer) two different weight initializations. Therefore I have 2 models with slight differences and I want to compare them with each other. I want to evaluate whether initializations are causing any large changes in the performance. So, I randomly select a chunk of the dataset and leave it out completely. Then, I split the remaining data into training and validation. I train the models using the training data, and I only use the validation data for early stopping. Once the training process stops, I find the models' performance on the left out test set. Next, I take the previous training and validation data, shuffle them, split them again, and train the models on the new training set and stop training using the new validation set. Then I collect the new trained models' performance on the same previous left out test set. I repeat this process 5 times, and I compare the average accuracies the two models returned on that test set. The method with higher mean accuracy and low stdev is the better one. I thought this process was called Monte Carlo cross validation. However, somebody told me vaguely this evaluation scheme was wrong - that I shouldn't be evaluating the same test set. There were no further explanations or comments so I cannot be sure whether to change my scheme or continue like this. Is the above method ideal to compare the two different models? Or should I use a completely different evaluation scheme? Any scheme recommendations or pointers?
0.92
t3_qsm2li
1,636,754,652
pytorch
How can I define the CUDA path when I use conda virtual environment?
Hello, I am using PyTorch 1.7 with CUDA 11. However, both PyTorch and CUDA are installed via anaconda. I'm trying to run a GitHub project and I need to build the project. In order to build for CUDA, I need to define the CUDA path. The problem occurs at this point. There is no CUDA outside the conda virtual environment (e.g., /usr/lib/cuda/). It is only available in the conda environment. However, since nvcc is not available in the conda version, the build process throws an error. Is there any suggestion? Project: [https://github.com/ddshan/hand\_object\_detector](https://github.com/ddshan/hand_object_detector) `/home/something/miniconda3/pkgs/cudatoolkit-11.0.221-h6bb024c_0/bin/nvcc: not found` I also asked the same question under r/CUDA I hope it is not a problem to ask the same question here. Thank you and best.
1
t3_qsfrl4
1,636,736,859
pytorch
Indirect Feedback Alignment (IFA) implementation
Can anyone please help me in implementing IFA algorithm from the paper: https://arxiv.org/abs/1609.01596 in this pytorch based repository called BioTorch: https://github.com/jsalbert/biotorch I understood the algorithm, but i am having really hard time in implementing the same. PLEASE HELP
0.88
t3_qqr4e3
1,636,538,859
pytorch
What is PyTorch Distributed - Distributed Deep Learning Model Training
nan
0.64
t3_qqb7y1
1,636,486,023
pytorch
How can I add values to a sparse matrix efficiently?
Hello, I'm trying to create an empty 4D sparse matrix, and add values to it after the creation of the matrix. I can't seem to find online how to do it, and the obvious way of a\[(index1, index2, index3, index4)\] doesn't work. Anyone got a solution for me?
0.88
t3_qpo3ny
1,636,408,055
pytorch
Mobile real-time GAN model
We have a product we want to move to real-time. It takes a src image and keypoints with a driving keypoints to create a new synthetic image. This is done in Python and it’s almost real-time. Are there good tutorials or approaches for speed optimization on mobile?
0.88
t3_qnxvu8
1,636,196,097
pytorch
PyTorch version - support for iOS
I am new to PyTorch framework and I have been looking at PyTorch [documentation](https://pytorch.org/mobile/home/). I am trying to find what iOS and Android versions are officially supported by PyTorch. However, I cannot get a clear picture of the compatibility matrix between PyTorch versions and mobile platforms. By digging into PyTorch's GitHub repo release branch, I could see PyTorch 1.9 supports iOS 12.0 as show [here](https://github.com/pytorch/pytorch/blob/orig/release%2F1.9/ios/LibTorch.podspec#L12). Similarly, it supports Android API 28 as shown [here](https://github.com/pytorch/pytorch/blob/v1.9.0/android/build.gradle#L5). Is my interpretation accurate? Would anyone be able to clarify? Thanks for the help.
1
t3_qnllo7
1,636,149,200
pytorch
PyTorch - batch training of multiple NN models
Does PyTorch have some kind of support for training multiple model instances in parallel? I want to implement an experiment where there are several agents in a shared environment, each having their own model weights and a shared model architecture, learning independently from their own set of observations. For this to work in parallel, I need to process a batch of observations using a batch of agent models. Is there support for this in PyTorch?
1
t3_qnki6j
1,636,145,950
pytorch
Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)
I have some problems when i try to run my inference.py. I tried to fix this error following similar topics but it’s still get this error. I tried to change version of pytorch to 1.4. then training but it's not running. This is my code from lib import * from l2_norm import L2Norm from default_box import DefBox import torch.nn.functional as F def create_vgg(): layers = [] in_channels = 3 cfgs = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'MC', 512, 512, 512, 'M', 512, 512, 512] for cfg in cfgs: if cfg == 'M': # floor layers += [nn.MaxPool2d(kernel_size=2, stride=2)] elif cfg == 'MC': # ceiling layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)] else: conv2d = nn.Conv2d(in_channels, cfg, kernel_size=3, padding=1) layers += [conv2d, nn.ReLU(inplace=True)] in_channels = cfg pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1) conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6) conv7 = nn.Conv2d(1024, 1024, kernel_size=1) layers += [pool5, conv6, nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)] return nn.ModuleList(layers) def create_extras(): layers = [] in_channels = 1024 cfgs = [256, 512, 128, 256, 128, 256, 128, 256] layers += [nn.Conv2d(in_channels, cfgs[0], kernel_size=1)] layers += [nn.Conv2d(cfgs[0], cfgs[1], kernel_size=3, stride=2, padding=1)] layers += [nn.Conv2d(cfgs[1], cfgs[2], kernel_size=1)] layers += [nn.Conv2d(cfgs[2], cfgs[3], kernel_size=3, stride=2, padding=1)] layers += [nn.Conv2d(cfgs[3], cfgs[4], kernel_size=1)] layers += [nn.Conv2d(cfgs[4], cfgs[5], kernel_size=3)] layers += [nn.Conv2d(cfgs[5], cfgs[6], kernel_size=1)] layers += [nn.Conv2d(cfgs[6], cfgs[7], kernel_size=3)] return nn.ModuleList(layers) def create_loc_conf(num_classes=1,bbox_aspect_num=[4, 6, 6, 6, 4, 4]): loc_layers = [] conf_layers = [] # source1 # loc loc_layers += [nn.Conv2d(512, bbox_aspect_num[0] * 4, kernel_size = 3, padding=1)] # conf conf_layers += [nn.Conv2d(512, bbox_aspect_num[0] * num_classes, kernel_size=3, padding=1)] # source2 # loc loc_layers += [nn.Conv2d(1024, bbox_aspect_num[1] * 4, kernel_size=3, padding=1)] # conf conf_layers += [nn.Conv2d(1024, bbox_aspect_num[1] * num_classes, kernel_size=3, padding=1)] # source3 # loc loc_layers += [nn.Conv2d(512, bbox_aspect_num[2] * 4, kernel_size=3, padding=1)] # conf conf_layers += [nn.Conv2d(512, bbox_aspect_num[2] * num_classes, kernel_size=3, padding=1)] # source4 # loc loc_layers += [nn.Conv2d(256, bbox_aspect_num[3] * 4, kernel_size=3, padding=1)] # conf conf_layers += [nn.Conv2d(256, bbox_aspect_num[3] * num_classes, kernel_size=3, padding=1)] # source5 # loc loc_layers += [nn.Conv2d(256, bbox_aspect_num[4] * 4, kernel_size=3, padding=1)] # conf conf_layers += [nn.Conv2d(256, bbox_aspect_num[4] * num_classes, kernel_size=3, padding=1)] # source6 # loc loc_layers += [nn.Conv2d(256, bbox_aspect_num[5] * 4, kernel_size=3, padding=1)] # conf conf_layers += [nn.Conv2d(256, bbox_aspect_num[5] * num_classes, kernel_size=3, padding=1)] return nn.ModuleList(loc_layers), nn.ModuleList(conf_layers) cfg = { "num_classes" : 2, #we only have 1 class: fire "input_size" : 300, #SSD 300 "bbox_aspect_num" : [4, 6, 6, 6, 4, 4], # ty le cho source 1 -> 6 "feature_maps" : [38, 19, 10, 5, 3, 1], "steps" : [8, 16, 32, 64, 100, 300], # Size of default box "min_size" : [30, 60, 111, 162, 213, 264], "max_size" : [60, 111, 162, 213, 264, 315], "aspect_ratios" : [[2], [2, 3], [2, 3], [2, 3], [2], [2]] } class SSD(nn.Module): def __init__(self, phase, cfg): super(SSD, self).__init__() self.phase = phase self.num_classes = cfg['num_classes'] # Create main modules self.vgg = create_vgg() self.extras = create_extras() self.loc, self.conf = create_loc_conf(cfg['num_classes'], cfg['bbox_aspect_num']) self.L2Norm = L2Norm() # Create default box dbox = DefBox(cfg) self.dbox_list = dbox.create_defbox() if phase == "inference": self.detect = Detect() def forward(self, x): sources = list() loc = list() conf = list() for k in range(23): x = self.vgg[k](x) # source 1 source1 = self.L2Norm(x) sources.append(source1) for k in range(23, len(self.vgg)): x = self.vgg[k](x) # source 2 sources.append(x) # source 3-6 for k, v in enumerate(self.extras): x = F.relu(v(x), inplace = True) if k % 2 == 1: sources.append(x) for (x, l, c) in zip(sources, self.loc, self.conf): # Data có dạng (batch_size, 4*aspect_ratio_num, featuremap_height, featuremap_width) # aspect_ratio_num = 4, 6, ... # -> (batch_size, featuremap_height, featuremap_width, 4*aspect_ratio_num) loc.append(l(x).permute(0, 2, 3, 1).contiguous()) conf.append(c(x).permute(0, 2, 3, 1).contiguous()) loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1) #(batch_size, 34928) conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1) # (btach_size, 8732) loc = loc.view(loc.size(0), -1, 4) # (batch_size, 8732, 4) conf = conf.view(conf.size(0), -1, self.num_classes) # (batch_size, 8732, 2) output = (loc, conf, self.dbox_list) if self.phase == "inference": return self.detect(output[0], output[1], output[2]) else: return output def decode(loc, defbox_list): ''' loc: [8732, 4] (delta_x, delta_y, delta_w, delta_h) defbox_list: [8732, 4] (cx_d, cy_d, w_d, h_d) returns: boxes[xmin, ymin, xmax, ymax] ''' boxes = torch.cat((defbox_list[:, :2] + loc[:, :2]*defbox_list[:, 2:]), defbox_list[:, 2:] * torch.exp(loc[:, 2:] * 0.2), dim = 1) boxes[:, :2] -= boxes[:, 2:] / 2 # calculate x_min, y_min boxes[:, 2:] += boxes[:, :2] / 2 # calculate x_max, y_max return boxes def nms(boxes, scores, overlap = 0.45, top_k = 200): """ boxes: [num_box, 4] # có 8732 num_box scores: [num_box] """ count = 0 keep = scores.new(scores.size(0)).zero_().long() # boxes: x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] # boxes area area = torch.mul(x2 - x1, y2 - y1) tmp_x1 = boxes.new() tmp_y1 = boxes.new() tmp_x2 = boxes.new() tmp_y2 = boxes.new() tmp_w = boxes.new() tmp_h = boxes.new() value, idx = scores.sort(0) idx = idx[-top_k:] # lấy 200 cái bdbox có độ tự tin cao nhất while idx.numel() > 0: i = idx[-1] # id của box có độ tự tin cao nhất keep[count] = i count += 1 if id.size(0) == 1: break idx = idx[:, -1] # id của các boxes ngoại trừ box có độ tự tin cao nhất #information boxes torch.index_select(x1, 0, idx, out = tmp_x1) # lấy ra những thằng có gt trong khoảng idx trong x1 torch.index_select(y1, 0, idx, out = tmp_y1) torch.index_select(x2, 0, idx, out = tmp_x2) torch.index_select(y2, 0, idx, out = tmp_y2) tmp_x1 = torch.clamp(tmp_x1, min = x1[i]) # = x1[i] nếu tmp_x1 < x[i] tmp_y1 = torch.clamp(tmp_y1, min = y1[i]) tmp_x2 = torch.clamp(tmp_x2, max = x2[i]) tmp_y2 = torch.clamp(tmp_y2, max = y2[i]) # = y2[i] nếu tmp_y2 > y2[i] # chuyển về tensor có size sao cho index giảm đi 1 tmp_w.resize_as_(tmp_x2) tmp_h.resize_as_(tmp_y2) tmp_w = tmp_x2 - tmp_x1 tmp_h = tmp_y2 - tmp_y1 tmp_w = torch.clamp(tmp_w, min = 0.0) # đưa phần tử < 0 về 0 tmp_h = torch.clamp(tmp_h, min = 0.0) # dien tich overlap inter = tmp_w * tmp_h # dien tich phan trung nhau others_area = torch.index_select(area, 0, idx) # dien tich cua cac bbox con lai union = area[i] + others_area - inter iou = inter / union idx = idx[iou.le(overlap)] # giu cac box co idx nho hon 0.45 return keep, count class Detect(Function): def __init__(self, conf_thresh = 0.01, top_k = 200, nms_thresh = 0.45): self.softmax = nn.Softmax(dim = -1) self.conf_thresh = conf_thresh self.top_k = top_k self.nms_thresh = nms_thresh @staticmethod def forward(self, loc_data, conf_data, dbox_list): num_batch = loc_data.size(0) num_dbox = loc_data.size(1) # tra ve 8732 dbox num_class = conf_data.size(2) # tra ve so class la 1 conf_data = self.softmax(conf_data) # tinh xac suat, dang co dinh dang (btach_num, 8732, 1) conf_preds = conf_data.transpose(2,1) # thanh (batch_num, num_class, num_dbox) output = torch.zeros(num_batch, num_class, self.top_k, 5) #xu li tung anh trong 1 batch for i in range(num_batch): # tinh bbox tu offset information va default box decode_boxes = decode(loc_data[i], dbox_list) # copy conf score cua anh thu i conf_scores = conf_preds[i].clone() for cl in range(1, num_class): c_mask = conf_preds[cl].gt(self.conf_thresh) # chi lay nhung conf > 0.01 scores = conf_preds[cl][c_mask] # CHỖ NÀY CẦN XEM LẠI if scores.nelement() == 0: # numel continue l_mask = c_mask.unsqueeze(1).expand_as(decode_boxes) # để đưa chiều về giống chiều của decode_box boxes = decode_boxes[l_mask].view(-1, 4) ids, count = nms(boxes, scores, self.nms_thresh, self.top_k) output[i, cl, :count] = torch.cat((scores[ids[:count]].unsqueeze(1), boxes[ids[:count]]), 1) return output if __name__ == "__main__": # vgg = create_vgg() # print(vgg) extras = create_extras() print(extras) loc, conf = create_loc_conf() print(loc) print(conf) ssd = SSD(phase="train", cfg=cfg) print(ssd) and this is [inference.py](https://inference.py) from lib import * from model import SSD from transform import DataTransform classes = ["fire"] cfg = { "num_classes": 2, #VOC data include 20 class + 1 background class "input_size": 300, #SSD300 "bbox_aspect_num": [4, 6, 6, 6, 4, 4], # Tỷ lệ khung hình cho source1->source6` "feature_maps": [38, 19, 10, 5, 3, 1], "steps": [8, 16, 32, 64, 100, 300], # Size of default box "min_size": [30, 60, 111, 162, 213, 264], # Size of default box "max_size": [60, 111, 162, 213, 264, 315], # Size of default box "aspect_ratios": [[2], [2,3], [2,3], [2,3], [2], [2]] } net = SSD(phase="inference", cfg=cfg) net_weights = torch.load("./weights/ssd300_20.pth", map_location={"cuda:0":"cpu"}) net.load_state_dict(net_weights) def predict(img_file_path): img = cv2.imread(img_file_path) color_mean = (8, 17, 32) input_size = 300 transform = DataTransform(input_size, color_mean) phase = "val" img_tranformed, boxes, labels = transform(img, phase, "", "") img_tensor = torch.from_numpy(img_tranformed[:,:,(2,1,0)]).permute(2,0,1) net.eval() inputs = img_tensor.unsqueeze(0) #(1, 3, 300, 300) output = net(inputs) plt.figure(figsize=(10, 10)) colors = [(255,0,0), (0,255,0), (0,0,255)] font = cv2.FONT_HERSHEY_SIMPLEX detections = output.data #(1, 21, 200, 5) 5: score, cx, cy, w, h scale = torch.Tensor(img.shape[1::-1]).repeat(2) for i in range(detections.size(1)): j = 0 while detections[0, i, j, 0] >= 0.6: score = detections[0, i, j, 0] pt = (detections[0, i, j, 1:]*scale).cpu().numpy() cv2.rectangle(img, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), colors[i%3], 2 ) display_text = "%s: %.2f"%(classes[i-1], score) cv2.putText(img, display_text, (int(pt[0]), int(pt[1])), font, 0.5, (255, 255, 255), 1, cv2.LINE_AA) j += 1 cv2.imshow("Result", img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": img_file_path = "/home/huynth/ImageProcessing/result/Median.jpg" predict(img_file_path) Please help me . Thank you !!!
1
t3_qn6b9o
1,636,099,839
pytorch
Complex(?) connected NN possible?
Is it possible to create the Network from the picture below in pytorch, and if yes how do I do it. I know that I can omit connections by using a sparse matrix for the weights, but can I create a connection / a weight that skips a layer? ​ https://preview.redd.it/6zb4g9ix8lx71.png?width=640&format=png&auto=webp&s=c3785a6e41b40bec3b3097a3d7b5912ebd25f2c3
1
t3_qmlqrp
1,636,035,922
pytorch
Easy Multi-Node PyTorch Lightning Training
nan
1
t3_qm2xcs
1,635,969,872
pytorch
iris - Open Source Photos Platform powered by PyTorch
This is my submission for PyTorch Annual Hackathon 2021! YouTube: [https://www.youtube.com/watch?v=ZMG2rohochc](https://www.youtube.com/watch?v=ZMG2rohochc) DevPost: [https://devpost.com/software/iris-7s3yna](https://devpost.com/software/iris-7s3yna) GitHub: [https://github.com/prabhuomkar/iris](https://github.com/prabhuomkar/iris)
1
t3_qlzy1g
1,635,961,619
pytorch
What softwares/applications do I need to train an audio classifier model in Windows using Python and Pytorch?
I'm new with all these, so please let me know how to get started with the softwares.
0.57
t3_qlosjg
1,635,922,283
pytorch
Help with custom forward function involving nn.Conv2d()
I have an issue with [custom forward function involving nn.Conv2d()](https://github.com/promach/gdas/blob/main/gdas.py#L119) I found that whenever `e` is 0 , [combined\_feature\_map](https://github.com/promach/gdas/blob/main/gdas.py#L375) will also become 0. Why ? Note: When [e is 0](https://github.com/promach/gdas/blob/main/gdas.py#L174), it actually uses `ConvEdge` class https://preview.redd.it/fz24qg69hax71.png?width=1922&format=png&auto=webp&s=c3a6b215e1bba8464772d833ad2fbc9b8e161873
1
t3_qlkge0
1,635,905,836
pytorch
How to install PyTorch using m1 max macbook pro?
​ ​ relatedn refs: \- [https://github.com/pytorch/pytorch/issues/47702](https://github.com/pytorch/pytorch/issues/47702) \- [https://towardsdatascience.com/yes-you-can-run-pytorch-natively-on-m1-macbooks-and-heres-how-35d2eaa07a83](https://towardsdatascience.com/yes-you-can-run-pytorch-natively-on-m1-macbooks-and-heres-how-35d2eaa07a83) \- [https://www.quora.com/unanswered/How-does-one-use-PyTorch-with-the-MacBook-pro-M1-Max-or-M1-Pro-for-Deep-Learning](https://www.quora.com/unanswered/How-does-one-use-PyTorch-with-the-MacBook-pro-M1-Max-or-M1-Pro-for-Deep-Learning)
0.75
t3_qkmvpr
1,635,798,200
pytorch
Feature Extraction in TorchVision using Torch FX (official pytorch blog)
nan
1
t3_qki1q1
1,635,785,058
pytorch
Accelerating PyTorch with CUDA Graphs (official pytorch blog)
nan
1
t3_qki14b
1,635,785,015
pytorch
Can I SLI load big (>11gb) models?
New BERT/pytorch user here, dreaming of utilizing larger models. I have access to the hardware, but before I embark on the journey of putting it all together I need to know, is such a thing possible? If not what's the point of these mammoth 4x GPU workstations I see online? Staggered training cycles? Something else? Thank you for your insight, and consideration.
1
t3_qk25dw
1,635,725,508
pytorch
Stability of updating shared layers in two step multi-head update?
nan
1
t3_qjjoft
1,635,661,641
pytorch
How to handle dimension changes between layers
Let's say I have an embedding layer, followed by a linear layer, and I use sigmoid at the end to convert logits to classes. class SimpleClassifier(nn.Module): def __init__(self, vocab_size, num_labels, embedding_dim = 32): super(SimpleClassifier, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.linear = nn.Linear(embedding_dim, num_labels) def forward(self, x): embed = self.embedding(x) out = self.linear(embed) return torch.sigmoid(out) x has the size: \[batch size, num of words\] after passing x through the embedding layer, embed has the size \[batch size, num of words, embedding\_dim\] passing embed through the linear layer, out has the size \[batch size, num of words, num\_labels\] What confuses me is: Wasn't the num of words supposed to be replaced by the embedding\_dim instead? I would expect embed to have the size \[batch size, embedding\_dim\] instead. The online tutorials which are using the same type of input x are using the above code framework without doing any additional dimension removal or reshaping, and getting the typical 2D results they want. What seems to be wrong here in the above code?
1
t3_qj1s0y
1,635,601,465
pytorch
PyTorch Tutor
Looking for a PyTorch SME to teach and advise me.
0.6
t3_qizh3h
1,635,592,872
pytorch
Need help with examples of errors
Hello, I’m working on my project related to Pytorch debugging. Could someone help me with examples of problems for the following issues? Thanks so much 🙏 Here are the issues: Attempting to construct a nn.Module inside TorchScript. This currently errors out because TorchScript would attempt to compile __init__() method of module, which usually contains a call to super(), which isn't supported. Instead, TS should really recognize that a call to constructor of nn.Module is the real problem. Calling into known torch.* components that are not scriptable. For example, torch.distributions currently is not scriptable. If TS sees a call into torch.distributions methods, it should warn users about it and prompt them to use jit.trace instead. Registering new buffers. This isn't supported because it is effectively modifying type of nn.Module. We should also give a better error message here.
1
t3_qitvff
1,635,567,825
pytorch
Ideas for avoiding overfitting in simple logistic regression
I have a simple logistic regression equivalent classifier (I got it from online tutorials): ​ class MyClassifier(nn.Module): def __init__(self, num_labels, vocab_size): super(MyClassifier, self).__init__() self.num_labels = num_labels self.linear = nn.Linear(vocab_size, num_labels) def forward(self, input_): return F.log_softmax(self.linear(input_), dim=1) Single there is only one layer, using dropout is not one of the options to reduce overfitting. My parameters and the loss/optimization functions are: learning_rate = 0.01 num_epochs = 5 criterion = nn.CrossEntropyLoss(weight = class_weights) optimizer = optim.Adam(model.parameters(), lr = learning_rate) I need to mention that my training data is imbalanced, that's why I'm using class\_weights. My training epochs are returning me these (I compute validation performance at every epoch as for the tradition): ​ Total Number of parameters: 98128 Epoch 1 train_loss : 8.941093041900183 val_loss : 9.984430663749626 train_accuracy : 0.6076273690389963 val_accuracy : 0.6575908660222202 ================================================== Epoch 2 train_loss : 8.115481783001984 val_loss : 11.780701822734605 train_accuracy : 0.6991507896001001 val_accuracy : 0.6662275931342518 ================================================== Epoch 3 train_loss : 8.045773667609911 val_loss : 13.179592760197878 train_accuracy : 0.7191923984562909 val_accuracy : 0.6701144928772814 ================================================== Epoch 4 train_loss : 8.059769958938631 val_loss : 14.473802320314771 train_accuracy : 0.731468294135531 val_accuracy : 0.6711249543086926 ================================================== Epoch 5 train_loss : 8.015543553590438 val_loss : 15.829670974340084 train_accuracy : 0.7383795859902959 val_accuracy : 0.6727273308589589 ================================================== Plots are: ​ https://preview.redd.it/1z09912otew71.png?width=1159&format=png&auto=webp&s=d2a37e322198e7c2337c00210dd990e9994867d4 The validation loss tells me that we're overfitting, right? How can I prevent that from happening, so I can trust the actual classification results this trained model returns me?
1
t3_qifpeo
1,635,522,245
pytorch
Custom lib or pytorch build with la pack
Hey guys, ​ I am trying to transfer a model from python to ios. To do this I used jit and it actually seems to work very easily. The only part was the model fails looking for the LA package built in. I am not sure if this is built into the jit package or built into the libtorch package to compile for ios. Can these builds be done on M1 or regular macs? I am not totally sure the process for adding the LApack to the build so it is included. Nor am I sure weather original pytorch needs lapack for the jit compile or if it's libtorch. Any insights or step by steps would be very helpful as I haven't done a custom build before so I am not sure what I am doing wrong.
1
t3_qiato5
1,635,507,388
pytorch
Best textbooks for learning Pytorch and NLP
I am moving towards Pytorch from Keras and I like it a lot! Does anyone have any recommendations for textbooks that do a good job of covering NLP in pytorch?
0.81
t3_qi4weu
1,635,482,626
pytorch
How to debug dimension errors? Pytorch newb here
Hello, I’m new to pytorch. I tried to implement a basic GAN and was running into errors like “stack expects each tensor to be equal size, but got [3, 784, 812] at entry 0 and [3, 960, 784] at entry 1” It seems like these are dimension errors as data passes through my layers. Does anyone know how to debug stuff like this? Just print out tensor shapes? ` ` class Discriminator(nn.Module):     def __init__(self, img_dim):         super().__init__()         self.disc = nn.Sequential(             nn.Linear(img_dim, 256),             nn.LeakyReLU(0.2),             nn.Linear(256, 128),             nn.LeakyReLU(0.2),             nn.Linear(128, 64),             nn.LeakyReLU(0.2),             nn.Linear(64, 1),             nn.Sigmoid()         )     def forward(self, x):         return self.disc(x) class Generator(nn.Module):     def __init__(self, z_dim, img_dim):         super().__init__()         self.gen = nn.Sequential(             nn.Linear(z_dim, 64),             nn.LeakyReLU(0.2),             nn.Linear(64, 128),             nn.LeakyReLU(0.2),             nn.Linear(128, 256),             nn.LeakyReLU(0.2),             nn.Linear(256, img_dim),             nn.Tanh()         )     def forward(self, x):         return self.gen(x) ` `
1
t3_qheck7
1,635,393,322
pytorch
Getting Latent Values in CNN Autoencoder
Hi all. I've created a CNN Autoencoder in the form of a class as such (I wanted to make it as flexible as possible so I can pass all sorts of configurations to it): ``` import sys import os import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader import numpy as np sys.path.append(os.path.join(os.path.dirname(__file__), '.')) from abstract_dataset import AbstractDataset class CnnAutoencoder(nn.Module): def __init__(self, scale=2, channel_maps=[], padding=1, kernel_size=3, num_channels=3, img_width=500, img_height=500, device=torch.device("cpu"), criterion=nn.BCELoss(), h_activation="relu", o_activation="sigmoid"): super().__init__() self.scale = scale self.channel_maps = channel_maps self.padding = padding self.kernel_size = kernel_size self.num_channels = num_channels self.img_width = img_width self.img_height = img_height self.device = device self.criterion = criterion self.h_activation = h_activation self.o_activation = o_activation self.reversed_channel_maps = list(reversed(channel_maps)) # Build convolutional layers self.convolutional_layers = nn.ModuleList([]) for i in range(len(self.channel_maps) - 1): self.convolutional_layers.append( nn.Conv2d( self.channel_maps[i], self.channel_maps[i+1], kernel_size=self.kernel_size, padding=self.padding ) ) # Build deconvolutional layers self.deconvolutional_layers = nn.ModuleList([]) for i in range(len(self.reversed_channel_maps) - 1): self.deconvolutional_layers.append( nn.ConvTranspose2d( self.reversed_channel_maps[i], self.reversed_channel_maps[i+1], kernel_size=self.kernel_size, padding=self.padding ) ) self.pool = nn.MaxPool2d(2, 2) self.criterion = criterion self.errs = [] # Initialize model to device self.to(self.device) def conv(self, x): for i in range(len(self.convolutional_layers)): conv_layer = self.convolutional_layers[i] if self.h_activation == "relu": x = F.relu(conv_layer(x)) else: raise Exception("Invalid hidden activation {}".format(self.h_activation)) x = self.pool(x) return x def deconv(self, x): for i in range(len(self.deconvolutional_layers)): deconv_layer = self.deconvolutional_layers[i] x = F.interpolate(x, scale_factor=self.scale, mode='nearest') x = deconv_layer(x) if i != len(self.deconvolutional_layers) - 1: if self.h_activation == "relu": x = F.relu(x) else: raise Exception("Invalid hidden activation {}".format(self.h_activation)) else: if self.o_activation == "sigmoid": x = torch.sigmoid(x) else: raise Exception("Invalid output activation {}".format(self.o_activation)) return x def encode(self, x): x = self.conv(x) x = x.view(x.size()[0], -1) return x def forward(self, x): x = self.conv(x) x = self.deconv(x) return x def errors(self, x): x_hat = self.forward(x) self.criterion.reduction = 'none' dim = self.num_channels * self.img_width * self.img_height err = self.criterion(x_hat.view(-1, dim), x_hat.view(-1, dim)).mean(axis=1) self.criterion.reduction = 'mean' return err.detach().cpu().numpy() def save(self, filename): state = { 'params': { 'o_activation': self.o_activation, 'h_activation': self.h_activation, 'channel_maps': self.channel_maps, 'device': self.device, 'scale': self.scale, 'padding': self.padding, 'kernel_size': self.kernel_size, 'num_channels': self.num_channels, 'img_width': self.img_width, 'img_height': self.img_height }, 'state_dict': self.state_dict(), 'optimizer': self.optimizer.state_dict() } torch.save(state, filename) def load(self, filename): state = torch.load(filename) self.load_state_dict(state['state_dict']) self.optimizer = state['optimizer'] # other parameters params = state['params'] self.o_activation = params['o_activation'] self.h_activation = params['h_activation'] self.channel_maps = params['channel_maps'] self.device = params['device'] self.scale = params['scale'] self.padding = params['padding'] self.kernel_size = params['kernel_size'] self.num_channels = params['num_channels'] self.img_width = params['img_width'] self.img_height = params['img_height'] def fit(self, x, epochs=100, lr=0.001, batch_size=5, optimizer_type="adam"): # Reset errors to empty list self.errs = [] data = AbstractDataset(x) dataloader = DataLoader(dataset=data, batch_size=batch_size, shuffle=True, drop_last=False) if optimizer_type == "adam": self.optimizer = optim.Adam(self.parameters(), lr=lr) else: raise Exception("Invalid optimizer_type: {}".format(optimizer_type)) num_iterations = len(x) / batch_size for epoch in range(epochs): curr_loss = 0 for i, (inputs, labels) in enumerate(dataloader): inputs, labels = inputs.to(self.device), labels.to(self.device) self.optimizer.zero_grad() output = self.forward(inputs) loss = self.criterion(output, labels) curr_loss += loss loss.backward() self.optimizer.step() curr_loss = curr_loss / num_iterations print("Epoch: %i\tLoss: %0.5f" % (epoch + 1, curr_loss.item())) self.errs.append(curr_loss.detach()) ``` My question is, since I don't use a LinearLayer after convolution, if I wanted to get a vector of features in a latent layer, I would have to perform the `encode` method: ``` def encode(self, x): x = self.conv(x) x = x.view(x.size()[0], -1) return x ``` It seems to be churning out correct values but I can't validate if it really is the correct ones. I just saw the code for `x.view(x.size()[0], -1)` somewhere in the forum but not sure what it does exactly. Or is this the proper way to extract latent layer values off of a CNN Autoencoder? Thanks
1
t3_qei3ry
1,635,038,822
pytorch
Receiving strange results for different batch sizes
I've implemented a simple logistic regression using pytorch as follows: class MyClassifier(nn.Module): def __init__(self, num_labels, feat_size): super(MyClassifier, self).__init__() self.linear = nn.Linear(feat_size, num_labels) def forward(self, input_): output = self.linear(input_) return output where my data is quite imbalanced. I didn't add a softmax layer to the end because I use the following: criterion = nn.CrossEntropyLoss(weight = class_weights) optimizer = optim.Adam(model.parameters(), lr = learning_rate) People were saying that CrossEntropyLoss would handle the softmax and the class weights I provide it should handle the imbalance during training. To compute the accuracy score, I use balanced\_accuracy of sklearn API. Under these circumstances, when my batch\_size is 128, I get the following results: Epoch 1 train_loss : 6.7878759426243205 val_loss : 7.433685937243139 train_accuracy : 0.4824034467755402 val_accuracy : 0.5251206026233478 ================================================== Epoch 2 train_loss : 5.99113222517245 val_loss : 8.959181152985904 train_accuracy : 0.5581671699259839 val_accuracy : 0.5300979308675885 ================================================== Epoch 3 train_loss : 5.8957389833456055 val_loss : 10.008684014987372 train_accuracy : 0.5725333115680177 val_accuracy : 0.5301676217747785 ================================================== Epoch 4 train_loss : 5.817642052350575 val_loss : 11.025033701397852 train_accuracy : 0.5853522987236132 val_accuracy : 0.5307039362469957 ================================================== Epoch 5 train_loss : 5.831438742645287 val_loss : 11.798206594042883 train_accuracy : 0.5896608333837227 val_accuracy : 0.5351319280522936 ================================================== ​ https://preview.redd.it/xfzf0lle2av71.png?width=1169&format=png&auto=webp&s=cf93d2509118c5ee59b54a37ff2b277f7108bc47 And when I run the trained model on the validation data after training is done, I get 0.685 balanced\_accuracy and confusion matrix looks like this: ​ https://preview.redd.it/jz0xw7en2av71.png?width=820&format=png&auto=webp&s=dc120a7cb676bcf4d58e3fd8d2522d1b05e8ecbf When I decrease the batch\_size to 72 so my ordinary laptop can handle this process faster on CPU (M1 chips aren't compatible with GPU support of torch unfortunately): Epoch 1 train_loss : 8.682287086720864 val_loss : 9.941184375842502 train_accuracy : 0.8459006809094946 val_accuracy : 0.912647343814439 ================================================== Epoch 2 train_loss : 8.064770712704517 val_loss : 11.877306490363774 train_accuracy : 0.9746633731419807 val_accuracy : 0.9292273581396854 ================================================== Epoch 3 train_loss : 8.081744464227276 val_loss : 13.33639626492239 train_accuracy : 0.9971578027592517 val_accuracy : 0.9340779315955289 ================================================== Epoch 4 train_loss : 8.06064057003796 val_loss : 14.592282639012128 train_accuracy : 1.0152058255637395 val_accuracy : 0.9428616279166708 ================================================== Epoch 5 train_loss : 7.995261219761772 val_loss : 15.561377628814542 train_accuracy : 1.0273957155370776 val_accuracy : 0.9351828058506229 ================================================== https://preview.redd.it/vrth9l9ow9v71.png?width=1178&format=png&auto=webp&s=1f1b9115df1c60ef6bc97a63be3ea0456da713f9 When I run this one on the validation set after training is over, I get a very similar balanced accuracy (also 0.68) and a similar (not the same but very close) confusion matrix. The question is, how come there is such a huge gap between the balanced accuracy results I get during the training epochs for two different batch sizes but similar results after training is done? Also, why do the loss values of validation and training look so off? The results are way too off compared to the reasonable balanced accuracy values I get after training is done, regardless of the batch size. I'm having a hard time explaining or understanding these results and will appreciate any guidance.
1
t3_qefee1
1,635,029,291
pytorch
Introducing PyTorch-DirectML: Train your machine learning models on any GPU
nan
0.97
t3_qe4als
1,634,993,324
pytorch
Traditional Machine Learning Models on GPU
I've just published a new major revision of a library I've been working on, [PyCave](https://github.com/borchero/pycave). It implements K-Means, GMMs and Markov chains using PyTorch and PyTorch Lightning, thus, enabling to train these models on GPUs and multiple nodes (and even TPUs). At the same time, the interface of the library is fully compatible with scikit-learn, making it a drop-in replacement. For example, you can run the following, to train a GMM on a GPU, gaining a \~100x speedup over scikit-learn. from pycave.bayes import GaussianMixture gmm = GaussianMixture(4, covariance_type="diag", trainer_params=dict(gpus=1)) gmm.fit(data) I'd be delighted if any of you can make use of this work! :) Of course, I also highly value any feedback ;)
1
t3_qdm98s
1,634,924,857
pytorch
PyTorch Python to mobile
So I need to move some models and modules from Python to objective c to run real-time on a phone: I’ve got the models given to me in pt format which loads a dictionary of the states dictionaries. Just wondering if I am doing this right. I converted the PyTorch save to PyTorch light and did a hit load. But I am not seeing the dictionary like in Python. In Python I just torch.load and can access the dictionary of the generator. What might I be missing?
0.75
t3_qdm5e4
1,634,924,543
pytorch
Validate models after storing the training model of each epoch?
Can we first store the training model state dict of each epoch, then validate models and plot validation loss curve by importing each epoch state dict? If yes, is this way recommended? The issue is that we are training some model variants and we don’t want to waste time on validation until we figure out the best model.
1
t3_qdd07x
1,634,894,017
pytorch
How can I create a loss function that will push the actual NN weights to move?
I'm trying to create a loss function that takes the actual weight values into account: loss = 1 - torch.mean(torch.tensor([torch.sum(w_arr) for w_arr in net.parameters()])) Where "net" is just a simple FC network with any number of layers. But I'm getting an error: RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn The goal here is to get each weight's value closest to 1 (or any other value) as possible.
1
t3_qd94ww
1,634,876,428
pytorch
Text recognition and creation
I'm wondering if there are existing algorithms to perform text recognition based on an existing catalog and a means to feed the algorithm text and have it generate dialogue based on the training data? In my example I have dialogue for characters in a movie or TV show. I have training sets for each character, but can't figure out how to train my set to recognize dialogue or classify dialogue to a specific character. I then want to feed an input of dialogue and say return the same sentence as if a particular person spoke it. Does this exist in some form?
1
t3_qd4wr1
1,634,861,356
pytorch
PyTorch 1.10 Release, including CUDA Graphs APIs, Frontend and Compiler Improvements
nan
1
t3_qcypb3
1,634,842,466
pytorch
Am I understanding CUDA Streams and Events correctly?
I want to exploit some parallelism in the custom model I've built and submit asynchronous kernels to CUDA which execute in parallel. Say I have a ModuleList full of operations which are fully independent of each other but which require the same input. The results of those operations are later collated into a single object to be passed on in the forward pass. Below is a minimally illustrative example of how I *think* streams and events are used. from torch.cuda import Stream, stream, Event from torch import empty def func(x, module_list): out = empty(len(module_list), device=module_list[0].device) event = Event() for i, module in enumerate(module_list): s = Stream() s.wait_event(event) with stream(s): out[i] = module(x) # this is not executed yet because of the wait_event() call event.record() # all jobs begin # work actually happens here event.synchronize() # wait until all jobs end return out # out is guaranteed to be filled with all results from above My understanding here is that the streams which are waiting on an event which has not been recorded will submit their work to the queue but will not run yet. Only once `event.record()` is called are those queued jobs executed. Then `event.synchronize()` tells the parent stream to wait until all those jobs are completed. Will `func()` do what I want?
1
t3_qcxkvp
1,634,839,249
pytorch
Example models
I am wondering if there is a resource for sample models in pytorch. Basically showing different net architectures and how to use various layers. I am hoping for some more complex ones. Thanks,
1
t3_qcvk5d
1,634,833,506
pytorch
Looking out for Under 18 PyTorch Developers
I am Devvrat from FleishmanHillard, we are one of the communication partners of Facebook. Together, we are working on a program in India for which we are identifying young developers under the age of 18 who have worked on PyTorch. If you are/know someone who is under the age of 18, in India and has worked on PyTorch, please recommend or do get in touch. You can contact me at [email protected]
0.27
t3_qcmcnb
1,634,801,477
pytorch
PyTorch System Requirements
I've looked around a fair bit and I don't see any solid documentation on what the system requirements are to run PyTorch. I'm mainly interested in the amount of RAM it needs to run. I'm speculating that it is at least 8GB of RAM. Any input or links are appreciated. Thank you.
1
t3_qcdaz6
1,634,770,579
pytorch
Vision Transformers in PyTorch
This is a simple explanation of vision transformers and how to incorporate them into your programs via PyTorch: [https://taying-cheng.medium.com/vision-transformers-in-pytorch-43d13cb7ec7a](https://taying-cheng.medium.com/vision-transformers-in-pytorch-43d13cb7ec7a)
1
t3_qcd0za
1,634,769,738
pytorch
GDAS paper : Searching for A Robust Neural Architecture in Four GPU Hours
nan
0.8
t3_qbzik6
1,634,732,297
pytorch
Derivatives in the loss function and losing the graph.
Hello all, I'm a bit of a beginner at Machine Learning and PyTorch and have run into an issue that I have not been able to solve. ## Background This is in the area of solving Bellman Equations from dynamic programming, although I don't think much much background is needed in that, based on the problem I am having. I am currently trying to use pytorch to approximate a choice/policy function that is implicitly defined by a system of functions, and the derivatives of those functions. ## Problem Description When I try to construct a loss function, I lose the `requires_grad` attribute that I need for backprop/training. In (what might be excessive) detail: Basically there are 4 fundamental (tensor) functions I need to work with. - Policy Function: states -> choices - Transition Function, G: states, choices -> states - Benefit function P: states, choices -> a measure of benefit I need to use derivatives of the transition G() and benefit P() functions to define the residuals of the model. When I try to take the derivative of P() or G() using `torch.autograd.functional.jacobian` (or `torch.autograd.grad`), even when using `create_graph=True`, I will often lose the computational graph. ## Code example ```python import torch #Constants PAYOFFS = torch.tensor([2.0,3], requires_grad=True) #states states = torch.tensor([1.0,-2], requires_grad=True) #NN I am using to approximate the choice function choices = torch.nn.Linear(2,1) #The benefit function ​def P(states, chosen): return PAYOFFS @ states - chosen output = choices.forward(states) #Returns: tensor([-1.3031], grad_fn=<AddBackward0>) p2 = profit(states, output) #Returns: tensor([-2.6969], grad_fn=<SubBackward0>) #The jacobian gives me what I need, but without the graph torch.autograd.functional.jacobian(profit, (states, output), create_graph=True) #Returns: (tensor([[2., 3.]], grad_fn=<ViewBackward>), tensor([[-1.]])) ``` Notice how that for the second tensor `tensor([[-1.]]).requires_grad == False`. One of the later conditions included in the loss function is that derivative (for notations sake, `DoP = dP/dOutput`) ```python residuals = DoP - F(states,ouptut) ``` ## Various Questions These are some of the questions that I've had while trying to fix this issue. - Why is the computational graph getting lost in XXX? - Are there good resources that discuss why this is happening? - Am I approaching building these derivatives in the wrong way? - I suspect so, I mean facebook uses pytorch. - Should I be using some other module for this type of issue? - I've heard about the module `higher` in connection to other issues with derivatives and pytorch, but have not found enough description of what it does to identify if I need to be using it, or even how to. Anyway, thank you in advance for any help, suggestions, or direction to references I should read.
1
t3_qbqlde
1,634,695,695
pytorch
Question for medical Pytorch
Hello everyone , I am studying pytorch the last month , Also, I am well skilled in frameworks as tf , keras .But I can’t handle the oop setup of Pytorch. How much could it take to get casual? Anyone know a blog or YouTube channel for medical pytorch setup for a kickstart?
0.67
t3_qaudlc
1,634,586,305
pytorch
Making Transfer Learning work right in plain PyTorch
nan
1
t3_qaitvg
1,634,547,611
pytorch
Source to learn pytorch?
I used pytorch for a year but am still very unfamiliar with some functions in the library. Is there any learning resource that can let me walk through each main function with example, say, in the Jupyter notebook?
1
t3_qaguzk
1,634,537,879
pytorch
Handling class imbalance
I've been looking at examples online to see what options I have in the case of a multiclass classification of imbalanced sets. I've read somewhere that I can either provide the class weights to the loss function (CrossEntropyLoss they were recommending) so during the training process, the imbalance is handled, or I can oversample using the WeightedRandomSampler. They were further saying that either option is equivalent to each other. Is that true? Can I just provide the class weights of training to the loss function and go ahead with that? Any other suggestions?
1
t3_qa71d1
1,634,502,661
pytorch
ResNets PyTorch CIFAR-10
I have trained [ResNet-18](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet18_PyTorch.ipynb), [ResNet-18 (dropout)](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet18_Dropout_PyTorch.ipynb), [ResNet-34](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet34_PyTorch.ipynb) and [ResNet-50](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet50_PyTorch.ipynb) from scratch using He weights initializations and other SOTA practices and their implementations in Python 3.8 and PyTorch 1.8. ResNet-18/34 has a different architecture as compared to ResNet-50/101/152 due to bottleneck as specified by Kaiming He et al. in their research paper. Also, note that when a conv layer is followed by a batch norm layer, the conv layer should not be using a bias layer as it's redundant. Thoughts?
0.67
t3_qa3uz7
1,634,493,309
pytorch
Query regarding "torch.save()"
# Code Structure in train.py model.train() # Model Traing Code model.eval() # Training accuracy and prediction torch.save() I am using [train.py](https://train.py) to train the model and then save it. This saved model is then used to train further and then predict on some other data. So I need to know whether or not *torch.save**()* keep the *train()* or *eval()* state of the model? I am a beginner, so if some of this seems obvious, please mention it.
1
t3_q9zley
1,634,480,320
pytorch
can someone help me speed up this very simple code?
I’m taking in latent vecs and generating images, pretty straight forward, but getting less than half the FPS as my Tensorflow model. Can someone help me speed this up? ``` def convert(model, inputs): z = inputs['z'] jzf = [float(i) for i in z] jzft = torch.FloatTensor(jzf) jzftr = jzft.reshape([1, 512]) latents = jzftr.cuda() truncation = inputs['truncation'] img = G(latents, None, truncation) img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8) return {'image': img[0].cpu().numpy()} ```
1
t3_q9d2vm
1,634,394,492
pytorch
The Ultimate Guide To PyTorch
nan
0.71
t3_q8zgx0
1,634,338,360
pytorch
Unknown errors with setting up a PyTorch Image classifier
Hello, thanks for your time. ​ As part of a computer science project, I have decided to create an image classifying CNN using PyTorch, which a user can interact with by selecting their own image (using Tkinter as a GUI) then the model will run this image through and output the predictions and confidence scores. ​ In order to speed up the progress, I have decided to use the ResNet18 model from PyTorch's website as well as [their example code](https://pytorch.org/hub/pytorch_vision_resnet/) but adapted it into my own program. From here, I can gradually add and change things until eventually, I have my own hand-trained model. ​ However, the code is throwing up many errors when trying to pass the image through the model. As PyTorch (and Python programming at this level in general) is quite new to me I was wondering if some guidance could be sought from here. I don't expect someone to code the perfect solution for me, as it needs to be my own work anyway, just an idea as to what the errors messages mean and what I need to look at rewriting. ​ The code is attached below, as well as a transcript of the error messages. ​ `import torch, torchvision` `import torch.nn as nn` `from torchvision import datasets, transforms` `import tkinter as tk` `from tkinter import *` `from tkinter.filedialog import askopenfile, askopenfilename` `from PIL import ImageTk, Image` ​ `#########################################################################` ​ ​ `def SelectUserImage():` `userfilewindow = tk.Toplevel()` `path = askopenfilename(filetypes=[("Image File", '*.jpg')])` `image =` [`Image.open`](https://Image.open)`(path)` `MLImage = image.convert('RGB')` [`MLImage.save`](https://MLImage.save)`('MLImage.jpg')` `test = ImageClassifier(MLImage)` `userfilewindow.pack()` ​ ​ `####################################################################################################` `def ImageClassifier(MLImage):` `ClassifierWindow = tk.Toplevel()` `model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)` `model.eval()` `preprocess = transforms.Compose([` `transforms.Resize(256),` `transforms.CenterCrop(224),` `transforms.ToTensor(),` `transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),` `])` `input_tensor = preprocess(image)` `input_batch = input_tensor.unsqueeze(0)` `if torch.cuda.is_available():` `input_batch = input_batch.to('cuda')` [`model.to`](https://model.to)`('cuda')` `with torch.no_grad():` `output = model(input_batch)` `# Tensor of shape 1000, with confidence scores over Imagenet's 1000 classes` `print(output[0])` `probabilities = torch.nn.functional.softmax(output[0], dim=0)` `print(probabilities)` `with open("imagenet_classes.txt", "r") as f:` `categories = [s.strip() for s in f.readlines()]` `# Show top categories per image` `top5_prob, top5_catid = torch.topk(probabilities, 5)` `for i in range(top5_prob.size(0)):` `print(categories[top5_catid[i]], top5_prob[i].item())` `ImageClassifier.Pack()` ​ `####################################################################################################` `window = Tk()` `window.title("CS Machine Learning Project") # Title for the main window` `FileExplorerLogo = ImageTk.PhotoImage(`[`Image.open`](https://Image.open)`("Local PC Icon.png"))` `Button(window, text='Choose Locally Stored Image', image=FileExplorerLogo, command=SelectUserImage, compound=LEFT).pack(` `side=TOP) # Button to load image from PC` `GDriveLogo = ImageTk.PhotoImage(`[`Image.open`](https://Image.open)`("Google Drive Icon.png"))` `Button(window, text='Choose Image from Google Drive', image=GDriveLogo, compound=LEFT).pack(` `side=TOP) # Button to load image from Google Drive` ​ `window.mainloop()` ​ ​ `####################################################################################################` ​ Errors: ​ Exception in Tkinter callback Traceback (most recent call last): File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\tkinter\\\_\_init\_\_.py", line 1892, in \_\_call\_\_ return self.func(\*args) File "C:\\Users\\griff\\PycharmProjects\\Project\_Interface\\[main.py](https://main.py)", line 28, in SelectUserImage test = ImageClassifier(MLImage) File "C:\\Users\\griff\\PycharmProjects\\Project\_Interface\\[main.py](https://main.py)", line 35, in ImageClassifier model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\site-packages\\torch\\[hub.py](https://hub.py)", line 362, in load repo\_or\_dir = \_get\_cache\_or\_reload(repo\_or\_dir, force\_reload, verbose) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\site-packages\\torch\\[hub.py](https://hub.py)", line 162, in \_get\_cache\_or\_reload \_validate\_not\_a\_forked\_repo(repo\_owner, repo\_name, branch) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\site-packages\\torch\\[hub.py](https://hub.py)", line 124, in \_validate\_not\_a\_forked\_repo with urlopen(url) as r: File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\urllib\\[request.py](https://request.py)", line 214, in urlopen return [opener.open](https://opener.open)(url, data, timeout) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\urllib\\[request.py](https://request.py)", line 523, in open response = meth(req, response) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\urllib\\[request.py](https://request.py)", line 632, in http\_response response = self.parent.error( File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\urllib\\[request.py](https://request.py)", line 561, in error return self.\_call\_chain(\*args) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\urllib\\[request.py](https://request.py)", line 494, in \_call\_chain result = func(\*args) File "C:\\Users\\griff\\miniconda3\\envs\\PyTorch\\lib\\urllib\\[request.py](https://request.py)", line 641, in http\_error\_default raise HTTPError(req.full\_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: rate limit exceeded ​ \############################################################################################ ​ ​ Thanks for your help everyone, have a nice day ​ \- Christian
1
t3_q8x24e
1,634,330,617
pytorch
Integer embeddings (from scratch)
nan
1
t3_q8rnhl
1,634,314,187
pytorch
How can I use biggan ( pytorch implementation) for text to scene generation?
I want to use the flick8r dataset but for the reverse task that it was created for. Biggan doesn't take text input. How do I make text to scene generation happen with it? If this post is inappropriate, I'll delete it please ping me. Thank you!
1
t3_q7sy8m
1,634,188,101
pytorch
Need explanations about torchtext steps for using texts in deep learning classification
Many pytorch deep learning examples online where the input is textual data (not those pre-existing ones in the libraries, but original textual data) had this data preparation framework: 1. read the textual data and save it in a csv file (ideally a pandas dataframe where "text" column has the texts, "labels" column has the labels to be used for classification) 2. define a tokenizer 3. call torchtext Fields and provide what preprocessing techniques to be applied, also provide the tokenizer defined above in there, also define the fields object where you specify the dataframe columns and the associated outputs of the Fields in tuple format 4. call torchtext Tabular and provide the fields, the saved csv file name etc. to obtain the preprocessed data 5. build vocabulary from the output of the Tabular 6. call BucketIterator to batch the data into batches Please feel free to correct any misunderstandings I might have in the above list, so I can learn and correct them. How it all looks like as a code is: from torchtext.legacy import data # 1) I read the texts and piled them up in experimental_data.csv file, where the # first column is something not important, so we ignore that in fields, # next column "text" has the training set texts, "label" has the labels for # texts in each row torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True # 2) Note that I'm using Field's default tokenizer by not providing it anytokenizers # 3) Fields below TEXT = data.Field(batch_first=True, include_lengths=True) LABEL = data.LabelField(dtype = torch.float, batch_first=True) fields = [(None, None), ('text', TEXT),('label', LABEL)] # 4) Tabular below, loading custom dataset training_data = data.TabularDataset(path = "experimental_data.csv", format = 'csv', fields = fields, skip_header = True) # 5) Vocabulary building. For some reason, TEXT.vocab.freqs is a dictionary where #keys are unique words. The values per word are not unique, so I suspect it doesn't #assign unique numbers to words, but collects their training data-level frequencies? #Some words have values 1. Why is that possible? I gave min_freq=100, doesn't it #work? TEXT.build_vocab(training_data, min_freq=100) LABEL.build_vocab(training_data) train_data, valid_data = training_data.split(split_ratio=0.75, random_state = random.seed(SEED)) BATCH_SIZE = 64 # 6) Load an iterator train_iterator, valid_iterator = data.BucketIterator.splits( (train_data, valid_data), batch_size = BATCH_SIZE, sort_key = lambda x: len(x.text), sort_within_batch=True, device = device) # I have no idea how to introduce a test data after this point... What confuses me is, what is actually happening to the data in the above steps? Do the batches actually have the words in texts, or unique numbers assigned to unique words, or word frequencies? What are the extracted features there? There are almost no proper, detailed explanations in none of the examples out there, and torchtext library also did not have enough explanations. I have tried to visualize the outputs of these steps, and they did not make sense to me. For example, in the Fields step I provided a min\_frequency threshold for the words as 100 (so those words that appear less frequent than 100 should be eliminated), but what I obtained after build\_vocab (.freqs attribute gave me) frequencies of words, and many words had the frequency of 1. How is that possible? Are there any detailed tutorials anywhere that dissect these steps, so I can learn what is going on? Also, let's say I am given a test set that was unseen before, how can I use the training set vocabulary to extract the same features from the test data and use that in evaluation? ​ Edit: after reading some online comments on torchtext, alternatively should I skip torchtext altogether and use Dataloader instead? Would writing my own feature extraction functions until the Dataloader step create a huge computational burden for large datasets?
0.89
t3_q7948i
1,634,124,513
pytorch
[HELP] Not able to detect CUDA on Conda instance
Hello all, I am looking for a some help with my torch installation, I am using a conda implementation on my Ubuntu 21.10 laptop, with a pretty old GPU. ​ I don't really know why but whenever I wake the laptop from sleep the CUDA goes missing, sometimes my python code is not even able to detect CUDA even after a fresh reboot, it's really frustrating, bc sometimes it works and other times it won't work. I am really troubled by this, can anyone please help me out in figuring out this issue? Right now I am reinstalling Torch via conda again, to see if I get it working, at this point I also want to mention that I have a cron job that runs the \`sudo apt update && sudo apt upgrade\` every time I login to my machine. ​ I am running Xserver on performance mode PRIME profile, is this one the causes of concern?
1
t3_q76nrs
1,634,113,348
pytorch
A PyTorch RL and DL framework I have built (not mine, but u/raharth)
nan
1
t3_q6p685
1,634,053,810
pytorch
[R] StyleGAN3: Alias-Free Generative Adversarial Networks
nan
1
t3_q6ow2b
1,634,053,001
pytorch
help with ram usage
I am training a stacked gru (2 layer) with a linear output layer. The input size (num timesteps, features) is the following: (3,178136) and the output is the following: (1, 155551). I have access to a supercomputer and am currently trying to run it on one high memory node (1575 gb). But I am getting memory allocation issues. Is there any tips that I can use to reduce the memory usage with reducing the size or number of layers of the network? Since this computing cluster has other nodes I am currently looking into writing some sort of parallel processing scheme that can take advantage of the memory on other nodes. Can parallel processing be used to distribute the memory usage across multiple nodes during the initialization of the model? I tried Googling distributed memory allocation on pytorch but it seems most of the literature out there is for breaking the training and test data into chunks and processing them on separate nodes. I need to distribute the model itself across multiple nodes. Can yall point me to some resources that speak on this topic?
0.84
t3_q6205s
1,633,976,089
pytorch
VGG-18 PyTorch
I have completed some extensive experiments using VGG-18 CNN network trained on CIFAR-10 dataset from scratch and have obtained a validation accuracy = 92.92%. The codes involves different techniques such as: 1. Image data augmentation 2. Kaiming He weight initialisations 3. Learning Rate Scheduler - linear LR warmup over 'k' steps followed by a plateau and step-decay 4. Manual implementation of early stopping 5. Comparison between early stopping vs. LR scheduler 6. Batch Normalization 7. Dropout - to combat overfitting You can access the code [here](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/VGG18_PyTorch.ipynb) and [here](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/VGG18_Dropout_PyTorch.ipynb). According to some research papers, for deep learning architectures, using SGD vs. Adam optimizer leads to faster convergence. Thoughts?
0.89
t3_q6049r
1,633,970,946
pytorch
How to correctly define the first layer dimensions for textual data batches
I created a simple text classification problem where I'd like to use pytorch to perform a logistic regression operation over the data. Data is texts, converted to batches. The classification model is as follows: class LogisticRegressionModel(nn.Module): def __init__(self, vocab_size, num_labels): super(LogisticRegressionModel, self).__init__() self.linear = nn.Linear(vocab_size, num_labels) def forward(self, x): print(x.shape) out = self.linear(x) return nn.functional.log_softmax(out, dim=1) The batch size is 64. The words in texts are converted to unique numbers, so inside of a batch looks like: (tensor([[ 100, 45, 23, ..., 212, 1560, 2], [ 0, 0, 8, ..., 2, 2, 2], [ 3, 51, 1393, ..., 203, 178, 2], ..., [ 38, 3635, 161, ..., 2, 1, 1], [ 97, 162, 285, ..., 2, 1, 1], [ 38, 149, 0, ..., 30, 1, 1]]), tensor([18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16])) torch.Size([64, 18]) Every batch has a different size, above one has 18 but others have 50 etc. I think that's the maximum number of words a text had in that batch. ​ My question is, why is my classifier not accepting the batches as input? Gives the following error RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x18 and 12853x16) (64x18) is the batch dimensions, and (12853x16) is the layer dimension (12853 is the vocabulary size, 16 is the number of classes). The error seems to be related to how I defined the linear layer in the logistic regression. Examples online had an embedding layer before the linear layer and it seemed like having the same type of batches as I do, embedding layer handled the batches, but the linear layer cannot. ​ What is the correct way of defining the linear layer, so that it can handle the batches as they are?
1
t3_q5wbui
1,633,960,353
pytorch
Custom C++ extensions vs libtorch
Hello, I am interested in having the model inference in C++ (CPU only). The model is trained in python, I have a few questions regarding libtorch vs Custom C++ extensions of pytorch. ​ 1. the main difference between libtorch vs Custom C++ extensions of pytorch (can both be used for inference?) 2. Which one is better in terms of both ease of use and performance in terms of inference. 3. can you convert any PyTorch model be used for inference in C++ using libtorch and/or C++ extensions. 4. Finally, which method is recommended for future use. ​ P.S: by custom C++ extensions I mean [this](https://pytorch.org/tutorials/advanced/cpp_extension.html#)
1
t3_q5rs5f
1,633,943,031
pytorch
A sneak peek on the features of TorchVision v0.11
nan
1
t3_q57r4v
1,633,871,407
pytorch
Any step by step instructions for compiling for Windows?
I'm trying to figure out how to compile pytorch so I can play with it on an old Cuda 3.0 card(a Quadro k420 if that matters), since the compiled binaries aren't compiled with support for older cards. I found lots of detailed instructions for Linux, but I haven't had any luck figuring out how to do it in Windows. Is there anywhere I can find a guide that will hold my hand?
0.86
t3_q41avz
1,633,710,626
pytorch
Modify convolution kernels ops
Hello, I try to modify the way convolutions are performed for a conv net (let take ResNet18 as an example) in PyTorch: Take the first layer. I want to take the FT(Fourier) of the input image F(I); take the FTs of the conv kernels F(k1),...F(k64). Next step, add them up: F(K\_total) = F(k1)+F(k2)+...+F(k64). Finally do a single do a single multiply: F(I) \* F(K\_total). Then do the inverse. The FT of the input image is not a big deal. But how can I operate on conv kernels ops in PyTorch ? I am willing to change the framework used, if you recommend it.
0.72
t3_q3rvq2
1,633,673,743
pytorch
Python server GAN move to on mobile processing. What are the biggest hurdles and issues? It’s a vision model for generating photos.
nan
1
t3_q3m5x6
1,633,651,991
pytorch
Can I use a mining rig for training a model on PyTorch, and will it be effective?
So I currently have a mining rig that I am considering using for training a machine learning model, but given the differences between mining rigs and my traditional ML computing setup, I was wondering if there would be any significant bottlenecks. My rig is as follows: 13x RTX 3080 GPUs (connected to the motherboard via PCI-E x16 to x1 risers) 16 GB DDR4 2400 MHz RAM Intel i5 7600k Western Digital SSD ASRock H110 BTC mining pro motherboard My main concern is with the use of risers and the relatively old CPU.
0.9
t3_q3h00k
1,633,635,990
pytorch
Model not training after revisiting in a few weeks
Hey Everyone! I created a CNN implementation a few months ago and it worked great on different losses (Dice, CE, Focal). The iou and F1 scores would turn out great in just 3-5 epochs. However, I revisited it now a few weeks later and tried to re-train it on the same data but it's not training. I initially tried to train it using Dice Loss (as it gave the best results) but it gave the no_grad error - something I had never faced before. I set requires_grad to True and it stopped giving the error but now it doesn't really train. The values just hop around a bit but stay the same more or less over 10s of epochs. I tried it with the other losses too and they're not training either. I have not changed the code base in any way. I have however done all this using colab. Would version changes or something along the lines contribute to this? Would really appreciate any help. I've been stuck on this for a while now and it's incredibly frustrating.
1
t3_q307m5
1,633,577,052
pytorch
Simple operators comparatively slow on CPU
I've made a [post](https://discuss.pytorch.org/t/speed-up-libtorch-operators-on-cpu/133254) on the Pytorch forums too about this. Libtorch operators such as + * or / are slow compared to other implementations such as C++ vectors or Armadillo. I tested by multiplying two vectors elements-wise 10 million times and got the following durations: Pytorch - 7.2 seconds Arma - 0.33 C++ vectors - 0.23 I understand that Pytorch is doing all sorts of things under the hood for backpropagation and is meant to be used on the GPU, but to me this difference is pretty significant and before I invest time in making my own backpropagation algorithm with Arma I'd like to know whether there are any ways of speeding up these types of vector operations.
1
t3_q2kkea
1,633,527,214
pytorch
PyTorch Forecasting lr_find out of bounds - request for help
I am trying to follow the PyTorch Forecasting tutorials to apply to my own data. My data is an irregular time series with multiple grouping variables. I am able to run everything fine until the optimal learning rate step. I get an error: RuntimeError: index 12 is out of bounds for dimension 0 with size 11. As best as I can tell index 12 is the lstm_decoder. I have searched the documentation, stackoverflow, and just googling a bunch but I’m not finding how to narrow down the problem. Could the problem be that my timeseries is irregular (weekly dates with some grouping not present at each time), or is there another issue I’m missing. I have also tried removing all missing values. allow_missing_time steps is set to true in the TimeSeriesDataSet step.
0.6
t3_q0v5zj
1,633,309,869
pytorch
Increasing GPU RAM Allocation?
Hey I'm running into an out of memory error while attempting neural style transfer using a pretrained VGG19. I have 2 questions: \- I have 6GB GPU memory available on my system, but PyTorch is only allocating around 3GB. Is there any way to increase that? \- Is 6GB enough for a single pass through VGG19?
0.86
t3_pzeqiu
1,633,114,949
pytorch
Primer EZ: Annotated Implementation
Primer is a transformer model found using an >1,000 TPUv2-hour evolutionary architecture search by Google. It can be >4X faster to train than vanilla transformer. Primer EV has the two most robust modifications in Primer: Squared ReLU activations and depth-wise convolution of K, Q, and V projections. * [Implementation with side-by-side notes](https://nn.labml.ai/transformers/primer_ez/index.html) * [Paper](https://papers.labml.ai/paper/2109.08668) * [Highlighted PDF](https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/papers/2109.08668.pdf) * [Twitter thread](https://twitter.com/labmlai/status/1440273380213551120)
1
t3_pyk4fx
1,633,009,609
pytorch
Ideas on how to create a differentiable loss function with count?
I'm trying to create a loss function for a NN that counts how many values in a tensor are above the value 10. For example, if I have the tensors: a = torch.tensor(\[1, 2, 12, 35, 3\]) b = torch.tensor(\[11, 22, 1, 3, 99\]) The loss will be 2 + 3 = 5. However, I can't figure out how to make something like this that will be differentiable
0.86
t3_pwx7p6
1,632,798,358
pytorch
Four short videos on the why, how, and what about PyKale, a library in the PyTorch ecosystem aiming to make machine learning (ML) more accessible to interdisciplinary research. Both ML experts and end users can do better research with our accessible design. Code: https://github.com/pykale/pykale [P]
nan
0.91
t3_pvukd7
1,632,665,372
pytorch
Cannot access a model's layers in tch-rs
nan
1
t3_pv5c7m
1,632,570,888
pytorch
A Guide to Writing CNNs from Scratch in PyTorch
nan
1
t3_puo0nj
1,632,502,867
pytorch
Help with Pytorch model deploy
Hi! I am a backend engineer developing an Rest API to provide access to a PyTorch model. The model was made by another developer and he no longer works in this project, so I have the task of figuring out what to do. However I have zero experience with Machine Learning and would like to know few resource that may help me to understand the basics about a PyTorch Neural Network and deploy it in production. ​ Thanks!
1
t3_pu8cwe
1,632,442,977
pytorch
Enhancement on splitting tensors
Is there any way to split a tensor into a tensor of sub-tensors in pytorch? Current solutions split it into a list/tuple of sub-tensors and make use of torch.stack() inevitably, which is very slow. Would like to know any suggestions from the community
1
t3_ptuu82
1,632,402,347
pytorch
Host and serve your PyTorch, TensorFlow, and Scikit-learn models quickly and easily
Hi Everyone, FlashAI.io was born out of a need to find a quick and simple way to host or serve my ML models. Sometimes you want to enable clients, colleagues, or apps to send inference requests to your models. FlashAI lets you do this via web requests. Serve your models with any hassle, try FlashAI.io The workflow is straight forward: \* Train your model locally \* Upload your model file to FlashAI.io \* Send inference requests to your model Currently this service supports Scikit-learn, TensorFlow, and PyTorch models. Try it out at [flashai.io](https://flashai.io/) See the tutorial at: [https://youtu.be/0yxUmZ2GnX8](https://youtu.be/0yxUmZ2GnX8) Please let me know what you think and if you have any suggestions for other features.
0.55
t3_ptf7j1
1,632,339,406
pytorch
Best way to append tensors
How can I append multiple tensors to a single one during training? One obvious method is using list comprehension to stack tensors and calling the stack function at the end. But this wouldn't be feasible if I move it into the GPU. Using torch.cat() creates a copy of the tensor and its both time consuming as well as might run out of memory when processing large batches. Which is the optimal way?
1
t3_pt64bm
1,632,312,365
pytorch
Tools and libraries to deploy model in production
Hi All, Question to people who deployed detectron2/pytorch models in production. How do you deploy an object detection dl model in production for real-time feed? Currently I am running app using plain python inference code but I believe that's not how models are deployed in production. Can someone guide me on this ? I want to deploy a real-time Object detection app on single powerful gpu where it's receiving 2 or more real-time feed and I would like to process them in real-time to trigger some events. I have looked at some blogs like medium and towards data-science but didn't find anything on real-time video processing in production that detailed as I want. I also checked some tools such Mlflow ,torch serve but didn't really understand what to do? If someone can help on deploying real-time video processing models in production that will be great !! Language preferred : Python Platform: GPU server - Nvidia but edge also is fine. If this question is not valid in this blog or you cannot answer in publicly, please feel free to dm me !! Thanks in advance !
0.81
t3_psulgl
1,632,265,928
pytorch
Cloud GPU
What do you use for cloud GPU computing? I’ve tried google colab but it’s limited to 24h. I have a script that’s gonna need a week to run (grid search with leave one out cross validation)
0.84
t3_prze03
1,632,158,447
pytorch
Image mean and std
I have a dataset with images where sizes varies. The images are polygons with 0 outside the region of interest (ROI). In my network, the input size is always fixed e.g. 224x224. What mean and std should I use in dataloader to normalze the image? The mean and std from the initial image size, the 224x224 mean and std and inside ROI or not?
1
t3_prs33e
1,632,133,860
pytorch
How to interpret pytorchviz visualization graph to debug gradient issue ?
I managed to [visualize the computational graph](https://i.imgur.com/wceJ0Df.png) for my gdas coding using [pytorchviz](https://github.com/szagoruyko/pytorchviz) However, how to use the visualized graph to debug the [grad=None issue](https://github.com/promach/gdas/blob/main/gdas.py#L464) ? https://preview.redd.it/yherfadcblo71.png?width=10121&format=png&auto=webp&s=05af403cf2fee16f5f9e83b5b30702af8d954270
1
t3_pro1tw
1,632,114,022
pytorch
What are the clip gan dataset that was used to train on colab?
I want to train a clip gan on colab, and I was told that they used a imagenet. But I think it is not true. You need the text and the image. Do we have the dataset for clip gan or the reproduce clip gan on colab? thank you
1
t3_pr6jys
1,632,052,498
pytorch
Spark2 + pytorch on GPU
Was reading the documentation of sparktorch (https://github.com/dmmiller612/sparktorch) which says you need spark >= 2.4.4. But to the best of my knowledge spark2 doesn't have gpu compute capabilities. Does that mean it can only use cpu compute? Am I missing something?
0.88
t3_pqbouq
1,631,922,764
pytorch
AWS lambda inference taking 3s even after warmup
I asked the [following from this sub](https://www.reddit.com/r/pytorch/comments/p6duzx/does_torchserve_in_aws_scale_to_have_equal/?utm_medium=android_app&utm_source=share) few weeks ago. >If I manually launch an ec2 server with pytorch inference, the inference time will depend on the resources I configured and the number of users. When many users request in parallel, inference time will increase (due to limited resources and waiting). >The requirement is: inference time per image per user should be less than 100 ms. Is there any way I can ensure this is met regardless of number of parallel requests? Is this possible with SageMaker? Many suggested to move the inference to AWS lambda for the best scaling. So, I open a video file in a server (ec2/beanstalk), stream each frame to the lambda and get predictions back and do further processing. When i do that, each frame takes 1.7 to 3 seconds to process. Although latency isn't an issue for us, we need a throughput of about 10 frames per second. What can I do?
1
t3_ppvphk
1,631,864,502
pytorch
German language sentiment classification - NLP Deep Learning
I am trying to build a sentiment classification (hate speech) for German language using NLP + Deep Learning. Any code tutorial? I found lots of research papers but few code implementations.
0.83
t3_pp4gd0
1,631,758,979
pytorch
Read quantized weights
I managed to quantize a model. I can see the weights are in qint8. But when I call [conv.weight.data](https://conv.weight.data), I get floating-point weights. Isn't there a way to get int8 weights directly, like in tflite?
1
t3_pp3cdw
1,631,754,903
pytorch
Inference with pytorch vs torchscript+libtorch
Hi! I would like to know if there is a big difference between doing inference (in production) with simple pytorch vs exporting pytorch model with torchscript and running it with libtorch. I can't find any benchmark.. My question is for CPU and GPU.
0.9
t3_po0icb
1,631,617,171
pytorch
Model bert_score not getting better.
I was developing a Encoder-decoder NLP generative model, and was evaluating it against a Bert_score on each epoch. I found that even when the loss keeps decreasing with ever epoch, the best Bert_score converges early into the training (eg. Epoch3, epoch15 etc) and never changes again. I have set my learning rate to be 0.0001 and my gradient clipping to be 1.0 . What all could be the possible reasons for this behaviour? I am using GRUs inside my encoder and decoder.
0.86
t3_pm7gzn
1,631,367,040
pytorch
Pytorch GPU Memory Leak Problem: Cuda Out of Memory Error !!
I am working on implementing UNet for image segmentation using Pytorch. I think there's a GPU memory leak problem because it raises Cuda out of Memory error. Pytorch Version: 1.9.0 What I've tried so far: * reducing batch size, even to 1. * reducing the number of workers in the data loader. * detaching tensors and deleting unneeded tensors after updating the grads. * setting the data grads and the model parameters grads to None at the end of the training loop. * enforcing GPU Cuda memory freeing using: `torch.cuda.empty_cache()` ​ Can anyone help please to check what's wrong here??
0.75
t3_pm6t0t
1,631,364,398
pytorch
help with installation w.o internet please
dear all, i am setting up my python/conda/pytorch environment on a totally new machine w. 4 GPUs and the machine does not have access to the internet unfortunately (and will not have). I am wondering if there is a way to download the package and build from the source as any commands using pip or conda to install will fail due to no access to the internet. If you have a solution/link to similar thread, please feel free to shine some light on me, much appreciated!!
0.38
t3_pkezpv
1,631,121,852