-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
203 lines (162 loc) · 6.18 KB
/
helpers.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
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
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import einops
from einops.layers.torch import Rearrange
import pdb
# import diffuser.utils as utils
#-----------------------------------------------------------------------------#
#---------------------------------- modules ----------------------------------#
#-----------------------------------------------------------------------------#
class SinusoidalPosEmb(nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, x):
device = x.device
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
emb = x[:, None] * emb[None, :]
emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
return emb
class Downsample1d(nn.Module):
def __init__(self, dim):
super().__init__()
self.conv = nn.Conv1d(dim, dim, 3, 2, 1)
def forward(self, x):
return self.conv(x)
class Upsample1d(nn.Module):
def __init__(self, dim):
super().__init__()
self.conv = nn.ConvTranspose1d(dim, dim, 4, 2, 1)
def forward(self, x):
return self.conv(x)
class Conv1dBlock(nn.Module):
'''
Conv1d --> GroupNorm --> Mish
'''
def __init__(self, inp_channels, out_channels, kernel_size, mish=True, n_groups=8):
super().__init__()
if mish:
act_fn = nn.Mish()
else:
act_fn = nn.SiLU()
self.block = nn.Sequential(
nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2),
Rearrange('batch channels horizon -> batch channels 1 horizon'),
nn.GroupNorm(n_groups, out_channels),
Rearrange('batch channels 1 horizon -> batch channels horizon'),
act_fn,
)
def forward(self, x):
return self.block(x)
#-----------------------------------------------------------------------------#
#---------------------------------- sampling ---------------------------------#
#-----------------------------------------------------------------------------#
def extract(a, t, x_shape):
b, *_ = t.shape
# print(a.device)
out = a.gather(-1, t)
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
def cosine_beta_schedule(timesteps, s=0.008, dtype=torch.float32):
"""
cosine schedule
as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
"""
steps = timesteps + 1
x = np.linspace(0, steps, steps)
alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
betas_clipped = np.clip(betas, a_min=0, a_max=0.999)
return torch.tensor(betas_clipped, dtype=dtype).to(device='cuda')
def apply_conditioning(x, conditions, action_dim):
for t, val in conditions.items():
x[:, t, action_dim:] = val.clone()
return x
#-----------------------------------------------------------------------------#
#---------------------------------- losses -----------------------------------#
#-----------------------------------------------------------------------------#
class WeightedLoss(nn.Module):
def __init__(self, weights, action_dim):
super().__init__()
self.register_buffer('weights', weights)
self.action_dim = action_dim
def forward(self, pred, targ):
'''
pred, targ : tensor
[ batch_size x horizon x transition_dim ]
'''
loss = self._loss(pred, targ)
weighted_loss = (loss * self.weights).mean()
a0_loss = (loss[:, 0, :self.action_dim] / self.weights[0, :self.action_dim]).mean()
return weighted_loss, {'a0_loss': a0_loss}
class WeightedStateLoss(nn.Module):
def __init__(self, weights):
super().__init__()
self.register_buffer('weights', weights)
def forward(self, pred, targ):
'''
pred, targ : tensor
[ batch_size x horizon x transition_dim ]
'''
loss = self._loss(pred, targ)
weighted_loss = (loss * self.weights).mean()
return weighted_loss, {'a0_loss': weighted_loss}
# class ValueLoss(nn.Module):
# def __init__(self, *args):
# super().__init__()
# pass
# def forward(self, pred, targ):
# loss = self._loss(pred, targ).mean()
# if len(pred) > 1:
# corr = np.corrcoef(
# utils.to_np(pred).squeeze(),
# utils.to_np(targ).squeeze()
# )[0,1]
# else:
# corr = np.NaN
# info = {
# 'mean_pred': pred.mean(), 'mean_targ': targ.mean(),
# 'min_pred': pred.min(), 'min_targ': targ.min(),
# 'max_pred': pred.max(), 'max_targ': targ.max(),
# 'corr': corr,
# }
# return loss, info
class WeightedL1(WeightedLoss):
def _loss(self, pred, targ):
return torch.abs(pred - targ)
class WeightedL2(WeightedLoss):
def _loss(self, pred, targ):
return F.mse_loss(pred, targ, reduction='none')
class WeightedStateL2(WeightedStateLoss):
def _loss(self, pred, targ):
return F.mse_loss(pred, targ, reduction='none')
# class ValueL1(ValueLoss):
# def _loss(self, pred, targ):
# return torch.abs(pred - targ)
# class ValueL2(ValueLoss):
# def _loss(self, pred, targ):
# return F.mse_loss(pred, targ, reduction='none')
Losses = {
'l1': WeightedL1,
'l2': WeightedL2,
'state_l2': WeightedStateL2,
# 'value_l1': ValueL1,
# 'value_l2': ValueL2,
}
if __name__ == "__main__":
betas = cosine_beta_schedule(1000, 1e-4)
print(betas)
alphas = 1. - betas
alphas_cumprod = torch.cumprod(alphas, axis=0)
alphas_cumprod_prev = torch.cat([torch.ones(1), alphas_cumprod[:-1]])
print(alphas_cumprod_prev)
# pdb.set_trace()
# tensor([0.0000, 0.0000, 0.0000, ..., 0.9990, 0.9990, 0.9990])
# <torch.Tensor: shape=(1000,), dtype=torch.float32, device='cpu', numpy=
# array([0.0000000e+00, 0.0000000e+00, 0.0000000e+00, ...,
# 9.9900099e-01, 9.9900099e-01, 9.9900099e-01], dtype=float32)>