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
[N] Lightning Transformers - Train HuggingFace Transformers at scale with PyTorch Lightning
[Lightning Transformers](https://github.com/PyTorchLightning/lightning-transformers) is for users who want to train, evaluate and predict using HuggingFace models and datasets with PyTorch Lightning. Full customizability of the code using the LightningModule and Trainer, with Hydra config composition for quick and easy experimentation. No boilerplate code required; easily swap out models, optimizers, schedulers, and more without touching the code. Check out the blog post: [Training Transformers at Scale with PyTorch Lightning](https://pytorch-lightning.medium.com/training-transformers-at-scale-with-pytorch-lightning-e1cb25f6db29) for more information or the [documentation](https://lightning-transformers.readthedocs.io/). https://i.redd.it/md2cqcukwjv61.gif
0.67
t3_mz2q56
1,619,457,350
pytorch
Pytorch Debug Log file
is there a way to see the backend logs for pytorch, like what functions are being called when we create a neural model, train a model. Something similar to java webapp debug logs. Any link for online reference or tutorial will be helpful. Thanks in advance.
0.99
t3_myyv3b
1,619,447,126
pytorch
Best Place to start
Dear Redditors I'm currently trying to build my first ever neural network with PyTorch. As a school project I want to create an AI to play Connect 4 but I can't find any good tutorials on how to learn DQN and how to apply it. Is it possible to learn to create the AI in two weeks? Thanks for any answers.
0.5
t3_myhv2w
1,619,385,431
pytorch
[P] An introduction to PyKale https://github.com/pykale/pykale​, a PyTorch library that provides a unified pipeline-based API for knowledge-aware multimodal learning and transfer learning on graphs, images, texts, and videos to accelerate interdisciplinary research. Welcome feedback/contribution!
nan
1
t3_mxub6p
1,619,302,381
pytorch
The PyTorch Geometric Temporal paper is out
This is a preliminary version: [https://arxiv.org/abs/2104.07788](https://arxiv.org/abs/2104.07788) We also added new layers and datasets with the new release: [https://github.com/benedekrozemberczki/pytorch\_geometric\_temporal](https://github.com/benedekrozemberczki/pytorch_geometric_temporal)
1
t3_mxsois
1,619,297,446
pytorch
Accessing modules - PyTorch ResNet-18
I am using a ResNet-18 coded as follows: class ResidualBlock(nn.Module): ''' Residual Block within a ResNet CNN model ''' def __init__(self, input_channels, num_channels, use_1x1_conv = False, strides = 1): # super(ResidualBlock, self).__init__() super().__init__() self.conv1 = nn.Conv2d( in_channels = input_channels, out_channels = num_channels, kernel_size = 3, padding = 1, stride = strides, bias = False ) self.bn1 = nn.BatchNorm2d(num_features = num_channels) self.conv2 = nn.Conv2d( in_channels = num_channels, out_channels = num_channels, kernel_size = 3, padding = 1, stride = 1, bias = False ) self.bn2 = nn.BatchNorm2d(num_features = num_channels) if use_1x1_conv: self.conv3 = nn.Conv2d( in_channels = input_channels, out_channels = num_channels, kernel_size = 1, stride = strides ) self.bn3 = nn.BatchNorm2d(num_features = num_channels) else: self.conv3 = None self.relu = nn.ReLU(inplace = True) self.initialize_weights() def forward(self, X): Y = F.relu(self.bn1(self.conv1(X))) Y = self.bn2(self.conv2(Y)) if self.conv3: X = self.bn3(self.conv3(X)) # print(f"X.shape due to 1x1: {X.shape} & Y.shape = {Y.shape}") else: # print(f"X.shape without 1x1: {X.shape} & Y.shape = {Y.shape}") pass Y += X return F.relu(Y) def shape_computation(self, X): Y = self.conv1(X) print(f"self.conv1(X).shape: {Y.shape}") Y = self.conv2(Y) print(f"self.conv2(X).shape: {Y.shape}") if self.conv3: h = self.conv3(X) print(f"self.conv3(X).shape: {h.shape}") def initialize_weights(self): for m in self.modules(): # print(m) if isinstance(m, nn.Conv2d): nn.init.kaiming_uniform_(m.weight) ''' # Do not initialize bias (due to batchnorm)- if m.bias is not None: nn.init.constant_(m.bias, 0) ''' elif isinstance(m, nn.BatchNorm2d): # Standard initialization for batch normalization- nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal_(m.weight) nn.init.constant_(m.bias, 0) b0 = nn.Sequential( nn.Conv2d(in_channels = 3, out_channels = 64, kernel_size = 3, stride = 1, padding = 1), nn.BatchNorm2d(num_features = 64), nn.ReLU()) def create_resnet_block(input_filters, output_filters, num_residuals, first_block = False): # Python list to hold the created ResNet blocks- resnet_blk = [] for i in range(num_residuals): if i == 0 and first_block: resnet_blk.append(ResidualBlock(input_channels = input_filters, num_channels = output_filters, use_1x1_conv = True, strides = 2)) else: resnet_blk.append(ResidualBlock(input_channels = output_filters, num_channels = output_filters, use_1x1_conv = False, strides = 1)) return resnet_blk b1 = nn.Sequential(*create_resnet_block(input_filters = 64, output_filters = 64, num_residuals = 2, first_block = True)) b2 = nn.Sequential(*create_resnet_block(input_filters = 64, output_filters = 128, num_residuals = 2, first_block = True)) b3 = nn.Sequential(*create_resnet_block(input_filters = 128, output_filters = 256, num_residuals = 2, first_block = True)) b4 = nn.Sequential(*create_resnet_block(input_filters = 256, output_filters = 512, num_residuals = 2, first_block = True)) # Initialize a ResNet-18 CNN model- model = nn.Sequential( b0, b1, b2, b3, b4, nn.AdaptiveAvgPool2d(output_size = (1, 1)), nn.Flatten(), nn.Linear(in_features = 512, out_features = 10)) The layer names are now as follows: for layer_name, param in trained_model.named_parameters(): print(f"layer name: {layer_name} has {param.shape}") >layer name: 0.0.weight has torch.Size(\[64, 3, 3, 3\]) > >layer name: 0.0.bias has torch.Size(\[64\]) > >layer name: 0.1.weight has torch.Size(\[64\]) > >layer name: 0.1.bias has torch.Size(\[64\]) > >layer name: 1.0.conv1.weight has torch.Size(\[64, 64, 3, 3\]) > >layer name: 1.0.bn1.weight has torch.Size(\[64\]) > >layer name: 1.0.bn1.bias has torch.Size(\[64\]) > >layer name: 1.0.conv2.weight has torch.Size(\[64, 64, 3, 3\]) > >layer name: 1.0.bn2.weight has torch.Size(\[64\]) > >layer name: 1.0.bn2.bias has torch.Size(\[64\]) > >layer name: 1.0.conv3.weight has torch.Size(\[64, 64, 1, 1\]) > >layer name: 1.0.conv3.bias has torch.Size(\[64\]) > >layer name: 1.0.bn3.weight has torch.Size(\[64\]) > >layer name: 1.0.bn3.bias has torch.Size(\[64\]) > >layer name: 1.1.conv1.weight has torch.Size(\[64, 64, 3, 3\]) > >layer name: 1.1.bn1.weight has torch.Size(\[64\]) > >layer name: 1.1.bn1.bias has torch.Size(\[64\]) > >layer name: 1.1.conv2.weight has torch.Size(\[64, 64, 3, 3\]) > >layer name: 1.1.bn2.weight has torch.Size(\[64\]) > >layer name: 1.1.bn2.bias has torch.Size(\[64\]) > >layer name: 2.0.conv1.weight has torch.Size(\[128, 64, 3, 3\]) > >layer name: 2.0.bn1.weight has torch.Size(\[128\]) > >layer name: 2.0.bn1.bias has torch.Size(\[128\]) > >layer name: 2.0.conv2.weight has torch.Size(\[128, 128, 3, 3\]) > >layer name: 2.0.bn2.weight has torch.Size(\[128\]) > >layer name: 2.0.bn2.bias has torch.Size(\[128\]) > >layer name: 2.0.conv3.weight has torch.Size(\[128, 64, 1, 1\]) > >layer name: 2.0.conv3.bias has torch.Size(\[128\]) > >layer name: 2.0.bn3.weight has torch.Size(\[128\]) > >layer name: 2.0.bn3.bias has torch.Size(\[128\]) > >layer name: 2.1.conv1.weight has torch.Size(\[128, 128, 3, 3\]) > >layer name: 2.1.bn1.weight has torch.Size(\[128\]) > >layer name: 2.1.bn1.bias has torch.Size(\[128\]) > >layer name: 2.1.conv2.weight has torch.Size(\[128, 128, 3, 3\]) > >layer name: 2.1.bn2.weight has torch.Size(\[128\]) > >layer name: 2.1.bn2.bias has torch.Size(\[128\]) > >layer name: 3.0.conv1.weight has torch.Size(\[256, 128, 3, 3\]) > >layer name: 3.0.bn1.weight has torch.Size(\[256\]) > >layer name: 3.0.bn1.bias has torch.Size(\[256\]) > >layer name: 3.0.conv2.weight has torch.Size(\[256, 256, 3, 3\]) > >layer name: 3.0.bn2.weight has torch.Size(\[256\]) > >layer name: 3.0.bn2.bias has torch.Size(\[256\]) > >layer name: 3.0.conv3.weight has torch.Size(\[256, 128, 1, 1\]) > >layer name: 3.0.conv3.bias has torch.Size(\[256\]) > >layer name: 3.0.bn3.weight has torch.Size(\[256\]) > >layer name: 3.0.bn3.bias has torch.Size(\[256\]) > >layer name: 3.1.conv1.weight has torch.Size(\[256, 256, 3, 3\]) > >layer name: 3.1.bn1.weight has torch.Size(\[256\]) > >layer name: 3.1.bn1.bias has torch.Size(\[256\]) > >layer name: 3.1.conv2.weight has torch.Size(\[256, 256, 3, 3\]) > >layer name: 3.1.bn2.weight has torch.Size(\[256\]) > >layer name: 3.1.bn2.bias has torch.Size(\[256\]) > >layer name: 4.0.conv1.weight has torch.Size(\[512, 256, 3, 3\]) > >layer name: 4.0.bn1.weight has torch.Size(\[512\]) > >layer name: 4.0.bn1.bias has torch.Size(\[512\]) > >layer name: 4.0.conv2.weight has torch.Size(\[512, 512, 3, 3\]) > >layer name: 4.0.bn2.weight has torch.Size(\[512\]) > >layer name: 4.0.bn2.bias has torch.Size(\[512\]) > >layer name: 4.0.conv3.weight has torch.Size(\[512, 256, 1, 1\]) > >layer name: 4.0.conv3.bias has torch.Size(\[512\]) > >layer name: 4.0.bn3.weight has torch.Size(\[512\]) > >layer name: 4.0.bn3.bias has torch.Size(\[512\]) > >layer name: 4.1.conv1.weight has torch.Size(\[512, 512, 3, 3\]) > >layer name: 4.1.bn1.weight has torch.Size(\[512\]) > >layer name: 4.1.bn1.bias has torch.Size(\[512\]) > >layer name: 4.1.conv2.weight has torch.Size(\[512, 512, 3, 3\]) > >layer name: 4.1.bn2.weight has torch.Size(\[512\]) > >layer name: 4.1.bn2.bias has torch.Size(\[512\]) > >layer name: 7.weight has torch.Size(\[10, 512\]) > >layer name: 7.bias has torch.Size(\[10\]) ​ In order to prune this model, I am referring to [PyTorch pruning tutorial](https://pytorch.org/tutorials/intermediate/pruning_tutorial.html#inspect-a-module). It's mentioned here that to prune a module/layer, use the following code: ​ parameters_to_prune = ( (model.conv1, 'weight'), (model.conv2, 'weight'), (model.fc1, 'weight'), (model.fc2, 'weight'), (model.fc3, 'weight'), ) But for the code above, the modules/layers no longer have this naming convention. For example, to prune the first conv layer of this model: >layer name: 0.0.weight has torch.Size(\[64, 3, 3, 3\]) ​ on trying the following code: prune.random_unstructured(model.0.0, name = 'weight', amount = 0.3) It gives me the error: >prune.random\_unstructured(trained\_model.0.0, name = 'weight', amount = 0.3) > >\^ > >SyntaxError: invalid syntax How do I handle this?
0.67
t3_mxlrir
1,619,276,776
pytorch
Pytorch Template
Hi everyone, I write a pytorch template codes. I keep revising this project about 6 months. Hope more people can see it. The aim of this template is: Pytorch template can do all kinds of ML projects. Make it easy and fast to revise pytorch codes. Thanks! [https://github.com/deeperlearner/pytorch-template](https://github.com/deeperlearner/Pytorch-Template)
0.93
t3_mxlpyq
1,619,276,646
pytorch
How can I use a lr scheduler just for its value?
I have a lr scheduler: import torch import torch.nn as nn import matplotlib.pyplot as plt model = torch.nn.Linear(2, 1) optimizer = torch.optim.SGD(model.parameters(), lr=0.05) scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=1e3, max_lr=1e-1, step_size_up=1000, mode="triangular2", cycle_momentum=False) lrs = [] for i in range(30000): optimizer.step() #print(optimizer.param_groups[0]["lr"]) lrs.append(optimizer.param_groups[0]["lr"]) scheduler.step() plt.plot(lrs) That looks like ​ https://preview.redd.it/jcaekfaahru61.png?width=782&format=png&auto=webp&s=408a002c216fc06642fc088d1498d28004682cf2 Is there a way to use this scheduler simply for its value for each epoch? That is, I want to plug its value at each epoch in a certain function: for epoch in num_epochs: loss = 5 - optimizer.param_groups[0]["lr"] My problem is that I have another lr scheduler, and when I use this one, my model just takes one of them as the scheduler. Again, I just need this one for its value, so it should be disconnected from the parameters
1
t3_mwa9iq
1,619,113,306
pytorch
Libtorch Build Error (C++)
Hello, I am trying to build a project using libtorch, as I want to try out using pytorch with C++. However, when i try to build the project (With C++ Version 17, in Visual Studio 2019), I get the following error: >function call is not allowed in a constant expression Following the error, it points to the following line in Macros.h, line 189: `#if __has_attribute(always_inline) || defined(__GNUC__)` Has anyone had this problem before?
0.72
t3_mw8gdp
1,619,108,443
pytorch
Calculate autodif of NN outputs wrt inputs.
Does anyone have an example of how to syntax this goal? Any example or response I get does autodif of loss wrt to parameters. I want to make my NN a function say f: t -> (x, Vx) where x is the calculated NN output from a typical training regiment, and Vx is the autodif of x wrt t (velocity of NN position output).
1
t3_mw3ub7
1,619,095,238
pytorch
How to change PyTorch sigmoid function to be more steep
My model works when I use "torch.sigmoid". I tried to make the sigmoid steeper by creating a new sigmoid function: def sigmoid(x): return 1 / (1 + torch.exp(-1e5*x)) But for some reason the gradient doesn't flow through it (I get NaN). Is there a problem in my function, or is there a way to simply change the PyTorch implementation to be steeper (as my function)? Code example: def sigmoid(x): return 1 / (1 + torch.exp(-1e5*x)) a = torch.tensor(0.0, requires_grad=True) b = torch.tensor(0.58, requires_grad=True) c = sigmoid(a-b) c.backward() a.grad > tensor(nan) ​
1
t3_mvpj9k
1,619,039,406
pytorch
LSTM, how many timesteps do you guys like to take as input?
Creating a predictive model, and curious how many timesteps you guys think I should take as input? I've been simply passing it 1, but am beginning to think maybe more might be beneficial. I understand the whole idea is that it should somewhat remember the previous data, but I'm worried it's not remembering well enough. (it's minute by minute data, trying to predict the next few minutes)
1
t3_mvlmxn
1,619,028,548
pytorch
The fastest polytope sampler, paper and conference. (In Pytorch)
nan
1
t3_mv9aq4
1,618,984,242
pytorch
.to(device) just hangs
Any attempt at casting anything in nn to cuda just waits. Nothing prints, no errors. It just sits there. I'm attempting to cast an LSTM, but it applies to anything, even if I just to try to cast the final linear layer it still results in the same problem. Any ideas? Completely out of them UPDATE: Looks like it was probably due to the outdated installation of PyTorch (on an RTX 3070 now, from a 2070, incompatibility with CUDA version probably)
1
t3_mv7tb9
1,618,977,689
pytorch
PyTorch optimizer.step() doesn't update weights when I use "if statement"
My model needs to learn certain parameters to solve this function: self.a * (r > self.b) * (self.c) Where self.a, self.b, and self.c are learnable parameters.My issue is that "b" does not change. I assume it's because the function is discontinuous. Though, it is a step function so I'm not sure how to modify it. Any ideas/tips will be appreciated ​ My code is import torch import torch.nn as nn import torch.optim as optim class model(nn.Module): def __init__(self): super(model, self).__init__() self.a = torch.nn.Parameter(torch.rand(1, requires_grad=True)) self.b = torch.nn.Parameter(torch.rand(1, requires_grad=True)) self.c = torch.nn.Parameter(torch.rand(1, requires_grad=True)) model_net = model() #function to learn = 5 * (r > 2) * (3) optimizer = optim.Adam(model_net.parameters(), lr = 0.1) for epoch in range(10): for r in range(10): optimizer.zero_grad() loss = 5 * (r > 2) * (3) - model_net.a * (r > model_net.b)*(model_net.c) loss.backward() optimizer.step() print(model_net.a) print(model_net.b) print(model_net.c) print()
0.9
t3_muhjnj
1,618,888,854
pytorch
I know this is over asked but hear me out...
Hi everyone. How do I learn PyTorch. I'm 14. I have substantial experience in Python and have previously dabbled in OpenCV. I have tried learning it in the past to no avail. Please help. I would appreciate any attention!
0.71
t3_muedpt
1,618,877,912
pytorch
An overview of the ML models introduced in TorchVision v0.9
nan
1
t3_mude3t
1,618,874,677
pytorch
How to optimize integer parameters as a part of the real-valued loss function?
I'm doing a research, where we are experimenting with different number systems for CNN. We are quantizing intermediate values after each layer with custom number of bits. The goal is to reduce the total size of the model, while retaining as much accuracy as possible. My idea is to do an aware-training. Of course we can set a scheme (layer 1 - 8 bits, layer 2 - 7 bits...etc) and train, so that weights can readjust to retain accuracy. But setting the scheme is not obvious. I can simulate the bit effects with torch's bit ops. I tried manually setting number of bits for different layers of a pretrained model, and it's counterintuitive. Some layers are too sensitive and some are not. So, i thought of making number of bits an integer variable and adding a weighted sum of them to the pre-existing loss function. Weight = size of that layer. So the optimizer can minimize the number of bits (hence total size) while adjusting the weights as well, to retain most of the accuracy. Problem is, number of bits for each layer is an integer. As SGD moves little by little, integers may not change at all, and might change suddenly. I read a bit on integer programming. But I'm not sure how to combine it with the rest of the real-valued loss function. Because i want to minimize number of bits WHILE changing weights accordingly to keep accuracy up.
1
t3_mu3t1h
1,618,848,050
pytorch
AI agent plays Chrome Dino
nan
0.94
t3_mti6hf
1,618,769,775
pytorch
Mask RCNN training time
Yo i am training my Mask RCNN on about 2000 images. It took me 1 hour for one epoch. Is it normal? I am so bored now cause I have 19 epochs left I am using CPU in Google Colab.
1
t3_mtcvsi
1,618,752,738
pytorch
Guide to PyTerrier: A Python Framework for Information Retrieval
nan
1
t3_mtbdjk
1,618,746,652
pytorch
Learning rate scheduler
Hey guys, I am trying to recreate results of “The Lottery Ticket Hypothesis” by Frankle et al. They are using CIFAR-10 which has 50K training images. Using a batch size = 64 gives 781 iterations/steps in one epoch. I am trying to implement this in PyTorch. For VGG-18 & ResNet-18, the authors propose the following learning rate schedule 1. Linear learning rate warmup for first k = 7813 steps from 0.0 to 0.1 ​ After 10 epochs or 7813 training steps, the learning rate schedule is as follows- 1. For the next 21094 training steps (or, 27 epochs), use a learning rate of 0.1 2. For the next 13282 training steps (or, 17 epochs), use a learning rate of 0.01 3. For any remaining training steps, use a learning rate of 0.001 I have implemented this in TensorFlow2 as follows: from typing import Callable, List, Optional, Union class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule): """ Applies a warmup schedule on a given learning rate decay schedule. Args: initial_learning_rate (:obj:`float`): The initial learning rate for the schedule after the warmup (so this will be the learning rate at the end of the warmup). decay_schedule_fn (:obj:`Callable`): The schedule function to apply after the warmup for the rest of training. warmup_steps (:obj:`int`): The number of steps for the warmup part of training. power (:obj:`float`, `optional`, defaults to 1): The power to use for the polynomial warmup (defaults is a linear warmup). name (:obj:`str`, `optional`): Optional name prefix for the returned tensors during the schedule. """ def __init__( self, initial_learning_rate: float, decay_schedule_fn: Callable, warmup_steps: int, power: float = 1.0, name: str = None, ): super().__init__() self.initial_learning_rate = initial_learning_rate self.warmup_steps = warmup_steps self.power = power self.decay_schedule_fn = decay_schedule_fn self.name = name def __call__(self, step): with tf.name_scope(self.name or "WarmUp") as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. global_step_float = tf.cast(step, tf.float32) warmup_steps_float = tf.cast(self.warmup_steps, tf.float32) warmup_percent_done = global_step_float / warmup_steps_float warmup_learning_rate = self.initial_learning_rate * tf.math.pow(warmup_percent_done, self.power) return tf.cond( global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: self.decay_schedule_fn(step - self.warmup_steps), name=name, ) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name, } boundaries = [21093, 34376] values = [0.1, 0.01, 0.001] learning_rate_fn = tf.keras.optimizers.schedules.PiecewiseConstantDecay(boundaries, values) warmup_shcedule = WarmUp(initial_learning_rate = 0.1, decay_schedule_fn = learning_rate_fn, warmup_steps = 7813) optimizer = tf.keras.optimizers.SGD(learning_rate = warmup_shcedule, momentum = 0.9, decay = 0.0, nesterov = False) I then train model using “tf.GradientTape” and view the learning rate as follows: optimizer._decayed_lr('float32').numpy() The resulting learning during the 60 epochs of training can be viewed: [learning rate scheduler](https://preview.redd.it/wbx65esp3pt61.png?width=559&format=png&auto=webp&s=5a3bdc23bf796da6e6d367e1c9cbd49fd160a4f6) You can access the complete code [here](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/VGG18_Train_from_scratch-LR_Warmup_%26_Step_Decay.ipynb). Since I am new to PyTorch, can you show me how I can achieve the same learning rate scheduler in torch? Thanks
1
t3_msn34u
1,618,648,586
pytorch
Dynamic Hyper-parameters: Change hyper-parameter values while a model is training
*Hyper-parameters control the learning process of models. They are set before training starts, either by intuition or a hyper-parameter search. They either stay static or change based on a pre-determined schedule. We are introducing dynamic hyper-parameters which can be manually adjusted during the training based on model training stats.* Github: [https://github.com/lab-ml/labml/blob/master/guides/dynamic\_hyperparameters.md](https://github.com/lab-ml/labml/blob/master/guides/dynamic_hyperparameters.md) ## What are hyper-parameters? Hyper-parameters are parameters that control the learning process of models, such as the learning rate, batch size, and weight decay. The model might not learn if the hyper-parameters are not set correctly. Setting hyper-parameters is a key part of deep learning research. Researchers find them based on intuition or by running a hyper-parameter search. In a hyper-parameter search, the model is trained repeatedly with different hyper-parameters to find the best set of hyper-parameters. Hyper-parameter search becomes costly as the number of hyper-parameters increases and the model training time increases. Some hyper-parameters change during the training based on a pre-determined schedule. For example, you could slowly decrease the learning rate, or you could decrease the coefficient of an auxiliary loss as the model learns. Finding these schedules is nearly impossible with a hyper-parameter search, and are usually determined based on the intuition of the researchers. ## Why is it hard to determine hyper-parameters? Setting hyper-parameters require quite a bit of experience with the kind of models and sizes you are training as well as the dataset. For instance, consider fine-tuning a pre-trained language model to classify tweets. You get a pre-trained language model as the backbone and attach a layer (or two) as the classification head. First, you freeze the parameters of the backbone and train the head for a certain number of updates, and then you unfreeze all parameters and train all the parameters. The number of steps to keep the backbone frozen is generally set to 1 epoch. This is a hyper-parameter. And the common practice of freezing for 1 epoch might be too small or too large depending on the size of the model as well as the dataset size. Someone who has worked with similar models and datasets will have a good intuition on this hyper-parameter. If you are new, you will have to try training the model to get a feel about it. <!-- Now consider setting the reward discount factor in a reinforcement learning agent. This determines how much the future rewards are discounted when considering the current step. A lower discount factor will only give rewards from the next few steps, whilst a discount factor close to one will get rewards from all future steps. That is, a smaller discount factor will make the agent short-sighted. It's generally faster to train agents initially with a small discount factor and increase it to be close to one towards the end of the training. Knowing how fast to change this is difficult. You will know by intuition if you have trained agents in the same environment before. Otherwise, you will have to run a few training sessions and study them to get a better understanding. --> ## ⚙️ Introducing Dynamic Hyper-parameters Dynamic hyper-parameters are hyper-parameters that researchers can adjust while the model is being trained. This allows researchers to actively control how the model trains, instead of letting the model train with a pre-determined set of hyper-parameters. Dynamic hyper-parameters help train the model faster and better on a single training session. Also, they let researchers play around with the hyper-parameters during a single training run to gather insights. Sometimes researchers save the model checkpoints and restart the training with changed hyper-parameter values. This has a similar effect to dynamic hyper-parameters but it's quite cumbersome to do. ## How does it work? You need to create a dynamic hyper-parameter and register them along with other configurations. from labml import experiment from labml.configs import FloatDynamicHyperParam lr = FloatDynamicHyperParam(2.5e-4, range_=(0, 0.1)) experiment.configs({ 'learning_rate': lr, ..., }) Then can call the dynamic hyper-parameter to get the current value. For example: def train(batch): optimizer.set_lr(lr()) optimizer.step() The call `lr()` will return the current learning rate set in [labml.ai](https://labml.ai) [app](https://github.com/lab-ml/app). [This is a screenshot of the mobile web interface](https://github.com/lab-ml/labml/blob/master/guides/dynamic_hp.png) *for changing dynamic hyper-parameters. In this* [*Demo*](https://app.labml.ai/run/6eff28a0910e11eb9b008db315936e2f/hyper_params) *experiment we adjusted the learning rate, clipping range, and the number of training epochs (per sample) to speed up the training of a* [*PPO agent (code)*](https://nn.labml.ai/rl/ppo/experiment.html) *for Atari Breakout. A standard learning rate decay and other static hyper-parameter values would have taken a lot of training updates to get over the score of 1.* ## Example use-cases **Freezing pre-trained layers**: When fine-tuning a language model, you can train with the backbone frozen until the rate of improvement of loss drops, and change the hyper-parameter affecting which layers are frozen. This is better and faster than going with the common practice of keeping the backbone frozen for 1 epoch for all models and datasets. **Learning-rate warm-up and decay**: The learning rate can be manually increased during the initial training updates. You could decide how long to warm up for based on the loss curves. Similarly, you can decay the learning rate when the loss values stabilize. This allows you to use higher learning rates initially to speed up the training. **Increase sequence length**: Recurrent models train faster when the BPTT length is shorter. But you need higher BPTT lengths to improve accuracy. Therefore, it is a common practice to start with a shorter BPTT length and increase it later. Again deciding when to do this beforehand is hard. Changing this dynamically is a lot easier. **Adjusting regularization parameters**: You can start with lower weight decay and lower dropout probabilities initially. Especially if you are not sure about the representation capacity of the model. You can then increase these regularization parameters later when the validation loss stops improving (higher variance). **Adjusting reinforcement learning hyper-parameters**: Reinforcement learning tends to have more hyper-parameters. Most of which need to change during training, such as discount factor, entropy-bonus coefficients, learning-rate, etc. Pre-determining them is almost impossible without observing a few training runs, and those training runs go many hours or days even for simple gaming environments. Changing these during training based on the agent's performance and other stats is a lot easier. ## What's next **Updating hyper-parameter schedules**: Our current implementation only allows users to update hyper-parameter values. This can take too much user time. For instance, let's say based on current loss curves the user figures out that he wants to drop the learning rate from `1e-3` to `2.5e-4` during the next 100,000 updates. With our current implementation, she would have to make several manual changes. We want to let users set and update hyper-parameter schedules so that user has to manually intervene only when necessary. **Rewind**: Often when training with dynamic hyper-parameters you feel like experimenting with them. Sort of like a small hyper-parameter search while the model is training. But when things go wrong you want to reset. To enable this we are working on a simple rewind (or undo) option, where the user could restart at any checkpoint, with a couple of taps on the screen.
1
t3_mqq0ca
1,618,405,078
pytorch
At which linguistic patterns and features attention heads of BERT look to ?
Hello, I am developing an extractive text summarizer for french language, I would like to explore the self-attention mechanism to see at which linguistic patterns it looks to by generating a heat map or? Any help?
1
t3_mq3q2m
1,618,325,167
pytorch
Docker container getting crashed while serving Pytorch models
I have to deploy some PyTorch models (around 4) in production, for demonstration purpose I have created a minimal code showing how I am deploying the models using `Flask` and `Docker Swarm` Problem is that when I load test the `API` endpoints I found that memory utilization of container/service increases and it crashes after some time, I tried increasing the container memory limit in a `docker-compose.yml` file but it only extends crashing time Here is the code https://preview.redd.it/7i1igpagrvs61.png?width=228&format=png&auto=webp&s=0ac25b3d481417078350629f7f061e75f7574278 **app.py** from flask import Flask, request, jsonify import numpy as np import cv2 as cv import traceback import json from predict_l import get_prediction_l from predict_x import get_prediction_x app = Flask(__name__) @app.route('/') def index(): return jsonify('Serving Yolov5 Pytorch models') @app.route('/prediction_l', methods = ['POST']) def prediction_l(): try: f1 = request.files['image'] f2 = np.fromstring(f1.read(), np.uint8) f3 = cv.imdecode(f2, cv.IMREAD_COLOR) res = get_prediction_l(f3) except Exception as e: print(str(traceback.format_exc())) return json.dumps(res) @app.route('/prediction_x', methods = ['POST']) def prediction_x(): try: f1 = request.files['image'] f2 = np.fromstring(f1.read(), np.uint8) f3 = cv.imdecode(f2, cv.IMREAD_COLOR) res = get_prediction_x(f3) except Exception as e: print(str(traceback.format_exc())) return json.dumps(res) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) **predict\_l.py** import torch import os os.environ["CUDA_VISIBLE_DEVICES"]="" model = torch.hub.load('ultralytics/yolov5', 'custom', path_or_model='model/yolov5l.pt') def get_prediction_l(image): # Inference results = model(image) # Results results.print() # Data pred_res = results.xyxy[0].tolist() return pred_res [Complete code](https://gist.github.com/atinesh-s/e2d1370b4898c2a62ae7af3c1b22e328)
1
t3_mpwbn3
1,618,293,727
pytorch
ValueError: Expected target size (384, 384), got torch.Size([384, 384, 384])
Hello! I am working on a quite complicated CNN which is already given and my task is, too retrain a model. The goal from the CNN is, that you can give it a Picture of a face and it will give you a voxelised Face-Modell The network is can be found here: [https://github.com/amadeuzou/vrn-pytorch/blob/master/vrn\_unguided.py](https://github.com/amadeuzou/vrn-pytorch/blob/master/vrn_unguided.py) i modified it a bit. The output should be in a Voxel-Like Shape. I now need too train this model with a dataset i got. For this i wrote a training script (i am very new too pytorch) and in my mind this script should work but it throws the error : `ValueError: Expected target size (384, 384), got torch.Size([384, 384, 384])` which does not make sense for me. I am loading a picture using CV and transform it in a numpy 384 \* 384 \* 3 array. This Input is then processed too a 384 \* 384 \* 384 Voxel Volume. However my problem is now: By running this script : (the data is load manually since i have only a small amount of data rn) `for epoch in range(20):` `print(epoch)` `VRN.train()` `predicted_model = VRN(inp)[-1].data.cpu()` `vol = predicted_model[0].numpy()` `optimizer.zero_grad()` `loss = lossfct(torch.from_numpy(vol), torch.from_numpy(voxel_array))` `loss.backward()` `print(loss)` `optimizer.step()` it gives me the error which is said above. This does not make sense for me since the input and the target both are in the same dimension (384, 384, 384). The Lossfunction is CrossEntropyLoss What should i do too solve this error? If needed i can show the full script.
0.5
t3_mopkqf
1,618,141,377
pytorch
Oop concepts for pytorch
Hello, I was going through an oop in pytorch tutorial the other day to prepare myself for when I learn pytorch. I had learned about the basics of consutructors, inheritance, and how to write functions. I had also learned about attributes and the “self” keyword. The rest of the sections go over exceptions, setters and getters, properties, global variables, etc, but I don’t often see these used much in pytorch code I have seen. Should I still learn that stuff? How much of oop class design do you need to know or what oop concepts should you be comfortable with before learning pytorch?
0.89
t3_mopkck
1,618,141,334
pytorch
torch.tensor. 'module' object not callable
I'm getting some strange error which seems to have been resolved in previous versions in pytorch. I'm running on OS: ubuntu 20.04 pytorch: from source (1.9.0a0+gite359842) CUDA: 11.2 Every torch code with cuda I've run so far works, but a simple torch.tensor() call gives me an error: TypeError: 'module' object is not callable. It's strange because if I go to the terminal and run a simple python code such as: >> import torch >> a = torch.tensor([[1., -1.], [1., -1.]], dtype=torch.uint8, device='cuda:0').unsqueeze(0) It'll run fine but if I used the same code to instantiate a tensor in my .py file, it throws an error. I even tried the exact same code in a new file and it works. There's no other folder/file in my directory called 'torch' or 'tensor' so it can't be an issue with that.
0.5
t3_mokf1o
1,618,115,873
pytorch
How can I set a minimum learning rate in lr_scheduler LambdaLR?
I'm using LambdaLR as a learning rate function: import torch import torch.nn as nn import matplotlib.pyplot as plt model = torch.nn.Linear(2, 1) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) lambda1 = lambda epoch: 0.99 ** epoch scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1, last_epoch = -1) lrs = [] for i in range(2001): optimizer.step() lrs.append(optimizer.param_groups[0]["lr"]) scheduler.step() plt.plot(lrs) https://preview.redd.it/929711v9vfs61.png?width=786&format=png&auto=webp&s=72c52ef9788a7ff3b407569270bdaa839a71569b I'm trying to set a min learning rate so it won't go to 0. How can I do that?
1
t3_mogkjb
1,618,100,941
pytorch
Growing neural cellular automata - Implementation from scratch
nan
1
t3_mo8n25
1,618,074,414
pytorch
Need help with anaconda and cuda
**~\anaconda3\lib\site-packages\torch\cuda\__init__.py in _lazy_init() 168 # This function throws if there's a driver initialization error, no GPUs 169 # are found or any other error occurs 170 torch._C._cuda_init() 171 # Some of the queued calls may reentrantly call _lazy_init(); 172 # we need to just return without initializing in that c**ase. RuntimeError: CUDA driver initialization failed, you might not have a CUDA gpu. I have already cheacked my gpu drivers my cuda version and gpu drivers pytorch 1.8.1 cuda 11.1.1 cudnn 8.0 https://i.stack.imgur.com/nuL9L.png
1
t3_mnmikf
1,617,989,996
pytorch
Pruning tutorial
Hey guys, I am looking for neural network pruning tutorials/implementations. I looked into [torch.nn.utils.prune](https://pytorch.org/docs/master/generated/torch.nn.utils.prune.global_unstructured.html) module but it doesn't present an end-to-end example and the [code](https://github.com/arjun-majumdar/Neural_Network_Pruning/blob/main/Iterative_Pruning_LeNet300_PyTorch.ipynb) that I came up with doesn't seem to work. Help?
1
t3_mndfdg
1,617,960,140
pytorch
Need help with a doubt
In my model , how to define output in training section of the code ? Sorry for such a basic question for epoch in range(num_epochs) for data in trainset: X, y = data model.zero_grad() output = ?
1
t3_mnc8r0
1,617,954,388
pytorch
Tensor Sizes Not Matching (ERROR)
Hi, I am working on this image classification model and I have 120 different types of images. I have read them all as grayscale and resized them to be 50x50 px. Here is the code for the model: ​ data = np.load("training_data.npy", allow_pickle=True)[0] labels = np.load("training_data.npy", allow_pickle=True)[1] training_data = [] for i in range(len(data)): training_data.append([np.array(data[i]), np.eye(120)]) np.random.shuffle(training_data) for item in training_data: item[0] = item[0][:147] device = torch.device("cuda:0") class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 5) self.conv2 = nn.Conv2d(32, 64, 5) self.conv3 = nn.Conv2d(64, 128, 5) self.pool1 = nn.MaxPool2d((2, 2)) self.pool2 = nn.MaxPool2d((2, 2)) self.pool3 = nn.MaxPool2d((2, 2)) # commenting out fc layers, replace value with our output self.fc1 = nn.Linear(512, 512) self.fc2 = nn.Linear(512, 120) def forward(self, x): x = F.relu(self.conv1(x)) x = self.pool1(x) x = F.relu(self.conv2(x)) x = self.pool2(x) x = F.relu(self.conv3(x)) x = self.pool3(x) x = x.flatten(start_dim=1) # flattening out # print(x.shape) # printing the shape of the flattened output x = F.relu(self.fc1(x)) x = self.fc2(x) return F.softmax(x, dim=1) net = Net().to(device) #net.forward(torch.randn(1, 1, 50, 50).to(device)) # passing a sample input (random) print(net) print(device) print(len(training_data)) optimizer = optim.Adam(net.parameters(), lr=0.001) loss_function = nn.MSELoss() X = torch.Tensor([i[0] for i in training_data]).view(-1,50,50) X = X/255.0 y = torch.Tensor([i[1] for i in training_data]) print(y[0]) VAL_PCT = 0.1 # lets reserve 10% of our data for validation val_size = int(len(X)*VAL_PCT) print(val_size) train_X = X[:-val_size] train_y = y[0][:-val_size] test_X = X[-val_size:] test_y = y[0][-val_size:] print(len(train_X), len(test_X)) for epoch in range(EPOCHS): for i in tqdm(range(0, len(train_X), BATCH_SIZE)): # from 0, to the len of x, stepping BATCH_SIZE at a time. [:50] ..for now just to dev #print(f"{i}:{i+BATCH_SIZE}") batch_X = train_X[i:i+BATCH_SIZE].view(-1, 1, 50, 50).to(device) batch_y = train_y[i:i+BATCH_SIZE].to(device) net.zero_grad() outputs = net(batch_X) loss = loss_function(outputs, batch_y) loss.backward() optimizer.step() # Does the update print(f"Epoch: {epoch}. Loss: {loss}") correct = 0 total = 0 with torch.no_grad(): for i in tqdm(range(len(test_X))): real_class = torch.argmax(test_y[i]).to(device) net_out = net(test_X[i].view(-1, 1, 50, 50).to(device))[0] # returns a list, predicted_class = torch.argmax(net_out) if predicted_class == real_class: correct += 1 total += 1 print("Accuracy: ", round(correct/total, 3)) When I run the program I run into this error: /usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py:528: UserWarning: Using a target size (torch.Size([0])) that is different to the input size (torch.Size([100, 120])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. return F.mse_loss(input, target, reduction=self.reduction) 0%| | 0/159 [00:00<?, ?it/s] Traceback (most recent call last): File "MLFINAL.py", line 126, in <module> loss = loss_function(outputs, batch_y) File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 889, in _call_impl result = self.forward(*input, **kwargs) File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py", line 528, in forward return F.mse_loss(input, target, reduction=self.reduction) File "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py", line 2928, in mse_loss expanded_input, expanded_target = torch.broadcast_tensors(input, target) File "/usr/local/lib/python3.6/dist-packages/torch/functional.py", line 74, in broadcast_tensors return _VF.broadcast_tensors(tensors) # type: ignore RuntimeError: The size of tensor a (120) must match the size of tensor b (0) at non-singleton dimension 1 At this point I have honestly no clue what to do. Any help would be amazing!
1
t3_mn6v3e
1,617,932,835
pytorch
Pretrained image classification model for nuts and bolts (or similar)
Hello! I'm looking for some pre trained image classification models to use with PyTorch on a Jetson Nano. I already know about the model zoo and the pre trained models included in the [https://github.com/dusty-nv/jetson-inference](https://github.com/dusty-nv/jetson-inference) repo. For demonstration purposes, however, I need a model trained on small objects from the context of production, ideally nuts, bolts, and similar small objects. Does anyone happen to know a source for this? Thanks a lot!
0.81
t3_mmn9th
1,617,870,495
pytorch
Combine 2 tensors
I have 2 tensors of size 100 each: a = torch.ones(100) b = torch.zeros(100) I'm trying to combine them to a tensor that looks like this: c = \[\[1,0\],\[1,0\],\[1,0\]...\[1,0\] \] How can I do that in an efficient way?
1
t3_mm39jb
1,617,805,538
pytorch
Latest Innovations with Grid.ai and PyTorch Lightning
Join us on April 13th at 11 am ET to hear about Grid.ai and PyTorch Lightning's latest innovations with our CEO and Founder William Falcon and Thomas Chaton, Research Engineering Manager. This discussion is excellent for AI researchers, machine learning engineers, and data scientists looking for new ways to accelerate and improve their current AI model training process. Leave with tangible strategies, new tools, and great ideas. Register now and submit any questions you have for William and Thomas! [https://zoom.us/webinar/register/1016176774118/WN\_yW66h71HSz-MXWNGAu6OOg](https://zoom.us/webinar/register/1016176774118/WN_yW66h71HSz-MXWNGAu6OOg)
0.5
t3_mloj4u
1,617,750,732
pytorch
Latest Innovations with Grid.ai and PyTorch Lightning
Join us on April 13th at 11 am ET to hear about Grid.ai and PyTorch Lightning's latest innovations with our CEO and Founder William Falcon and Thomas Chaton, Research Engineering Manager. This discussion is excellent for AI researchers, machine learning engineers, and data scientists looking for new ways to accelerate and improve their current AI model training process. Leave with tangible strategies, new tools, and great ideas. Register now and submit any questions you have for William and Thomas! [https://zoom.us/webinar/register/1016176774118/WN\_yW66h71HSz-MXWNGAu6OOg](https://zoom.us/webinar/register/1016176774118/WN_yW66h71HSz-MXWNGAu6OOg)
0.54
t3_mlogf5
1,617,750,513
pytorch
How to differentiate a gradient in Pytorch
I'm trying to differentiate a gradient in PyTorch. I found [this](https://stackoverflow.com/questions/49149699/differentiate-gradients) link but can't get it to work. My code looks as follows: import torch from torch.autograd import grad import torch.nn as nn import torch.optim as optim class net_x(nn.Module): def __init__(self): super(net_x, self).__init__() self.fc1=nn.Linear(2, 20) self.fc2=nn.Linear(20, 20) self.out=nn.Linear(20, 4) def forward(self, x): x=self.fc1(x) x=self.fc2(x) x=self.out(x) return x nx = net_x() r = torch.tensor([1.0,2.0]) nx(r) >>>tensor([-0.2356, -0.7315, -0.2100, -0.6741], grad_fn=<AddBackward0>) But when I try to differentiate the function with respect to the first parameter grad(nx, r[0]) I get the error TypeError: 'net_x' object is not iterable
1
t3_mllx32
1,617,743,682
pytorch
Predicting Four Variables Using Three Variables
Hi, I have a dataset of 8M rows with 7 numerical features (hearing test audiogram data) and was tasked with predicting 4 variables based on 3. This is how the provided dataset looks like (used fake numbers). Does anyone know what model/approach is the best? I'm thinking Neural Network given the size.. but also have never used multiple independent AND dependent variables before... Any and all pointers are appreciated!! https://preview.redd.it/ltlalc3hplr61.png?width=781&format=png&auto=webp&s=7cbef4f1c9b5e8da7fa67594e85fefcb51b82a55
0.84
t3_mlj2g8
1,617,735,776
pytorch
Example help
I'm looking for an example pytorch example for an inverted pendulum on a cart where the gains are defined and you create a NN to update gains based on initial offset angle and force. I haven't found any good examples with code and was wondering if there were resources for this (sorry new to ML)?
1
t3_mkz983
1,617,669,467
pytorch
Weird assertion error
I asked this on SO but didn't get any useful answers. I'm really confused to why I'm having this error. The error I'm getting is `RuntimeError: all only supports torch.uint8 and torch.bool dtypes` . This happens when I run assertion to check for data leakage. [Link to SO question](https://stackoverflow.com/questions/66924836/runtimeerror-all-only-supports-torch-uint8-and-torch-bool-dtypes)
1
t3_mkqhcf
1,617,644,946
pytorch
Gradients of model output layer and intermediate layer wrt inputs
I’m trying to visualize model layer outputs using the [saliency core package](https://github.com/PAIR-code/saliency) package on a simple conv net. This requires me to compute the gradients of the model output layer and intermediate convolutional layer output w.r.t the input. I’ve attempted to do this in the last code block, but I run into the error RuntimeError: grad can be implicitly created only for scalar outputs . How do I retrieve these gradients and what is this error telling me? ​ \`\`\` `import torch` `import torch.nn as nn` `import torchvision` `from torchvision import datasets, transforms` `from` [`torch.utils.data`](https://torch.utils.data) `import DataLoader` `import numpy as np` `from tqdm.notebook import tqdm` `device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")` `from google.colab import drive` `drive.mount('/content/drive')` `root = '/content/drive/MyDrive/Work/ExplainMNIST'` `import os` `# !pip install saliency` `import saliency.core as saliency` ​ `# Hyperparameters` `batch_size = 32` `num_classes = 10` ​ `data_dir = os.path.join(root, "data")` `mnist_train = torchvision.datasets.MNIST(data_dir, train=True, transform=transforms.Compose([` `transforms.ToTensor(),` `transforms.Normalize((0.1307,), (0.3081))` `]), download=True)` `mnist_test = torchvision.datasets.MNIST(data_dir, train=False, transform=transforms.Compose([` `transforms.ToTensor(),` `transforms.Normalize((0.1307,), (0.3081))` `]), download=True)` `train_loader = DataLoader(mnist_train, batch_size=batch_size, shuffle=True)` `test_loader = DataLoader(mnist_test, batch_size=batch_size, shuffle=True)` `checkpoint_dir = os.path.join(root, 'checkpoints')` `if not os.path.exists(checkpoint_dir):` `os.makedirs(checkpoint_dir)` ​ `images_, labels_ = next(iter(train_loader))` `images_ = images_.to(device)` `labels_ = labels_.to(device)` ​ `class ConvNet(nn.Module):` `def __init__(self, in_channels, num_classes):` `super(ConvNet, self).__init__()` `self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=10, kernel_size=3)` `self.pool1 = nn.MaxPool2d(3)` `self.conv2 = nn.Conv2d(in_channels=10, out_channels=10, kernel_size=3)` `self.activation = nn.ReLU()` `self.fc = nn.Linear(360, num_classes)` `def forward(self, x):` `x = self.conv1(x)` `x = self.pool1(x)` `x = self.activation(x)` `x = self.conv2(x)` `x = self.activation(x)` `conv = x` `x = self.fc(x.reshape(x.shape[0], -1))` `return {'output': x, 'conv': conv}` ​ `model = ConvNet(1, num_classes)` `model =` [`model.to`](https://model.to)`(device)` `model.eval()` ​ `#HELP! here is my attempt` `with torch.set_grad_enabled(True):` `output, conv = model(images_).values()` `output_class = output[:, 0]` `# Here is how i tried to do it` `grads = torch.autograd.grad(output, images_)` `grads2 = torch.autograd.grad(conv, images_)`
1
t3_mk987e
1,617,584,725
pytorch
Iterative Pruning: LeNet-300-100 - PyTorch
I am trying to implement iterative pruning algorithm (as described in the research papers in [\[1\]](https://arxiv.org/abs/1506.02626), [\[2\]](https://arxiv.org/abs/1803.03635)) which is: train a model, prune p% of smallest weights per layer, re-train the pruned model and repeat. For experiment purposes, I am using LeNet-300-100 neural network on MNIST. The code can be accessed [here](https://github.com/arjun-majumdar/Lottery_Ticket_Hypothesis-TensorFlow_2/blob/master/LeNet_300_100-Iterative_Pruning.ipynb) Within the function “train\_with\_grad\_freezing(model, epoch)”, I am using the following lines of code for freezing the pruned weights by making their computed gradients equal to 0: for layer_name, param in model.named_parameters(): if 'weight' in layer_name: tensor = param.data.cpu().numpy() grad_tensor = param.grad.data.cpu().numpy() grad_tensor = np.where(tensor == 0, 0, grad_tensor) param.grad.data = torch.from_numpy(grad_tensor).to(device) The first time I train the model, the code works fine after which I prune the layers by using the code: # Prune 15% of smallest magnitude weights in FC layers and 10% in output layer- pruned_d = prune_lenet(model = best_model, pruning_params_fc = 15, pruning_params_op = 10) # Initialize and load pruned Python3 dict into a new model- pruned_model = LeNet300() pruned_model.load_state_dict(pruned_d) However, on re-training this pruned model, the training metric is stuck for these values: >training loss = 0.0285, training accuracy = 99.04%, val\_loss = 0.0910 & val\_accuracy = 97.68% What’s going wrong?
1
t3_miz3p6
1,617,415,553
pytorch
Exception: process 0 terminated with exit code 1 when use torch.multiprocessing.spawn on GPUs
nan
1
t3_miulhe
1,617,400,332
pytorch
How to fix and find the source of the exception: Exception: process 1 terminated with exit code 1 for multiple GPU training with DDP and Pytorch
nan
1
t3_miul9q
1,617,400,315
pytorch
tgt and src have to have equal features for a Transformer Network in Pytorch
I am attempting to train EEG data through a transformer network. The input dimensions are 50x16684x60 (seq x batch x features) and the output is 16684x2. Right now I am simply trying to run a basic transformer, and I keep getting an error telling me ​ \`RuntimeError: the feature number of src and tgt must be equal to d\_model\` ​ Why would the source and target feature number ever be equal? Is it possible to run such a dataset through a transformer? ​ Here is my basic model: ​ `input_size = 60 # seq x batch x features` `hidden_size = 32` `num_classes = 2` `learning_rate = 0.001` `batch_size = 64` `num_epochs = 2` `sequence_length = 50` `num_layers = 2` `dropout = 0.5` ​ `class Transformer(nn.Module):` `def __init__(self, input_size, hidden_size, num_layers, num_classes):` `super(Transformer, self).__init__()` `self.hidden_size = hidden_size` `self.num_layers = num_layers` `self.transformer = nn.Transformer(60, 2)` `self.fc = nn.Linear(hidden_size * sequence_length, num_classes)` `def forward(self, x, y):` `# Forward Propogation` `out, _ = self.transformer(x,y)` `out = out.reshape(out.shape[0], -1)` `out = self.fc(out)` `return out` ​ `model = Transformer(input_size, hidden_size, num_layers, num_classes)` ​ `criterion = nn.MSELoss()` `optimizer = optim.Adam(model.parameters(), lr=learning_rate)` ​ `for epoch in range(num_epochs):` `for index in tqdm(range(16684)):` `X, y = (X_train[index], Y_train[index])` `print(X.shape, y.shape)` `output = model(X, y)` ​ `loss = criterion(output, y)` `model.zero_grad()` `loss.backward()` `optimizer.step()` `if index % 500 == 0:` `print(f"Epoch {epoch}, Batch: {index}, Loss: {loss}")`
1
t3_mis588
1,617,393,208
pytorch
Introducing PyTorch Profiler – The New And Improved Performance Debugging Profiler For PyTorch
The analysis and refinement of the large-scale deep learning model’s performance is a constant challenge that increases in importance with the model’s size. Owing to a lack of available resources, PyTorch users had a hard time overcoming this problem. There were common GPU hardware-level debugging tools, but PyTorch-specific background of operations was not available. Users had to merge multi-tools or apply minimal correlation information manually to make sense of the data to retrieve the missing information. The PyTorch Profiler came to the rescue, an open-source tool for precise, efficient, and troubleshooting performance investigations of large-scale deep learning models.  Summary: [https://www.marktechpost.com/2021/04/02/introducing-pytorch-profiler-the-new-and-improved-performance-debugging-profiler-for-pytorch/](https://www.marktechpost.com/2021/04/02/introducing-pytorch-profiler-the-new-and-improved-performance-debugging-profiler-for-pytorch/) Source: https://pytorch.org/blog/introducing-pytorch-profiler-the-new-and-improved-performance-tool/
1
t3_minp5n
1,617,380,486
pytorch
DQN loss from only one output element
I'm trying to implement a simple DQN. And I wonder if I have understood it correctly that it's fine to apply the loss function to only the difference between the (scalar) target and just one element of the output, something like this: ​ def fn_reinforce(self,batch): # (state, action, reward, next_state) for i in range(self.batch_size): if batch[i].next_state is None: Q_target = batch[i].reward Q_predict = self.policy_net(batch[i].state)[0,batch[i].action] loss = self.loss_fn(Q_predict, Q_target) else: with torch.no_grad(): next_Q = torch.max(self.target_net(batch[i].next_state)) Q_target = batch[i].reward + next_Q Q_predict = self.policy_net(batch[i].state)[0, batch[i].action] loss = self.loss_fn(Q_predict, Q_target) self.optimizer.zero_grad() loss.backward() for param in self.policy_net.parameters(): param.grad.data.clamp_(-1, 1) self.optimizer.step()
1
t3_mie3kq
1,617,342,880
pytorch
how can i create multiple 3d meshes and textures of different items/objects from an image using pytorch3d ?
what would be the methods / techniques used for this task ?
0.5
t3_mi08rx
1,617,297,808
pytorch
Why are some tutorials in Github repo missing from pytorch.org/tutorials?
I tried to skim over [pytorch.org](https://pytorch.org/)'s tutorials to find some tutorials I needed. I discovered that some tutorials like [https://pytorch.org/tutorials/beginner/basics/data\_tutorial.html](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) is not included in [https://pytorch.org/tutorials/](https://pytorch.org/tutorials/). However, it is reachable in tutorial's github, [https://github.com/pytorch/tutorials/tree/master/beginner\_source/basics](https://github.com/pytorch/tutorials/tree/master/beginner_source/basics) Why is the website's tutorial not synced properly with Github's tutorial page? Thought it was automated internally to reflect the repo's tutorial to the website. Should I stick to Github repo to access all tutorials without missing out some tutorials?
1
t3_mhzy8l
1,617,297,009
pytorch
Why are some PyTorch missing from pytorch.org/tutorials ?
I tried to skim over [pytorch.org](https://pytorch.org)'s tutorials to find some tutorials I needed. I discovered that some tutorials like [https://pytorch.org/tutorials/beginner/basics/data\_tutorial.html](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) is not included in [https://pytorch.org/tutorials/](https://pytorch.org/tutorials/). ​ However, it is reachable in tutorial's github, [https://github.com/pytorch/tutorials/tree/master/beginner\_source/basics](https://github.com/pytorch/tutorials/tree/master/beginner_source/basics) ​ Why is the website's tutorial not synced properly with Github's tutorial page? Thought it was automated internally to reflect the repo's tutorial to the website. Should I stick to Github repo to access all tutorials without missing out some tutorials?
0.92
t3_mhqolu
1,617,264,898
pytorch
What is the difference between these two Net class declarations?
class Net(nn.Module): def __init__(self): super(Net, self).__init__() and class Net(nn.Module): def __init__(self): super().__init__() functionally what is the difference between these two?
1
t3_mhcgu4
1,617,215,461
pytorch
Help understanding how to implement multiple loss functions
Hey guys, had a quick question that I was hoping someone here could help out with. ​ I was going to run some experiments comparing MC Dropout to Bayes by Backprop. My implementation is like this: Run some images through efficientNetb0 and then extract the output and push that output through a single dense 512 layer. Then at test time run 100 forwards passes for each image and average the results. For MC Dropout I think this is rather easy, just train the network normally (but don't turn off dropout at test time). For my Bayesian layers however, I'm not sure how to handle the loss (the variational free energy) for the Bayesian layer while also using Cross entropy to train the efficientNet model? How is it that you're supposed to do this? Do I just work out the variational free energy using the outputs and then get the cross entropy loss of the same outputs and add those two together? ​ Any help at all would be appreciated.
1
t3_mgn660
1,617,130,509
pytorch
Hotword Detection
Hello, I'm currently learning Machine Learning and want to implement Hotword Detection with Pytorch. I watched countless of videos, spent hours searching the internet for somewhat useable information, but yeah. I don't understand much of it. Can someone provide me a brief guide (with resources, would really appreciate that, if possible) or explain it to me like to an idiot? I know that for time-series it's preferably to use a RNN, but how do I process the audio-data with Pytorch and train with that?
1
t3_mgjcri
1,617,120,185
pytorch
[torchtext] Checking whether batches assign the right row number to the text (rows) in the dataset
Hi, We are using the standard Fields, TabularDataset, and BucketIterator classes of torchtext for a proper LSTM implementation with pytorch. Our dataset is a dataframe where every row has a column named "index\_names" with row numbers, "text" column with texts, and "label" column with the true class labels. ​ We need to verify that, the output of BucketIterator, a set of batches of the dataset, has the correct row numbers associated with the text in the dataset, so we can interpret the final results properly. The code is below. How can we make sure every batch in, for example, `train_iter` has the correct row numbers per text (per row)? ​ We appreciate any help and we'd be grateful! ​ `label_field = Field(sequential=False, use_vocab=False, batch_first=True, dtype=torch.float)` `text_field = Field(tokenize='spacy', lower=True, include_lengths=True, batch_first=True)` `fields = [('index_names', label_field), ('text', text_field), ('label', label_field)]` ​ `# TabularDataset` `train, valid, test = TabularDataset.splits(path='./', train='train.csv', validation='valid.csv',` `test='test.csv', format='CSV', fields=fields, skip_header=True)` ​ `# Iterators` `train_iter = BucketIterator(train, batch_size=32, sort_key=lambda x: len(x.text),` `device=device, sort=True, sort_within_batch=True)` `valid_iter = BucketIterator(valid, batch_size=32, sort_key=lambda x: len(x.text),` `device=device, sort=True, sort_within_batch=True)` `test_iter = BucketIterator(test, batch_size=32, sort_key=lambda x: len(x.text),` `device=device, sort=True, sort_within_batch=True)`
1
t3_mfpyxb
1,617,025,774
pytorch
DistributedDataParallel (DDP) Examples
I'm looking for good tutorials on DDP. I usually pride myself on being able to figure things out on my own pretty well, but I've been banging my head against the wall on this one. I've used DataParallel before (which is really easy to use), but I wanted to train on multiple nodes, so I'm trying to learn DDP. The documentation leaves a lot to be desired and every online tutorial I find conflicts with other ones and many seem outdated. Does anyone have suggestions? I have it working on a single node multi-gpu setup, but I run into issues when I try multi-node. It's frustrating that I can't seem to find a single resource that shows an example of torch code that trains on a single gpu, modified to use DDP to train on a multi-node multi-gpu setup, to see exactly what needs to be changed. (Cross posted from [r/deeplearning](https://www.reddit.com/r/deeplearning/) as no one had any suggestions over there - maybe I'm not alone in my confusion?)
0.86
t3_mfpc6q
1,617,023,723
pytorch
[HELP] Confusion regarding last layers of Fully Connected Network
Hello All. I am a beginner in Deep Learning world and have recently studied the concepts. I was trying to build a simple NN on MNIST data. Trying to apply the knowledge. Here goes the flow: * Data Type - 60000 rows; Each row consists: 28 * 28 i.e., 784 columns So, input shape: (60000, 784) * Label - (60000, ) * NN - Simple 3 layered Fully Connected Network. * Loss function: CrossEntropyLoss * Optimizer: SGD. * Output Layer Neurons: 10 (for each digit) via Softmax. * Custom Dataset initialized, fed to DataLoader. Now my understanding is that, I pass on the epoch value, the model trains and returns the output tensor with probabilities and the cross entropy calculates the loss by comparing prediction and ground truth, with optimizer updating gradiants after backpropogation. **HERE IS WHERE MY CONFUSION BEGINS.** I see in **PyTorch** people using: `_ , prediction = torch.max(NNModel, 1)` to get the prediction value. Now what this essentially does is return the index at which highest probability is. E.g., `prediction = 4`. This makes me wonder, whether feeding the whole data to NN, will the output tensors be trained in such a way that: `1st Neuron is for label 1.`. `2nd Neuron is for label 2.`. `And so on up to 9.???? `. How can we compare index received with the ground truth if its not the case and the numbers (in this example) are organised in random order across output layer Neurons??? It might sound stupid but I am really planning to get some practical knowledge and few of these basics are haunting me due to less experience in this field. Any help would be LARGELY appreciated. Thanks.. :)
0.84
t3_meyewz
1,616,924,843
pytorch
GPU comparison & impact
I am planning on buying a laptop and I have two GPU options, viz. RTX 3070 Vs 3080. How much of a difference is there from the point of view of Deep Learning training between these two?
0.5
t3_meszfc
1,616,899,964
pytorch
App that lets you search docs of PyTorch, NumPy, Python, and Stack Overflow at one place
nan
0.97
t3_meknmu
1,616,873,021
pytorch
PyTorch Geometric Temporal 0.24.
[https://github.com/benedekrozemberczki/pytorch\_geometric\_temporal](https://github.com/benedekrozemberczki/pytorch_geometric_temporal) The new release has 2 new attention based models: MTGNN from Connecting the Dots: Multivariate Time Series Forecasting with Graph Neural Networks. GMAN from A Graph Multi-Attention Network for Traffic Prediction We also added a large windmill output forecasting dataset.
0.95
t3_me1fln
1,616,801,637
pytorch
Why does my pytorch distributed training (DDP) code send a SIGKILL signal on it's own?
nan
1
t3_mdsljr
1,616,776,493
pytorch
Design Pattern of Pytorch based machine learning code.
Hello, I am looking for articles or papers on the design patterns of Pytorch based ML programmes and also patterns for the design of Pytorch framework itself. Any pointer or suggested reading will be appreciated. ​ Thanks!
0.9
t3_mdjinz
1,616,745,123
pytorch
Converting PyTorch and TensorFlow Models into Apple Core ML using CoreMLTools
nan
0.67
t3_mdjczc
1,616,744,443
pytorch
Two Layer Network
I am trying to compute the forward pass of a two layer Network but I keep getting this error message. RuntimeError: 1D tensors expected, but got 2D and 2D tensors How do I resolve this issue ? `def nn_loss_part1(params, X, y=None, reg=0.0):` `W1, b1 = params['W1'], params['b1']` `W2, b2 = params['W2'], params['b2']` `N, D = X.shape` `hidden = None` `scores = None` `forwardPass =` [`torch.dot`](https://torch.dot)`(X,W1) + b1` `h = torch.maximum(forwardPass , 0)` `scores =` [`torch.dot`](https://torch.dot)`(h, W2) + b2` `return scores, hidden` `toy_X, toy_y, params = get_toy_data()` `scores, _ = nn_loss_part1(params, toy_X)` `print('Your scores:')` `print(scores)` `print()` `print('correct scores:')` `correct_scores = torch.tensor([` `[-3.8160e-07, 1.9975e-07, 1.0911e-07],` `[-5.0228e-08, 1.2784e-07, -5.2746e-08],` `[-5.9560e-07, 9.1178e-07, 1.1879e-06],` `[-3.2737e-08, 1.8820e-07, -2.8079e-07],` `[-1.9523e-07, 2.0502e-07, -6.0692e-08]], dtype=torch.float32, device=scores.device)` `print(correct_scores)` `print()` `We get < 1e-10` `scores_diff = (scores - correct_scores).abs().sum().item()` `print('Difference between your scores and correct scores: %.2e' % scores_diff)`
1
t3_mdfxlw
1,616,730,115
pytorch
how to debug pytorch c++ source
some methods in pytorch needs to call the function which written by c++? how could I debug with it, just like the python debugging process? thanks
1
t3_mdeo8j
1,616,725,743
pytorch
RNN: Prediction of words using pen points coordinates
Hello i'm trying to build a model that takes pen points coordinates (x,y) as an input and predicts the english word (5 letters or less) as an output. What is the best way to do this using LSTM or GRU ? ​ https://preview.redd.it/xx7lvs00o7p61.png?width=1222&format=png&auto=webp&s=368768d764f6e829eca14f978f080098babed2e2
0.76
t3_md3ooq
1,616,693,517
pytorch
the first time using torchvision ... got the following error, help please
**\~\\anaconda3\\envs\\pytorch\\lib\\site-packages\\torchvision\\datasets\\utils.py** in \_get\_redirect\_url**(url, max\_hops)** 69 70 **def** \_get\_redirect\_url**(**url**:** str**,** max\_hops**:** int **=** **10)** **->** str**:** **---> 71** **import** requests 72 73 **for** hop **in** range**(**max\_hops **+** **1):** **ModuleNotFoundError**: No module named 'requests'
0.38
t3_mcm68e
1,616,634,880
pytorch
Watch Episode 4 - PyTorch Lightning Community Talks
Watch Episode 4 of our Lightning #Community Talks Series with Aishwarya Srinivasan and Sachin Abeywardana, Sr. ML Engineer Canva. They discuss how Sachin uses #PyTorchLightning for training OpenAI's multilingual CLIP. [https://bit.ly/3vZFWBU](https://bit.ly/3vZFWBU) \#deeplearning #NLP https://preview.redd.it/a62jxd4sv1p61.png?width=4444&format=png&auto=webp&s=de9cf2b4619c2dede2dc9065f46d11b7e2d36ebc
1
t3_mci94d
1,616,624,081
pytorch
From MIT CSAIL researchers! Create novel images using GANs! (checkout where they create a new face using faces of 4 different people)
nan
0.75
t3_mcf10p
1,616,615,839
pytorch
Guide To Catalyst - A PyTorch Framework For Accelerated Deep Learning - Analytics India Magazine
nan
0.75
t3_mbdul9
1,616,503,292
pytorch
training on partially annotated images
Before I write a dataloader from the ground up.. my scenario is: * a bunch of images, * each having a (likely) incomplete label list (drawn from about 2000 labels - some map to simplifications of eachother e.g. an image might say 'animal' or 'pet dog', there's a tree which can infer that the label 'pet dog' should also activate the outputs for 'dog' and 'animal') * and some of those labels have bounding box and polygonal annotations I'm thinking it should be possible to have one core net with an output for the whole label list (trained on all images including ones with no annotations), and then train something pixel level for actual annotations I note there's "fully convolutional nets" for using the exact same features for pixel and image level annotations , but they're not as good as dedicated conv/deconv ones (but if thats the only way to utilise such incomplete data, i'll go with it) ​ What about suppressing errors for un-annotaed pixels, in the "partially annotated" case (the vast majority) (absence of an anotation really means "we dont know what this pixel is", rather than the absence of the annotated categories) ​ ​ Is there a common well maintaned existing dataloader that handles this scenario (i'd imagine it's common) ? "ImageFolder" is insufficient for this because there's multiple labels for most images. tbh i'd prefer to filter out the single label images.. they're broad scenes rarely focused on a single object I'm not adverse to writing it myself otherwise.
1
t3_mb4tvd
1,616,467,836
pytorch
Complete Guide to PyKeen: Python KnowlEdge EmbeddiNgs for Knowledge Graphs
Pykeen is a python package that generates [knowledge graph](https://analyticsindiamag.com/knowledge-graphs-are-the-reason-why-you-see-mona-lisa-when-you-google-da-vinci/) embeddings while abstracting away the training loop and evaluation. The knowledge graph embeddings obtained using pykeen are reproducible, and they convey precise semantics in the knowledge graph. Read more: [https://analyticsindiamag.com/complete-guide-to-pykeen-python-knowledge-embeddings-for-knowledge-graphs/](https://analyticsindiamag.com/complete-guide-to-pykeen-python-knowledge-embeddings-for-knowledge-graphs/)
0.92
t3_mag9sc
1,616,392,425
pytorch
[Questions] Implement custom optimizer
Hello community, I want to change the weight update iteration in the SGD optimizer, and I found a code like : lr = 0.001 for param in model.parameters(): weight_update = << something >> param.data.sub_(lr*weight_update) optimizer = torch.optim.SGD(model.parameters(),lr=lr) So instead of updating the weight by the derivative of the loss respect to the weights, I want to customize this term as it is shown like this. `W<-- W - lr*weight_update` The code runs, but the weights are not updating during the training. ​ Any suggestion ?
1
t3_ma62hw
1,616,360,510
pytorch
CNN not updating between epochs
Hi, I am currently implementing a CNN for text sentiment analysis, but for some reason, the model is not updating between epochs. Any advice would be great! Please see code below: ​ Architecture: ​ import torch import torch.nn as nn import torch.nn.functional as F class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv1d(in_channels = 1, out_channels = 1, kernel_size = 20, stride = 2) # 300 in, 141 out self.conv2 = nn.Conv1d(in_channels = 1, out_channels = 1, kernel_size = 10, stride = 2, padding = 1) # 141 in, 67 out self.conv3 = nn.Conv1d(in_channels = 1, out_channels = 1, kernel_size = 7, stride = 2) # 67 in, 31 out self.fc1 = nn.Linear(31, 10) self.fc2 = nn.Linear(10, 3) def forward(self, x): number_instances = x.size()[0] # Store size of x x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = x.view(-1, number_instances, 31) # Flatten Layer x = torch.squeeze(x) # Convert to correct dimensions x = F.relu(self.fc1(x)) x = F.softmax(self.fc2(x), dim = 1) return x convolutional_model = CNN() print(convolutional_model) Data and set up: device = torch.device("cpu") # use cpu x_train = torch.from_numpy(np.asarray(document_embeddings_train)).float() x_train = x_train.unsqueeze(1).to(device) # Add dimension y_train = torch.from_numpy(np.asarray(labels_encoded_train)).long().to(device) x_test = torch.from_numpy(np.asarray(document_embeddings_test)).float() x_test = x_test.unsqueeze(1).to(device) y_test = torch.from_numpy(np.asarray(labels_encoded_test)).long().to(device) optimizer = torch.optim.Adam(convolutional_model.parameters(), lr=0.001) loss_fn = nn.CrossEntropyLoss() convolutional_model = convolutional_model.to(device) loss_fn = loss_fn.to(device) Training: EPOCHS = 5 # Train model for 1000 epochs loss_list = np.zeros((EPOCHS,)) # Initialise variable to store loss for each epoch accuracy_list = np.zeros((EPOCHS,)) # Initialise variable to store the test accuracy for epoch in tqdm.trange(EPOCHS): y_pred = convolutional_model(x_train) # Create model using training data loss = loss_fn(y_pred, y_train) # Compute loss on training data loss_list[epoch] = loss.item() # Save loss to list optimizer.zero_grad() # Zero gradients loss.backward() # Use backpropagation to update weights optimizer.step() with torch.no_grad(): total_correct = 0 predicted_test_labels = convolutional_model(x_test) # Test model predicted_test_labels_list = predicted_test_labels.tolist() actual_test_labels_list = y_test.tolist() for i in range(len(predicted_test_labels_list)): max_prob = max(predicted_test_labels_list[i]) predicted_label = predicted_test_labels_list[i].index(max_prob) actual_label = actual_test_labels_list[i] if predicted_label == actual_label: total_correct += 1 percentage_correct = total_correct/len(actual_test_labels_list) accuracy_list[epoch] = percentage_correct # Save accuracy to list This is returning the same accuracy for each epoch and I can't work out why, thanks in advance for any advice!
1
t3_m9u4wo
1,616,323,532
pytorch
Manually assign weights using PyTorch
I am using Python 3.8 and PyTorch 1.7 to manually assign and change the weights and biases for a neural network. As an example, I have defined a LeNet-300-100 fully-connected neural network to train on MNIST dataset. The code for class definition is: class LeNet300(nn.Module): def __init__(self): super(LeNet300, self).__init__() # Define layers- self.fc1 = nn.Linear(in_features = input_size, out_features = 300) self.fc2 = nn.Linear(in_features = 300, out_features = 100) self.output = nn.Linear(in_features = 100, out_features = 10) self.weights_initialization() def forward(self, x): out = F.relu(self.fc1(x)) out = F.relu(self.fc2(out)) return self.output(out) def weights_initialization(self): ''' When we define all the modules such as the layers in '__init__()' method above, these are all stored in 'self.modules()'. We go through each module one by one. This is the entire network, basically. ''' for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) To experiment with trying to change the weights for this model- ​ # Instantiate model- mask_model = LeNet300() To assign all of the weights in each of the layers to one (1), I use the code- with torch.no_grad(): for layer in mask_model.state_dict(): mask_model.state_dict()[layer] = nn.parameter.Parameter(torch.ones_like(mask_model.state_dict()[layer])) # Sanity check- mask_model.state_dict()['fc1.weight'] This output shows that the weights are not equal to 1. I also tried the code- for param in mask_model.parameters(): # print(param.shape) param = nn.parameter.Parameter(torch.ones_like(param)) But this does not work as well. ​ Help?
1
t3_m9azt9
1,616,259,269
pytorch
Guide To Kornia: An OpenCV-inspired PyTorch Framework - Analytics India Magazine
nan
1
t3_m97mpb
1,616,248,910
pytorch
SIREN implemented from scratch
nan
1
t3_m94ds5
1,616,236,260
pytorch
Model parameters weights and bias
Hi all, I want to print my weights and bias for my model. And I plan to make some statistics on it and change it a bit and put it back. Is it possible to change weights and bias in PyTorch?
0.33
t3_m8jjf1
1,616,167,175
pytorch
Feed Forward NN Loss is calculating NaN
Hi, I'm trying to create a simple feed forward NN, but when computing the loss it is returning NaN. Any advice? Here is my architecture: ​ class Net(nn.Module): def __init__(self,k): super(Net, self).__init__() self.fc1 = nn.Linear(k, 5) # 1st hidden layer takes an input of size k self.fc2 = nn.Linear(5, 3) # Output layer has a size of 3 neurons def forward(self, x): x = F.relu(self.fc1(x)) # ReLu activation for 1st hidden layer x = F.softmax(self.fc2(x), dim=1) # Softmax activation for output layer return x model = Net(300) # Create model for an embedding of size k=300 Here is my optimizer and loss fn: ​ optimizer = torch.optim.Adam(model.parameters(), lr=0.001) loss_fn = nn.CrossEntropyLoss() I was running a check over a single epoch to see what was happening and this is what happened: y_pred = model(x_train) # Create model using training data loss = loss_fn(y_pred, y_train) # Compute loss on training data print(y_pred) print(y_train) print(loss_fn(y_pred, y_train)) The printing returns the following output: tensor([[0.3597, 0.2954, 0.3449], [0.3615, 0.2955, 0.3430], [0.3600, 0.2954, 0.3446], ..., [0.3590, 0.2953, 0.3457], [0.3603, 0.2955, 0.3442], [0.3605, 0.2955, 0.3441]], grad_fn=<SoftmaxBackward>) tensor([0, 0, 0, ..., 0, 2, 0]) tensor(nan, grad_fn=<NllLossBackward>) My Tensors are of length 300 as I am passing in word embeddings with 300 dimensions. Thanks in advance ​ Edit: Here is the code for one specific predicition vs actual: ​ in: print(y_pred[0]) print(y_train[0]) print(loss_fn(y_pred, y_train)) print(loss.item()) out: tensor([0.3079, 0.1110, 0.2661], grad_fn=<SelectBackward>) tensor(0) tensor(nan, grad_fn=<NllLossBackward>) nan Edit 2 - SOLVED: ​ I have sorted out the nan issue by realising some of my embeddings were non-existent due to the preprocessing of the text. Thanks for the help!
1
t3_m8efj2
1,616,150,285
pytorch
Pytorch rans out of gpu memory when model iteratively called.
Hey Guys, I'm using sentence Bert to encode sentences from thousands of files. The model easily fits in gpu, and in each iteration, I load a text sentences, tokenize (return\_type="pt"), and feed that into the model. I repeat this process for each file, so theoretically, if the model runs for one input it must be able to run without any additional gpu memory requirement for all samples. However, after 5% of the samples are processed, I get out of memory error "RuntimeError: CUDA out of memory. Tried to allocate 2.61 GiB (GPU 0; 15.78 GiB total capacity; 5.23 GiB already allocated; 1004.75 MiB free; 13.37 GiB reserved in total by PyTorch)" . Is this a pytorch bug? anyone has faced it before? any workarounds? ​ THanks
0.5
t3_m7v3zo
1,616,086,101
pytorch
Hands-On Guide to Torch-Points3D: A Modular Deep Learning Framework for 3D Data
There has been a surge of advancements in automated analysis of [3D data ](https://analyticsindiamag.com/application-of-data-science-on-3d-imagery-data/)caused by affordable LiDAR sensors, more efficient photogrammetry algorithms, and new neural network architectures. So much that the number of papers related to 3D data being presented at vision conferences is now on par with images, although this rapid methodological development is beneficial to the young field of deep learning for 3D, with its fast pace come several shortcomings:  Read more: [https://analyticsindiamag.com/hands-on-guide-to-torch-points3d-a-modular-deep-learning-framework-for-3d-data/](https://analyticsindiamag.com/hands-on-guide-to-torch-points3d-a-modular-deep-learning-framework-for-3d-data/)
1
t3_m7p7oy
1,616,068,736
pytorch
Installing Pytorch with ROCm but checking if CUDA enabled ? How can I know if I am running on the AMD GPU?
Hi there, This is my first time using Pytorch. I am installing it while trying to use an AMD GPU. My understanding is that I can use the new ROCm platform (I am aware that is in beta) to use Pytorch. ​ How can I check that what I am running is running in the GPU?. I know for CUDA enabled GPUS I can just print torch\*\*.**cuda**.\*\*is\_available(), but how about while using ROCm?. ​ Maybe I am missing something but they do not provide instructions on how to check on their official website for ROCm. [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)
0.79
t3_m7jjbu
1,616,043,585
pytorch
Pytorch C++ and generating CMakeLists.txt for project - can't find <torch/torch.h>
I have a file structure like this: proj/ includes/ foo.h src/ foo.cpp main.cpp Here is my CMakeLists.txt for main.cpp: cmake_minimum_required(VERSION 3.18) project(proj) set(Torch_DIR /path/to/cmake/Torch) find_package(Torch REQUIRED) include_directories(${PROJECT_SOURCE_DIR}/includes ${TORCH_INCLUDE_DIR}) add_subdirectory(includes) add_subdirectory(src) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}") include_directories(includes) include_directories(${OpenCV_INCLUDE_DIRS}) include_directories(${TORCH_INCLUDE_DIR}) add_executable(proj main.cpp) target_link_libraries(seg foo_lib ${OpenCV_LIBS} "${TORCH_LIBRARIES}") set_property(TARGET proj PROPERTY CXX_STANDARD 14) Here is my CMakeLists.txt for includes: set(Torch_DIR /path/to/cmake/Torch) find_package(Torch REQUIRED) include_directories(${PROJECT_SOURCE_DIR}/includes ${TORCH_INCLUDE_DIR}) Here is my CMakeLists.txt for src: include_directories(${PROJECT_SOURCE_DIR}/includes) add_library(foo_lib foo.cpp) Upon executing make I get: fatal error: torch/torch.h: No such file or directory 1 | #include <torch/torch.h> But it can link in main.cpp. So obviously my CMakeLists are not created correctly, so any advice on how to create these properly would be appreciated.
0.33
t3_m7fn37
1,616,029,940
pytorch
gradient of embedding for padded tokens
Hey Guys, [Here](https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html) when explaining nn.Embedding, it says "The gradient for this vector from Embedding is always zero.", I assume once you train the weights, the vector at padding index is no longer going to be all zeros? Even after that the gradient still returns 0?
0.75
t3_m79gl0
1,616,011,952
pytorch
HyperBand and BOHB: understanding hyperparameter optimization algorithms
If you want to learn about state-of-the-art hyperparameter optimization algorithms (HPO), in this article I’ll tell you what they are and how they work. We cover: - A bit about HPO Approaches - What is Bayesian Optimization, and why is this method effective? - How do state-of-the-art Hyperparameter Optimization algorithms work? - **Hyperband vs BOHB comparison** [HyperBand vs. BOHB](https://neptune.ai/blog/hyperband-and-bohb-understanding-state-of-the-art-hyperparameter-optimization-algorithms?utm_source=reddit&utm_medium=post&utm_campaign=blog-hyperband-and-bohb-understanding-state-of-the-art-hyperparameter-optimization-algorithms&utm_content=pytorch)
1
t3_m658nh
1,615,887,477
pytorch
What is Trax and How is it a Better Framework for Advanced Deep Learning?
nan
0.33
t3_m5iee1
1,615,806,818
pytorch
Guide To PyTorch Metric Learning: A Library For Implementing Metric Learning Algorithms
nan
0.88
t3_m5hfcw
1,615,802,801
pytorch
Object localization from scratch
I am reading and watching tutorials for performing object localization. Lately, I watched this [video](https://www.youtube.com/watch?v=GSwYGkTfOKk) from Andrew Ng who proposes different loss functions for the target label 'y'. Now, theoretically, I understand the underlying concepts, however, can you point me to code examples implementing this from scratch with an associated dataset? Thanks!
0.81
t3_m5bsup
1,615,779,305
pytorch
Fast weights transformer implementation/tutorial
We added an implementation of “Linear Transformers Are Secretly Fast Weight Memory Systems” to our collection of paper implementations with notes in PyTorch. Annotated code: [https://nn.labml.ai/transformers/fast_weights/index.html](https://nn.labml.ai/transformers/fast_weights/index.html) This paper by Imanol Schlag, Kazuki Irie and Jürgen Schmidhuber compares self attention to fast weight systems and introduces a new linear self attention update rule and a projection function. We have also implemented a simple experiment to train the model on the Tiny Shakespeare dataset. * [Github repo](https://github.com/lab-ml/nn) * [Paper](https://arxiv.org/abs/2102.11174) * [Colab notebook](https://colab.research.google.com/github/lab-ml/nn/blob/master/labml_nn/transformers/fast_weights/experiment.ipynb) * [Training loss charts](https://app.labml.ai/run/928aadc0846c11eb85710242ac1c0002)
1
t3_m4tdni
1,615,720,388
pytorch
Self-Attention Computer Vision - PyTorch Code - Analytics India Magazine
As discussed in [one of our articles](https://analyticsindiamag.com/going-beyond-cnn-stand-alone-self-attention/), Self-Attention is gradually gaining prominent place from sequence modeling in natural language processing to Medical Image Segmentation. [https://analyticsindiamag.com/pytorch-code-for-self-attention-computer-vision/](https://analyticsindiamag.com/pytorch-code-for-self-attention-computer-vision/)
0.75
t3_m4sodo
1,615,717,120
pytorch
Basic sequence prediction with attention/transformer in pytorch
So I've been working on this problem for a few days and just not making progress. My goal is really simple: Use a transformer to predict future values of a Sine wave. I know that sounds trivial, but I can't get the code right. All the examples in the tutorials are using Transformers for NLP and have complicated embedding code. I haven't been able to reverse engineer a simple model that uses the Attention/Transformer network to predict a simple floating point time series. This paper is what really got me investigating this technique for floating point time series: [https://arxiv.org/pdf/2001.08317.pdf](https://arxiv.org/pdf/2001.08317.pdf) Has anyone done this or do you know of any tutorials?
1
t3_m4p4r1
1,615,700,827
pytorch
Looking for someone who can review my code
Hi, I am a self learner. I built a Seq2Seq model following some online tutorials. But my model is giving some error during training. I am thus looking for a mentor who can review my code and help me in resolving the issue. \----------------------- Error: AttributeError Traceback (most recent call last) ​ <ipython-input-63-472071541d41> in <module>() 8 start\_time = time.time() 9 \---> 10 train\_loss = train(model, train\_iterator, optimizer, criterion, CLIP) 11 valid\_loss = evaluate(model, valid\_iterator, criterion) 12 ​ 6 frames ​ /usr/local/lib/python3.7/dist-packages/transformers/models/bert/modeling\_bert.py in forward(self, input\_ids, attention\_mask, token\_type\_ids, position\_ids, head\_mask, inputs\_embeds, encoder\_hidden\_states, encoder\_attention\_mask, past\_key\_values, use\_cache, output\_attentions, output\_hidden\_states, return\_dict) 917 raise ValueError("You cannot specify both input\_ids and inputs\_embeds at the same time") 918 elif input\_ids is not None: \--> 919 input\_shape = input\_ids.size() 920 batch\_size, seq\_length = input\_shape 921 elif inputs\_embeds is not None: ​ AttributeError: 'Field' object has no attribute 'size' \--------------------- My code is available in this github repo for your review: [https://github.com/Ninja16180/BERT/blob/main/Training\_Seq2Seq\_Model\_using\_Pre-Trained\_BERT\_Model.ipynb](https://github.com/Ninja16180/BERT/blob/main/Training_Seq2Seq_Model_using_Pre-Trained_BERT_Model.ipynb) ​ Appreciate your help. ​ Thanks in advance!
0.81
t3_m48njj
1,615,649,875
pytorch
ResNet from scratch - ImageNet
Hey Guys, I have been experimenting with ResNet architectures. As of now I have coded 18 and 34 using Pytorch with CIFAR-10, however I would like to experiment training with ImageNet dataset. I read that the original dataset is around 400 GB (approx) which might need an AWS EC2 instance to compute. Is there any smaller version of it which I can read/explore? Haven't really found a good online resource(s) which talks about ImageNet specific data preparation. Help?
1
t3_m3yo8b
1,615,608,238
pytorch
How to access a class object when I use torch.nn.DataParallel()?
Hello, I want to train my model using PyTorch with multiple GPUs. I included the following line: `model = torch.nn.DataParallel(model, device_ids=opt.gpu_ids)` Then, I tried to access the optimizer that was defined in my model definition: `G_opt = model.module.optimizer_G` However, I got an error: >AttributeError: 'DataParallel' object has no attribute optimizer\_G I think it is related with the definition of optimizer in my model definition. It works when I use single GPU without \`torch.nn.DataParallel\`. But it does not work with multi GPUs even though I call with `module` and I could not find the solution. Here is the model definition: `class MyModel(torch.nn.Module):` `...` `self.optimizer_G = torch.optim.Adam(params,` [`lr=opt.lr`](https://lr=opt.lr)`, betas=(opt.beta1, 0.999))` I used Pix2PixHD implementation in [GitHub](https://github.com/NVIDIA/pix2pixHD) if you want to see the full code. Thank you, Best.
0.75
t3_m3sm6t
1,615,587,387
pytorch
When does one divide by the meta_batch_size for MAML during meta-learning?
nan
1
t3_m3q01j
1,615,579,877
pytorch
Pytorch Geometric on Google Colab
Hello all, I am trying to install Pytorch Geometric on google colab, but I keep running into errors. Does anybody have a notebook with a working installation that I could use? Thank you
1
t3_m3auq7
1,615,527,345
pytorch
Repeated inference causes slowdown?
I call a model on an input once, it takes 0.02s. I call the same model on the same input twice, back to back, it takes 0.04s, sensible so far. I call the same model in the same input five times, back to back to back to back to back, it now takes 0.9s, when it should take 0.1s. Ten times, 5.7s, when it should take 0.2s. When I clear the cache between every run, the sum of the times for the runs goes down to something that could be expected, but clearing the cache takes a second each time or so. What the Hell is going on?
1
t3_m2vpmr
1,615,483,890
pytorch
ResNet-18 vs ResNet-34
I have trained [ResNet-18](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet-18_CIFAR10-PyTorch.ipynb) and [ResNet-34](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet_34_CIFAR10_PyTorch.ipynb) from scratch using PyTorch on CIFAR-10 dataset. The validation accuracy I get for ResNet-18 is 84.01%, whereas for ResNet-34 is 82.43%. Is this a sign of ResNet-34 overfitting as compared to ResNet-18? Ideally, ResNet-34 should achieve a higher validation accuracy as compared to ResNet-18. Thoughts?
1
t3_m1cftx
1,615,313,467
pytorch
ResNet-18 from scratch
I have implemented ResNet-18 CNN from scatch in Python and PyTorch using CIFAR-10 dataset. You can see it [here](https://github.com/arjun-majumdar/CNN_Classifications/blob/master/ResNet-18_CIFAR10-PyTorch.ipynb). Let me know your comments/feedbacks.
0.79
t3_m12byo
1,615,278,994