|
| 1 | +--- |
| 2 | +Title: PyTorch Cheat Sheet |
| 3 | +PyTorch version: 1.0Pre |
| 4 | +Date updated: 7/30/18 |
| 5 | + |
| 6 | +--- |
| 7 | + |
| 8 | +# Imports |
| 9 | +--------------- |
| 10 | +### General |
| 11 | + |
| 12 | +``` |
| 13 | +import torch # root package |
| 14 | +from torch.utils.data import Dataset, Dataloader # dataset representation and loading |
| 15 | +``` |
| 16 | + |
| 17 | +### Neural Network API |
| 18 | + |
| 19 | +``` |
| 20 | +import torch.autograd as autograd # computation graph |
| 21 | +from torch.autograd import Variable # variable node in computation graph |
| 22 | +import torch.nn as nn # neural networks |
| 23 | +import torch.nn.functional as F # layers, activations and more |
| 24 | +import torch.optim as optim # optimizers e.g. gradient descent, ADAM, etc. |
| 25 | +from torch.jit import script, trace # hybrid frontend decorator and tracing jit |
| 26 | +``` |
| 27 | +See [autograd](https://pytorch.org/docs/stable/autograd.html), [nn](https://pytorch.org/docs/stable/nn.html), [functional](https://pytorch.org/docs/stable/nn.html#torch-nn-functional) and [optim](https://pytorch.org/docs/stable/optim.html) |
| 28 | + |
| 29 | +### Hybrid frontend |
| 30 | + |
| 31 | +``` |
| 32 | +torch.jit.trace() # takes your module or function and an example data input, and traces the computational steps that the data encounters as it progresses through the model |
| 33 | +@script # decorator used to indicate data-dependent control flow within the code being traced |
| 34 | +``` |
| 35 | +See [hybrid frontend](https://pytorch.org/docs/stable/hybridfrontend) |
| 36 | + |
| 37 | +### ONNX |
| 38 | + |
| 39 | +``` |
| 40 | +torch.onnx.export(model, dummy data, xxxx.proto) # exports an ONNX formatted model using a trained model, dummy data and the desired file name |
| 41 | +model = onnx.load("alexnet.proto") # load an ONNX model |
| 42 | +onnx.checker.check_model(model) # check that the model IR is well formed |
| 43 | +onnx.helper.printable_graph(model.graph) # print a human readable representation of the graph |
| 44 | +``` |
| 45 | +See [onnx](https://pytorch.org/docs/stable/onnx.html) |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +### Vision |
| 50 | + |
| 51 | +``` |
| 52 | +from torchvision import datasets, models, transforms # vision datasets, architectures & transforms |
| 53 | +import torchvision.transforms as transforms # composable transforms |
| 54 | +``` |
| 55 | + |
| 56 | +See [torchvision](https://pytorch.org/docs/stable/torchvision/index.html) |
| 57 | + |
| 58 | +### Distributed Training |
| 59 | + |
| 60 | +``` |
| 61 | +import torch.distributed as dist # distributed communication |
| 62 | +from multiprocessing import Process # memory sharing processes |
| 63 | +
|
| 64 | +``` |
| 65 | + |
| 66 | +See [distributed](https://pytorch.org/docs/stable/distributed.html) and [multiprocessing](https://pytorch.org/docs/stable/multiprocessing.html) |
| 67 | + |
| 68 | + |
| 69 | +# Tensors |
| 70 | +-------------------- |
| 71 | + |
| 72 | +### Creation |
| 73 | + |
| 74 | +``` |
| 75 | +torch.randn(*size) # tensor with independent N(0,1) entries |
| 76 | +torch.[ones|zeros](*size) # tensor with all 1's [or 0's] |
| 77 | +torch.Tensor(L) # create tensor from [nested] list or ndarray L |
| 78 | +x.clone() # clone of x |
| 79 | +with torch.no_grad(): # code wrap that stops autograd from tracking tensor history |
| 80 | +requires_grad=True # arg, when set to True, tracks computation history for future derivative calculations |
| 81 | +``` |
| 82 | + |
| 83 | +See [tensor](https://pytorch.org/docs/stable/tensors.html) |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | +### Dimensionality |
| 88 | + |
| 89 | +``` |
| 90 | +x.size() # return tuple-like object of dimensions |
| 91 | +torch.cat(tensor_seq, dim=0) # concatenates tensors along dim |
| 92 | +x.view(a,b,...) # reshapes x into size (a,b,...) |
| 93 | +x.view(-1,a) # reshapes x into size (b,a) for some b |
| 94 | +x.transpose(a,b) # swaps dimensions a and b |
| 95 | +x.permute(*dims) # permutes dimensions |
| 96 | +x.unsqueeze(dim) # tensor with added axis |
| 97 | +x.unsqueeze(dim=2) # (a,b,c) tensor -> (a,b,1,c) tensor |
| 98 | +``` |
| 99 | +See [tensor](https://pytorch.org/docs/stable/tensors.html) |
| 100 | + |
| 101 | +### Algebra |
| 102 | + |
| 103 | +``` |
| 104 | +A.mm(B) # matrix multiplication |
| 105 | +A.mv(x) # matrix-vector multiplication |
| 106 | +x.t() # matrix transpose |
| 107 | +``` |
| 108 | +See [math operations](https://pytorch.org/docs/stable/torch.html?highlight=mm#math-operations) |
| 109 | + |
| 110 | +### GPU Usage |
| 111 | + |
| 112 | +``` |
| 113 | +torch.cuda.is_available # check for cuda |
| 114 | +x.cuda() # move x's data from CPU to GPU and return new object |
| 115 | +x.cpu() # move x's data from GPU to CPU and return new object |
| 116 | +
|
| 117 | +if not args.disable_cuda and torch.cuda.is_available(): # device agnostic code and modularity |
| 118 | + args.device = torch.device('cuda') # |
| 119 | +else: # |
| 120 | + args.device = torch.device('cpu') # |
| 121 | +
|
| 122 | +net.to(device) # recursively convert their parameters and buffers to device specific tensors |
| 123 | +mytensor.to(device) # copy your tensors to a device (gpu, cpu) |
| 124 | +
|
| 125 | +``` |
| 126 | +See [cuda](https://pytorch.org/docs/stable/cuda.html) |
| 127 | + |
| 128 | + |
| 129 | +# Deep Learning |
| 130 | +``` |
| 131 | +nn.Linear(m,n) # fully connected layer from m to n units |
| 132 | +nn.ConvXd(m,n,s) # X dimensional conv layer from m to n channels where X⍷{1,2,3} and the kernel size is s |
| 133 | +nn.MaxPoolXd(s) # X dimension pooling layer (notation as above) |
| 134 | +nn.BatchNorm # batch norm layer |
| 135 | +nn.RNN/LSTM/GRU # recurrent layers |
| 136 | +nn.Dropout(p=0.5, inplace=False) # dropout layer for any dimensional input |
| 137 | +nn.Dropout2d(p=0.5, inplace=False) # 2-dimensional channel-wise dropout |
| 138 | +nn.Embedding(num_embeddings, embedding_dim) # (tensor-wise) mapping from indices to embedding vectors |
| 139 | +
|
| 140 | +``` |
| 141 | +See [nn](https://pytorch.org/docs/stable/nn.html) |
| 142 | + |
| 143 | + |
| 144 | +### Loss Functions |
| 145 | + |
| 146 | +``` |
| 147 | +nn.X where for example X is ... # BCELoss, CrossEntropyLoss, L1Loss, MSELoss, NLLLoss, SoftMarginLoss, MultiLabelSoftMarginLoss, CosineEmbeddingLoss, KLDivLoss, MarginRankingLoss, HingeEmbeddingLoss or CosineEmbeddingLoss |
| 148 | +``` |
| 149 | +See [loss functions](https://pytorch.org/docs/stable/nn.html#loss-functions) |
| 150 | + |
| 151 | +### Activation Functions |
| 152 | + |
| 153 | +``` |
| 154 | +nn.X where for example X is ... # ReLU, ReLU6, ELU, SELU, PReLU, LeakyReLU, Threshold, HardTanh, Sigmoid, Tanh, LogSigmoid, Softplus, SoftShrink, Softsign, TanhShrink, Softmin, Softmax, Softmax2d or LogSoftmax |
| 155 | +``` |
| 156 | +See [activation functions](https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity) |
| 157 | + |
| 158 | +### Optimizers |
| 159 | + |
| 160 | +``` |
| 161 | +opt = optim.x(model.parameters(), ...) # create optimizer |
| 162 | +opt.step() # update weights |
| 163 | +optim.X where for example X is ... # SGD, Adadelta, Adagrad, Adam, SparseAdam, Adamax, ASGD, LBFGS, RMSProp or Rprop |
| 164 | +``` |
| 165 | +See [optimizers](https://pytorch.org/docs/stable/optim.html) |
| 166 | + |
| 167 | +### Learning rate scheduling |
| 168 | + |
| 169 | +``` |
| 170 | +scheduler = optim.X(optimizer,...) # create lr scheduler |
| 171 | +scheduler.step() # update lr at start of epoch |
| 172 | +optim.lr_scheduler.X where ... # LambdaLR, StepLR, MultiStepLR, ExponentialLR or ReduceLROnPLateau |
| 173 | +
|
| 174 | +``` |
| 175 | +See [learning rate scheduler](https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate) |
| 176 | + |
| 177 | +# Data Utilities |
| 178 | + |
| 179 | +### Datasets |
| 180 | + |
| 181 | +``` |
| 182 | +Dataset # abstract class representing dataset |
| 183 | +TensorDataset # labelled dataset in the form of tensors |
| 184 | +Concat Dataset # concatenation of Datasets |
| 185 | +``` |
| 186 | +See [datasets](https://pytorch.org/docs/stable/data.html?highlight=dataset#torch.utils.data.Dataset) |
| 187 | + |
| 188 | +### Dataloaders and DataSamplers |
| 189 | + |
| 190 | +``` |
| 191 | +DataLoader(dataset, batch_size=1, ...) # loads data batches agnostic of structure of individual data points |
| 192 | +sampler.Sampler(dataset,...) # abstract class dealing with ways to sample from dataset |
| 193 | +sampler.XSampler where ... # Sequential, Random, Subset, WeightedRandom or Distributed |
| 194 | +
|
| 195 | +``` |
| 196 | +See [dataloader](https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader) |
| 197 | + |
| 198 | + |
| 199 | +## Also see |
| 200 | + |
| 201 | +* [Deep Learning with PyTorch: A 60 Minute Blitz](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html) _(pytorch.org)_ |
| 202 | +* [PyTorch Forums](https://discuss.pytorch.org/) _(discuss.pytorch.org)_ |
| 203 | +* [PyTorch for Numpy users](https://github.com/wkentaro/pytorch-for-numpy-users) _(github.com/wkentaro/pytorch-for-numpy-users)_ |
0 commit comments