mirror of
https://github.com/pytorch/pytorch.git
synced 2025-10-20 21:14:14 +08:00
Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/44090 This is an initial commit pulling in the torchgpipe fork at https://github.com/facebookresearch/fairscale. The purpose of this commit is to just pull in the code and ensure all tests and builds work fine. We will slowly modify this to match our intended API mentioned in https://fb.quip.com/txurAV3zIFox#RPZACAfAKMq. Follow up PRs would address further changes needed on top of the initial commit.. We're pulling the code into the `torch.distributed._pipeline.sync` package. The package is private on purpose since there is a lot of work (ex: docs, API changes etc.) that needs to go in before we can actually officially support this. ghstack-source-id: 114864254 Test Plan: 1) waitforbuildbot 2) Ran all tests on my devgpu Reviewed By: mrshenli Differential Revision: D23493316 fbshipit-source-id: fe3c8b7dadeeb86abdc00e8a8652491b0b16743a
44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
# Copyright 2019 Kakao Brain
|
|
#
|
|
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
|
#
|
|
# This source code is licensed under the BSD license found in the
|
|
# LICENSE file in the root directory of this source tree.
|
|
import torch
|
|
from torch import nn
|
|
|
|
from torch.distributed._pipeline.sync import Pipe
|
|
|
|
|
|
def test_simple_linears():
|
|
def sum_grad(parameters):
|
|
return sum([p.grad.sum() for p in parameters if p.grad is not None])
|
|
|
|
def zero_grad(parameters):
|
|
for p in parameters:
|
|
p.grad = None
|
|
|
|
inputs = torch.rand(8, 1)
|
|
model = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 4), nn.Linear(4, 2), nn.Linear(2, 1),)
|
|
|
|
# Without Pipe
|
|
outputs = model(inputs)
|
|
loss = outputs.mean()
|
|
loss.backward()
|
|
|
|
grad_without_pipe = sum_grad(model.parameters())
|
|
|
|
zero_grad(model.parameters())
|
|
|
|
# With Pipe
|
|
model = Pipe(model, [2, 2], devices=["cpu", "cpu"], chunks=4)
|
|
|
|
outputs = model(inputs)
|
|
loss = outputs.mean()
|
|
loss.backward()
|
|
|
|
grad_with_pipe = sum_grad(model.parameters())
|
|
|
|
# Both grads should be identical.
|
|
assert torch.allclose(grad_with_pipe, grad_without_pipe)
|