File size: 8,246 Bytes
5769ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import os
import pytest

import torch
import torch.nn as nn
from mmcv import Config

from risk_biased.models.cvae_encoders import (
    CVAEEncoder,
    BiasedEncoderNN,
    FutureEncoderNN,
    InferenceEncoderNN,
)
from risk_biased.models.latent_distributions import (
    GaussianLatentDistribution,
    QuantizedDistributionCreator,
)

from risk_biased.models.cvae_params import CVAEParams


@pytest.fixture(scope="module")
def params():
    torch.manual_seed(0)
    working_dir = os.path.dirname(os.path.realpath(__file__))
    config_path = os.path.join(
        working_dir, "..", "..", "..", "risk_biased", "config", "learning_config.py"
    )
    waymo_config_path = os.path.join(
        working_dir, "..", "..", "..", "risk_biased", "config", "waymo_config.py"
    )
    paths = [config_path, waymo_config_path]
    if isinstance(paths, str):
        cfg = Config.fromfile(paths)
    else:
        cfg = Config.fromfile(paths[0])
        for path in paths[1:]:
            c = Config.fromfile(path)
            cfg.update(c)
    cfg.batch_size = 4
    cfg.state_dim = 5
    cfg.dynamic_state_dim = 5
    cfg.map_state_dim = 2
    cfg.num_steps = 3
    cfg.num_steps_future = 4
    cfg.latent_dim = 2
    cfg.hidden_dim = 64
    cfg.device = "cpu"
    cfg.sequence_encoder_type = "LSTM"
    cfg.sequence_decoder_type = "MLP"
    return cfg


@pytest.mark.parametrize(
    "num_agents, num_map_objects, type, interaction_nn_class",
    [
        (4, 5, "MLP", BiasedEncoderNN),
        (2, 4, "LSTM", BiasedEncoderNN),
        (3, 2, "maskedLSTM", BiasedEncoderNN),
        (4, 5, "MLP", FutureEncoderNN),
        (2, 4, "LSTM", FutureEncoderNN),
        (3, 2, "maskedLSTM", FutureEncoderNN),
        (4, 5, "MLP", InferenceEncoderNN),
        (2, 4, "LSTM", InferenceEncoderNN),
        (3, 2, "maskedLSTM", InferenceEncoderNN),
    ],
)
def test_attention_encoder_nn(
    params,
    num_agents: int,
    num_map_objects: int,
    type: str,
    interaction_nn_class: nn.Module,
):
    params.sequence_encoder_type = type
    cvae_params = CVAEParams.from_config(params)
    if interaction_nn_class == BiasedEncoderNN:
        model = interaction_nn_class(
            cvae_params,
            num_steps=cvae_params.num_steps,
            latent_dim=2 * cvae_params.latent_dim,
        )
    elif interaction_nn_class == FutureEncoderNN:
        model = interaction_nn_class(
            cvae_params,
            num_steps=cvae_params.num_steps + cvae_params.num_steps_future,
            latent_dim=2 * cvae_params.latent_dim,
        )
    else:
        model = interaction_nn_class(
            cvae_params,
            num_steps=cvae_params.num_steps,
            latent_dim=2 * cvae_params.latent_dim,
        )
    assert model.latent_dim == 2 * params.latent_dim
    assert model.hidden_dim == params.hidden_dim

    x = torch.rand(params.batch_size, num_agents, params.num_steps, params.state_dim)
    offset = x[:, :, -1, :]
    x = x - offset.unsqueeze(-2)
    mask_x = torch.rand(params.batch_size, num_agents, params.num_steps) > 0.1
    encoded_absolute = torch.rand(params.batch_size, num_agents, params.hidden_dim)
    encoded_map = torch.rand(params.batch_size, num_map_objects, params.hidden_dim)
    mask_map = torch.rand(params.batch_size, num_map_objects) > 0.1
    if interaction_nn_class == FutureEncoderNN:
        y = torch.rand(
            params.batch_size, num_agents, params.num_steps_future, params.state_dim
        )
        y = y - offset.unsqueeze(-2)
        y_ego = y[:, 0:1]
        mask_y = torch.rand(params.batch_size, num_agents, params.num_steps_future)
    else:
        y = None
        y_ego = None
        mask_y = None
    x_ego = x[:, 0:1]
    if interaction_nn_class == BiasedEncoderNN:
        risk_level = torch.rand(params.batch_size, num_agents)
    else:
        risk_level = None

    output = model(
        x,
        mask_x,
        encoded_absolute,
        encoded_map,
        mask_map,
        y=y,
        mask_y=mask_y,
        x_ego=x_ego,
        y_ego=y_ego,
        offset=offset,
        risk_level=risk_level,
    )
    # check shape
    assert output.shape == (params.batch_size, num_agents, 2 * params.latent_dim)


