PyTorch

PyTorch - QuickStart

Basic

# version
torch.__version__               # PyTorch version
torch.version.cuda              # Corresponding CUDA version
torch.backends.cudnn.version()  # Corresponding cuDNN version
torch.cuda.get_device_name(0)   # GPU type

# seed
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)

# GPU
torch.cuda.is_available()
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
torch.cuda.empty_cache()        # clear GPU cache

device = (
    "cuda"
    if torch.cuda.is_available()
    else "mps"
    if torch.backends.mps.is_available()
    else "cpu"
)

Tensor

tensor = torch.randn(2, 3)

# tensor info
tensor.type()   # Data type
tensor.size()   # Shape of the tensor
tensor.shape    # Shape of the tensor
tensor.dim()    # Number of dimensions

# type convertions
tensor = tensor.cuda()
tensor = tensor.cpu()
tensor = tensor.float()
tensor = tensor.long()
torch.set_default_tensor_type(torch.FloatTensor)   # Set default tensor type

# torch.Tensor <=> np.ndarray
ndarray = tensor.cpu().numpy()
tensor = torch.from_numpy(ndarray).float()
tensor = torch.from_numpy(ndarray.copy()).float()  # If ndarray has negative stride

# 从只包含一个元素的张量中提取值
value = tensor.item()

# torch.Tensor <=> PIL.Image
# PyTorch中的张量默认采用N×D×H×W的顺序,并且数据范围在[0, 1],需要进行转置和规范化。
image = PIL.Image.fromarray(torch.clamp(tensor * 255, min=0, max=255
    ).byte().permute(1, 2, 0).cpu().numpy())
image = torchvision.transforms.functional.to_pil_image(tensor)  # Equivalently way

tensor = torch.from_numpy(np.asarray(PIL.Image.open(path))
    ).permute(2, 0, 1).float() / 255
tensor = torchvision.transforms.functional.to_tensor(PIL.Image.open(path))  # Equivalently way

# np.ndarray <=> PIL.Image
image = PIL.Image.fromarray(ndarray.astypde(np.uint8))
ndarray = np.asarray(PIL.Image.open(path))

# reshape
tensor.reshape(shape)
tensor.permute(0,2,1) # swap axes
tensor.flatten() # 展成 1D 向量
tensor.squeeze() # 去掉维数为 1 的的维度
tensor.unsqueeze(dim=0) # 增加维度

# shuffle
tensor = tensor[torch.randperm(tensor.size(0))]  # Shuffle the first dimension

# copy
# Operation                 |  New/Shared memory | Still in computation graph |
tensor.clone()            # |        New         |          Yes               |
tensor.detach()           # |      Shared        |          No                |
tensor.detach().clone()   # |        New         |          No                |

# concatenate
tensor = torch.cat(list_of_tensors, dim=0)
tensor = torch.stack(list_of_tensors, dim=0)

# one-hot
N = tensor.size(0)
one_hot = torch.zeros(N, num_classes).long()
one_hot.scatter_(dim=1,
    index=torch.unsqueeze(tensor, dim=1),
    src=torch.ones(N, num_classes).long())

# non-zero
torch.nonzero(tensor)               # Index of non-zero elements
torch.nonzero(tensor == 0)          # Index of zero elements
torch.nonzero(tensor).size(0)       # Number of non-zero elements
torch.nonzero(tensor == 0).size(0)  # Number of zero elements

# equal
torch.allclose(tensor1, tensor2)  # float tensor
torch.equal(tensor1, tensor2)     # int tensor

# expand
# Expand tensor of shape 64*512 to shape 64*512*7*7.
torch.reshape(tensor, (64, 512, 1, 1)).expand(64, 512, 7, 7)

# normalize
F.normalize(tensor, dim=1)

Dataloader

from torch.utils.data import TensorDataset, Dataset, DataLoader

train_ds = TensorDataset(x_train[:50000], y_train[:50000])
valid_ds = TensorDataset(x_train[50000:], y_train[50000:])
train_dl = DataLoader(train_ds, batch_size=mini_batch, shuffle=True, num_workers=4)
valid_dl = DataLoader(valid_ds, batch_size=len(valid_ds))

for xb, yb in train_dl:
    pass

自定义dataset

# 需要实现__getitem__、__len__两个方法
class SparseDataset(Dataset):
    def __init__(self, data):
        self.data = data
    
    def __getitem__(self, index):
        data = self.data[index].tocoo()
        i = torch.LongTensor(np.vstack((data.row, data.col)))
        v = torch.FloatTensor(data.data)
        data = torch.sparse.FloatTensor(i, v, torch.Size(data.shape))
        return data
    
    def __len__(self):
        return self.data.shape[0]

Layer

# convolution layer
conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True)
conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=True)

Weight initialization

