This repository was archived by the owner on Apr 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathimpala_cnn.py
More file actions
186 lines (159 loc) · 5.5 KB
/
impala_cnn.py
File metadata and controls
186 lines (159 loc) · 5.5 KB
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
import math
import torch as th
from torch import nn
from torch.nn import functional as F
from . import torch_util as tu
from gym3.types import Real, TensorType
REAL = Real()
class Encoder(nn.Module):
"""
Takes in seq of observations and outputs sequence of codes
Encoders can be stateful, meaning that you pass in one observation at a
time and update the state, which is a separate object. (This object
doesn't store any state except parameters)
"""
def __init__(self, obtype, codetype):
super().__init__()
self.obtype = obtype
self.codetype = codetype
def initial_state(self, batchsize):
raise NotImplementedError
def empty_state(self):
return None
def stateless_forward(self, obs):
"""
inputs:
obs: array or dict, all with preshape (B, T)
returns:
codes: array or dict, all with preshape (B, T)
"""
code, _state = self(obs, None, self.empty_state())
return code
def forward(self, obs, first, state_in):
"""
inputs:
obs: array or dict, all with preshape (B, T)
first: float array shape (B, T)
state_in: array or dict, all with preshape (B,)
returns:
codes: array or dict
state_out: array or dict
"""
raise NotImplementedError
class CnnBasicBlock(nn.Module):
"""
Residual basic block (without batchnorm), as in ImpalaCNN
Preserves channel number and shape
"""
def __init__(self, inchan, scale=1, batch_norm=False):
super().__init__()
self.inchan = inchan
self.batch_norm = batch_norm
s = math.sqrt(scale)
self.conv0 = tu.NormedConv2d(self.inchan, self.inchan, 3, padding=1, scale=s)
self.conv1 = tu.NormedConv2d(self.inchan, self.inchan, 3, padding=1, scale=s)
if self.batch_norm:
self.bn0 = nn.BatchNorm2d(self.inchan)
self.bn1 = nn.BatchNorm2d(self.inchan)
def residual(self, x):
# inplace should be False for the first relu, so that it does not change the input,
# which will be used for skip connection.
# getattr is for backwards compatibility with loaded models
if getattr(self, "batch_norm", False):
x = self.bn0(x)
x = F.relu(x, inplace=False)
x = self.conv0(x)
if getattr(self, "batch_norm", False):
x = self.bn1(x)
x = F.relu(x, inplace=True)
x = self.conv1(x)
return x
def forward(self, x):
return x + self.residual(x)
class CnnDownStack(nn.Module):
"""
Downsampling stack from Impala CNN
"""
def __init__(self, inchan, nblock, outchan, scale=1, pool=True, **kwargs):
super().__init__()
self.inchan = inchan
self.outchan = outchan
self.pool = pool
self.firstconv = tu.NormedConv2d(inchan, outchan, 3, padding=1)
s = scale / math.sqrt(nblock)
self.blocks = nn.ModuleList(
[CnnBasicBlock(outchan, scale=s, **kwargs) for _ in range(nblock)]
)
def forward(self, x):
x = self.firstconv(x)
if getattr(self, "pool", True):
x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
for block in self.blocks:
x = block(x)
return x
def output_shape(self, inshape):
c, h, w = inshape
assert c == self.inchan
if getattr(self, "pool", True):
return (self.outchan, (h + 1) // 2, (w + 1) // 2)
else:
return (self.outchan, h, w)
class ImpalaCNN(nn.Module):
name = "ImpalaCNN" # put it here to preserve pickle compat
def __init__(
self, inshape, chans, outsize, scale_ob, nblock, final_relu=True, **kwargs
):
super().__init__()
self.scale_ob = scale_ob
h, w, c = inshape
curshape = (c, h, w)
s = 1 / math.sqrt(len(chans)) # per stack scale
self.stacks = nn.ModuleList()
for outchan in chans:
stack = CnnDownStack(
curshape[0], nblock=nblock, outchan=outchan, scale=s, **kwargs
)
self.stacks.append(stack)
curshape = stack.output_shape(curshape)
self.dense = tu.NormedLinear(tu.intprod(curshape), outsize, scale=1.4)
self.outsize = outsize
self.final_relu = final_relu
def forward(self, x):
x = x.to(dtype=th.float32) / self.scale_ob
b, t = x.shape[:-3]
x = x.reshape(b * t, *x.shape[-3:])
x = tu.transpose(x, "bhwc", "bchw")
x = tu.sequential(self.stacks, x, diag_name=self.name)
x = x.reshape(b, t, *x.shape[1:])
x = tu.flatten_image(x)
x = th.relu(x)
x = self.dense(x)
if self.final_relu:
x = th.relu(x)
return x
class ImpalaEncoder(Encoder):
def __init__(
self,
inshape,
outsize=256,
chans=(16, 32, 32),
scale_ob=255.0,
nblock=2,
**kwargs
):
codetype = TensorType(eltype=REAL, shape=(outsize,))
obtype = TensorType(eltype=REAL, shape=inshape)
super().__init__(codetype=codetype, obtype=obtype)
self.cnn = ImpalaCNN(
inshape=inshape,
chans=chans,
scale_ob=scale_ob,
nblock=nblock,
outsize=outsize,
**kwargs
)
def forward(self, x, first, state_in):
x = self.cnn(x)
return x, state_in
def initial_state(self, batchsize):
return tu.zeros(batchsize, 0)