class GeluIsh(nn.Module): # Wraps the elementwise chain above as a layer
def forward(self, x):
return gelu_ish(x)
net = nn.Sequential(nn.Linear(1024, 1024), GeluIsh(),
nn.Linear(1024, 1024), GeluIsh(),
nn.Linear(1024, 1024), GeluIsh(),
nn.Linear(1024, 1024)).to(d2l.try_gpu())
X = torch.randn(512, 1024, device=d2l.try_gpu())
opt = torch.optim.SGD(net.parameters(), lr=0.01)
def train_step(model):
opt.zero_grad(set_to_none=True)
model(X).sum().backward()
opt.step()
cnet = torch.compile(net)
t0 = time.perf_counter()
train_step(cnet); torch.cuda.synchronize() # First call: compiles
print(f'first compiled step: {time.perf_counter() - t0:.1f} s')
print(d2l.Benchmark(lambda: train_step(net), desc='eager'))
print(d2l.Benchmark(lambda: train_step(cnet), desc='compiled'))