File size: 3,847 Bytes
68d3a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""Tests for told_check2.Boundary (Opus audit M5): the treatment itself, with a NumPy stand-in for torch, so the Mac can
run it. Checks what every model call receives at factor one and at half 0.5, that inputs are never modified, that the
policy proposal maps back and clips only the knee, and that reinstalling does not stack conversions."""
import types
import unittest

import numpy as np

import told_check2 as TC2

KNEE = 4


class T(np.ndarray):
    """A NumPy array with the torch method the wrapper uses (.abs())."""
    def abs(self):
        return np.abs(self)


FAKE_TORCH = types.SimpleNamespace(
    float32=np.float32,
    tensor=lambda v, dtype=None, device=None: np.asarray(v, dtype=np.float32).view(T),
    zeros=lambda shape, device=None: np.zeros(shape, dtype=np.float32),
    maximum=np.maximum,
)


class Model:
    def __init__(self):
        self.seen = {"next": [], "reward": [], "Q": []}

    def next(self, z, a, task):
        self.seen["next"].append(np.array(a, copy=True))
        return z

    def reward(self, z, a, task):
        self.seen["reward"].append(np.array(a, copy=True))
        return 0.0

    def Q(self, z, a, task, return_type="avg"):
        self.seen["Q"].append(np.array(a, copy=True))
        return 0.0

    def pi(self, z, task):
        m = np.array([[0.1, -0.2, 0.3, -0.4, 0.4, 0.9]], dtype=np.float32)   # model-space proposal; knee 0.4
        return m.copy(), {"mean": m.copy()}


def agent():
    return types.SimpleNamespace(cfg=types.SimpleNamespace(action_dim=6), device=None, model=Model())


class BoundaryTest(unittest.TestCase):
    def setUp(self):
        self.agent = agent()
        self.b = TC2.Boundary(self.agent, KNEE, FAKE_TORCH)
        self.u = np.array([[0.2, -0.3, 0.5, -0.6, 1.0, -0.7]], dtype=np.float32)

    def test_factor_one_passes_actions_unchanged(self):
        self.b.install(1.0)
        before = self.u.copy()
        self.agent.model.next(None, self.u, 0)
        self.assertTrue(np.array_equal(self.agent.model.seen["next"][0], before))
        self.assertTrue(np.array_equal(self.u, before))
        a, info = self.agent.model.pi(None, 0)
        self.assertAlmostEqual(float(a[0, KNEE]), 0.4, places=6)          # no doubling, no clip at factor one

    def test_half_halves_only_the_knee_for_next_reward_and_q(self):
        self.b.install(0.5)
        for name in ("next", "reward", "Q"):
            getattr(self.agent.model, name)(None, self.u, 0)
            seen = self.agent.model.seen[name][-1]
            self.assertAlmostEqual(float(seen[0, KNEE]), 0.5, places=6)
            self.assertTrue(np.allclose(np.delete(seen, KNEE, axis=1), np.delete(self.u, KNEE, axis=1)))
        self.assertEqual(float(self.u[0, KNEE]), 1.0)                       # the planner's u is never modified
        self.assertEqual(self.b.calls["next"], 1)
        self.assertAlmostEqual(float(self.b.model_knee_max), 0.5, places=6)

    def test_policy_proposal_maps_back_and_clips_only_the_knee(self):
        self.b.install(0.5)
        a, info = self.agent.model.pi(None, 0)
        self.assertAlmostEqual(float(a[0, KNEE]), 0.8, places=6)            # 0.4 model space -> 0.8 command
        self.assertAlmostEqual(float(info["mean"][0, KNEE]), 0.8, places=6)
        self.assertAlmostEqual(float(a[0, 5]), 0.9, places=6)               # another coordinate is not clipped or scaled

    def test_reinstall_does_not_stack_conversions(self):
        self.b.install(0.5)
        self.b.install(0.5)
        self.agent.model.next(None, self.u, 0)
        self.assertAlmostEqual(float(self.agent.model.seen["next"][-1][0, KNEE]), 0.5, places=6)
        self.b.install(1.0)
        self.agent.model.next(None, self.u, 0)
        self.assertAlmostEqual(float(self.agent.model.seen["next"][-1][0, KNEE]), 1.0, places=6)


if __name__ == "__main__":
    unittest.main()