-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtest_multipliers.py
41 lines (29 loc) · 1.32 KB
/
test_multipliers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
"""Tests for Multiplier class."""
import torch
import cooper
def test_multipliers_init():
init_tensor = torch.randn(100, 1)
multiplier = cooper.multipliers.DenseMultiplier(init_tensor)
multiplier.project_()
assert torch.allclose(multiplier(), init_tensor)
init_tensor = torch.tensor([0.0, -1.0, 2.5])
multiplier = cooper.multipliers.DenseMultiplier(init_tensor)
multiplier.project_()
assert torch.allclose(multiplier(), init_tensor)
# For inequality constraints, the multipliers should be non-negative
init_tensor = torch.tensor([0.1, -1.0, 2.5])
multiplier = cooper.multipliers.DenseMultiplier(init_tensor, positive=True)
multiplier.project_()
assert torch.allclose(multiplier(), torch.tensor([0.1, 0.0, 2.5]))
def test_custom_projection():
class CustomProjectionMultiplier(cooper.multipliers.DenseMultiplier):
def project_(self):
# Project multipliers so that maximum non-zero entry is exactly 1
max_entry = torch.relu(self.weight).max()
if max_entry > 0:
self.weight.data = self.weight.data / max_entry
init_tensor = torch.randn(100, 1)
multiplier = CustomProjectionMultiplier(init_tensor)
multiplier.project_()
assert torch.allclose(multiplier.weight.data.max(), torch.tensor([1.0]))