|
| 1 | +#! /usr/bin/env python3 |
| 2 | + |
| 3 | +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved |
| 4 | + |
| 5 | +import unittest |
| 6 | + |
| 7 | +import torch |
| 8 | +from botorch.test_functions.aug_rosenbrock import GLOBAL_MAXIMUM, neg_aug_rosenbrock |
| 9 | + |
| 10 | + |
| 11 | +class TestNegAugRosenbrock(unittest.TestCase): |
| 12 | + def test_single_eval_neg_aug_rosenbrock(self, cuda=False): |
| 13 | + device = torch.device("cuda") if cuda else torch.device("cpu") |
| 14 | + for dtype in (torch.float, torch.double): |
| 15 | + X = torch.zeros(4, device=device, dtype=dtype) |
| 16 | + res = neg_aug_rosenbrock(X) |
| 17 | + self.assertEqual(res.dtype, dtype) |
| 18 | + self.assertEqual(res.device.type, device.type) |
| 19 | + self.assertEqual(res.shape, torch.Size()) |
| 20 | + |
| 21 | + def test_single_eval_neg_aug_rosenbrock_cuda(self): |
| 22 | + if torch.cuda.is_available(): |
| 23 | + self.test_single_eval_neg_aug_rosenbrock(cuda=True) |
| 24 | + |
| 25 | + def test_batch_eval_neg_aug_rosenbrock(self, cuda=False): |
| 26 | + device = torch.device("cuda") if cuda else torch.device("cpu") |
| 27 | + for dtype in (torch.float, torch.double): |
| 28 | + X = torch.zeros(2, 4, device=device, dtype=dtype) |
| 29 | + res = neg_aug_rosenbrock(X) |
| 30 | + self.assertEqual(res.dtype, dtype) |
| 31 | + self.assertEqual(res.device.type, device.type) |
| 32 | + self.assertEqual(res.shape, torch.Size([2])) |
| 33 | + |
| 34 | + def test_batch_eval_neg_aug_rosenbrock_cuda(self): |
| 35 | + if torch.cuda.is_available(): |
| 36 | + self.test_batch_eval_neg_aug_rosenbrock(cuda=True) |
| 37 | + |
| 38 | + def test_neg_aug_rosenbrock_global_maximum(self, cuda=False): |
| 39 | + device = torch.device("cuda") if cuda else torch.device("cpu") |
| 40 | + for dtype in (torch.float, torch.double): |
| 41 | + X = torch.tensor( |
| 42 | + [[1, 1, 1, 1], [1, 0.95, 0.5, 1], [1, 0.91, 0.1, 1], [1, 0.99, 0.9, 1]], |
| 43 | + device=device, |
| 44 | + dtype=dtype, |
| 45 | + requires_grad=True, |
| 46 | + ) |
| 47 | + res = neg_aug_rosenbrock(X) |
| 48 | + for r in res: |
| 49 | + self.assertAlmostEqual(r.item(), GLOBAL_MAXIMUM, places=4) |
| 50 | + grad = torch.autograd.grad(res.sum(), X)[0] |
| 51 | + self.assertLess(grad.abs().max().item(), 1e-4) |
| 52 | + |
| 53 | + def test_neg_aug_rosenbrock_global_maximum_cuda(self): |
| 54 | + if torch.cuda.is_available(): |
| 55 | + self.test_neg_aug_rosenbrock_global_maximum(cuda=False) |
0 commit comments