init.kaiming_normal_(layer.weight, mode='fan_out', nonlinearity='relu')
nn.init.constant_(layer.weight, val=1.0)
nn.init.constant_(layer.bias, val=0.0)
nn.init.xavier_normal_(layer.weight)
nn.init.constant_(layer.bias, val=0.0)

# Initialization with given tensor.
layer.weight = torch.nn.Parameter(tensor)

Module

# init
super(Model, self).__init__()

# parameter
self.weight = nn.Parameter(torch.Tensor(n_classes, embed_dim))
init.xavier_uniform_(self.weight)

# parameter list
self.params = nn.ParameterList()
for i in range(3):
    self.params.append(nn.Parameter(torch.Tensor(2,3)))

Training

idx = np.arange(n_train)
for i in range(epochs):
    np.random.shuffle(idx)
    tr = trange(n_train // batch + 1)
    for j in tr:
        batch_idx = idx[j*batch:(j+1)*batch]
        pred = model(x_train[batch_idx])
        loss = model.loss(pred, labels[batch_idx])
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        tr.set_description("Epoch {}: loss: {}".format(i, loss.item()))
        tr.refresh()

Learning rate

# If there is one global learning rate (which is the common case).
lr = next(iter(optimizer.param_groups))['lr']

# If there are multiple learning rates for different layers.
all_lr = []
for param_group in optimizer.param_groups:
    all_lr.append(param_group['lr'])

# Reduce learning rate when validation accuarcy plateau.
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', patience=5, verbose=True)
for t in range(0, 80):
    train(...); val(...)
    scheduler.step(val_acc)

# Cosine annealing learning rate.
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=80)
# Reduce learning rate by 10 at given epochs.
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[50, 70], gamma=0.1)
for t in range(0, 80):
    scheduler.step()
    train(...); val(...)

# Learning rate warmup by 10 epochs.
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda t: t / 10)
for t in range(0, 10):
    scheduler.step()
    train(...); val(...)

Save/load checkpoint

# Save checkpoint.
is_best = current_acc > best_acc
best_acc = max(best_acc, current_acc)
checkpoint = {
    'best_acc': best_acc,    
    'epoch': t + 1,
    'model': model.state_dict(),
    'optimizer': optimizer.state_dict(),
}
model_path = os.path.join('model', 'checkpoint.pth.tar')
torch.save(checkpoint, model_path)
if is_best:
    shutil.copy('checkpoint.pth.tar', model_path)

# Load checkpoint.
if resume:
    model_path = os.path.join('model', 'checkpoint.pth.tar')
    assert os.path.isfile(model_path)
    checkpoint = torch.load(model_path)
    best_acc = checkpoint['best_acc']
    start_epoch = checkpoint['epoch']
    model.load_state_dict(checkpoint['model'])
    optimizer.load_state_dict(checkpoint['optimizer'])
    print('Load checkpoint at epoch %d.' % start_epoch)

Others

  • 建议有参数的层和汇合(pooling)层使用torch.nn模块定义,激活函数直接使用torch.nn.functional。torch.nn模块和torch.nn.functional的区别在于,torch.nn模块在计算时底层调用了torch.nn.functional,但torch.nn模块包括该层参数,还可以应对训练和测试两种网络状态。使用torch.nn.functional时要注意网络状态
  • model(x)前用model.train()和model.eval()切换网络状态。 不需要计算梯度的代码块用with torch.no_grad()包含起来。model.eval()和torch.no_grad()的区别在于,model.eval()是将网络切换为测试状态,例如BN和随机失活(dropout)在训练和测试阶段使用不同的计算方法。torch.no_grad()是关闭PyTorch张量的自动求导机制,以减少存储使用和加速计算,得到的结果无法进行loss.backward()。
  • torch.nn.CrossEntropyLoss的输入不需要经过Softmax。torch.nn.CrossEntropyLoss等价于torch.nn.functional.log_softmax + torch.nn.NLLLoss。
  • loss.backward()前用optimizer.zero_grad()清除累积梯度。optimizer.zero_grad()和model.zero_grad()效果一样。
  • 用del及时删除不用的中间变量,节约GPU存储。
  • 使用inplace操作可节约GPU存储
  • 减少CPU和GPU之间的数据传输。例如如果你想知道一个epoch中每个mini-batch的loss和准确率,先将它们累积在GPU中等一个epoch结束之后一起传输回CPU会比每个mini-batch都进行一次GPU到CPU的传输更快。
  • 使用半精度浮点数half()会有一定的速度提升,具体效率依赖于GPU型号。需要小心数值精度过低带来的稳定性问题。
  • 时常使用assert tensor.size() == (N, D, H, W)作为调试手段,确保张量维度和你设想中一致。
  • 除了标记y外,尽量少使用一维张量,使用n*1的二维张量代替,可以避免一些意想不到的一维张量计算结果。

References