@pytest.mark.parametrize(
    "num_agents, num_map_objects, type, interaction_nn_class, latent_distribution_class",
    [
        (2, 8, "MLP", BiasedEncoderNN, GaussianLatentDistribution),
        (7, 5, "LSTM", BiasedEncoderNN, GaussianLatentDistribution),
        (2, 10, "maskedLSTM", BiasedEncoderNN, QuantizedDistributionCreator),
        (2, 8, "MLP", FutureEncoderNN, GaussianLatentDistribution),
        (7, 5, "LSTM", FutureEncoderNN, QuantizedDistributionCreator),
        (2, 10, "maskedLSTM", FutureEncoderNN, GaussianLatentDistribution),
        (2, 8, "MLP", InferenceEncoderNN, QuantizedDistributionCreator),
        (7, 5, "LSTM", InferenceEncoderNN, GaussianLatentDistribution),
        (2, 10, "maskedLSTM", InferenceEncoderNN, GaussianLatentDistribution),
    ],
)
# TODO: Add test for QuantizedDistributionCreator
def test_attention_cvae_encoder(
    params,
    num_agents: int,
    num_map_objects: int,
    type: str,
    interaction_nn_class,
    latent_distribution_class,
):
    params.sequence_encoder_type = type
    if interaction_nn_class == FutureEncoderNN:
        risk_level = None
        y = torch.rand(
            params.batch_size, num_agents, params.num_steps_future, params.state_dim
        )
        mask_y = torch.rand(params.batch_size, num_agents, params.num_steps_future)
    else:
        risk_level = torch.rand(params.batch_size, num_agents)
        y = None
        mask_y = None

    if interaction_nn_class == BiasedEncoderNN:
        model = interaction_nn_class(
            CVAEParams.from_config(params),
            num_steps=params.num_steps,
            latent_dim=2 * params.latent_dim,
        )
    elif interaction_nn_class == FutureEncoderNN:
        model = interaction_nn_class(
            CVAEParams.from_config(params),
            num_steps=params.num_steps + params.num_steps_future,
            latent_dim=2 * params.latent_dim,
        )
    else:
        model = interaction_nn_class(
            CVAEParams.from_config(params),
            num_steps=params.num_steps,
            latent_dim=2 * params.latent_dim,
        )

    encoder = CVAEEncoder(model, GaussianLatentDistribution)
    # check latent_dim
    assert encoder.latent_dim == 2 * params.latent_dim

    x = torch.rand(params.batch_size, num_agents, params.num_steps, params.state_dim)
    offset = x[:, :, -1, :]
    x = x - offset.unsqueeze(-2)
    if y is not None:
        y = y - offset.unsqueeze(-2)
        x_ego = x[:, 0:1]
        y_ego = y[:, 0:1]
    else:
        x_ego = x[:, 0:1]
        y_ego = None
    mask_x = torch.rand(params.batch_size, num_agents, params.num_steps) > 0.1
    encoded_absolute = torch.rand(params.batch_size, num_agents, params.hidden_dim)
    encoded_map = torch.rand(params.batch_size, num_map_objects, params.hidden_dim)
    mask_map = torch.rand(params.batch_size, num_map_objects) > 0.1

    latent_distribution = encoder(
        x=x,
        mask_x=mask_x,
        encoded_absolute=encoded_absolute,
        encoded_map=encoded_map,
        mask_map=mask_map,
        y=y,
        mask_y=mask_y,
        x_ego=x_ego,
        y_ego=y_ego,
        offset=offset,
        risk_level=risk_level,
    )
    latent_mean = latent_distribution.mu
    latent_log_std = latent_distribution.logvar
    # check shape
    assert (
        latent_mean.shape
        == latent_log_std.shape
        == (params.batch_size, num_agents, params.latent_dim)
    )

    latent_sample_1, weights = latent_distribution.sample()
    # check shape when n_samples = 0
    assert latent_sample_1.shape == latent_mean.shape
    assert latent_sample_1.shape[:-1] == weights.shape

    latent_sample_2, weights = latent_distribution.sample(n_samples=2)
    # check shape when n_samples = 2
    assert latent_sample_2.shape == (
        params.batch_size,
        num_agents,
        2,
        params.latent_dim,
    )

    latent_sample_3, weights = latent_distribution.sample()
    # make sure sampling is non-deterministic
    assert not torch.allclose(latent_sample_1, latent_sample_3)