File size: 8,442 Bytes
079c32c |
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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
import shutil
from time import sleep
import pytest
import numpy as np
import tempfile
import torch
from ding.data.model_loader import FileModelLoader
from ding.data.storage_loader import FileStorageLoader
from ding.framework import task
from ding.framework.context import OnlineRLContext
from ding.framework.middleware.distributer import ContextExchanger, ModelExchanger, PeriodicalModelExchanger
from ding.framework.parallel import Parallel
from ding.utils.default_helper import set_pkg_seed
from os import path
def context_exchanger_main():
with task.start(ctx=OnlineRLContext()):
if task.router.node_id == 0:
task.add_role(task.role.LEARNER)
elif task.router.node_id == 1:
task.add_role(task.role.COLLECTOR)
task.use(ContextExchanger(skip_n_iter=1))
if task.has_role(task.role.LEARNER):
def learner_context(ctx: OnlineRLContext):
assert len(ctx.trajectories) == 2
assert len(ctx.trajectory_end_idx) == 4
assert len(ctx.episodes) == 8
assert ctx.env_step > 0
assert ctx.env_episode > 0
yield
ctx.train_iter += 1
task.use(learner_context)
elif task.has_role(task.role.COLLECTOR):
def collector_context(ctx: OnlineRLContext):
if ctx.total_step > 0:
assert ctx.train_iter > 0
yield
ctx.trajectories = [np.random.rand(10, 10) for _ in range(2)]
ctx.trajectory_end_idx = [1 for _ in range(4)]
ctx.episodes = [np.random.rand(10, 10) for _ in range(8)]
ctx.env_step += 1
ctx.env_episode += 1
task.use(collector_context)
task.run(max_step=3)
@pytest.mark.tmp
def test_context_exchanger():
Parallel.runner(n_parallel_workers=2)(context_exchanger_main)
def context_exchanger_with_storage_loader_main():
with task.start(ctx=OnlineRLContext()):
if task.router.node_id == 0:
task.add_role(task.role.LEARNER)
elif task.router.node_id == 1:
task.add_role(task.role.COLLECTOR)
tempdir = path.join(tempfile.gettempdir(), "test_storage_loader")
storage_loader = FileStorageLoader(dirname=tempdir)
try:
task.use(ContextExchanger(skip_n_iter=1, storage_loader=storage_loader))
if task.has_role(task.role.LEARNER):
def learner_context(ctx: OnlineRLContext):
assert len(ctx.trajectories) == 2
assert len(ctx.trajectory_end_idx) == 4
assert len(ctx.episodes) == 8
assert ctx.env_step > 0
assert ctx.env_episode > 0
yield
ctx.train_iter += 1
task.use(learner_context)
elif task.has_role(task.role.COLLECTOR):
def collector_context(ctx: OnlineRLContext):
if ctx.total_step > 0:
assert ctx.train_iter > 0
yield
ctx.trajectories = [np.random.rand(10, 10) for _ in range(2)]
ctx.trajectory_end_idx = [1 for _ in range(4)]
ctx.episodes = [np.random.rand(10, 10) for _ in range(8)]
ctx.env_step += 1
ctx.env_episode += 1
task.use(collector_context)
task.run(max_step=3)
finally:
storage_loader.shutdown()
sleep(1)
if path.exists(tempdir):
shutil.rmtree(tempdir)
@pytest.mark.tmp
def test_context_exchanger_with_storage_loader():
Parallel.runner(n_parallel_workers=2)(context_exchanger_with_storage_loader_main)
class MockPolicy:
def __init__(self) -> None:
self._model = self._get_model(10, 10)
def _get_model(self, X_shape, y_shape) -> torch.nn.Module:
return torch.nn.Sequential(
torch.nn.Linear(X_shape, 24), torch.nn.ReLU(), torch.nn.Linear(24, 24), torch.nn.ReLU(),
torch.nn.Linear(24, y_shape)
)
def train(self, X, y):
loss_fn = torch.nn.MSELoss(reduction="mean")
optimizer = torch.optim.Adam(self._model.parameters(), lr=0.01)
y_pred = self._model(X)
loss = loss_fn(y_pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
def predict(self, X):
with torch.no_grad():
return self._model(X)
def model_exchanger_main():
with task.start(ctx=OnlineRLContext()):
set_pkg_seed(0, use_cuda=False)
policy = MockPolicy()
X = torch.rand(10)
y = torch.rand(10)
if task.router.node_id == 0:
task.add_role(task.role.LEARNER)
else:
task.add_role(task.role.COLLECTOR)
task.use(ModelExchanger(policy._model))
if task.has_role(task.role.LEARNER):
def train(ctx):
policy.train(X, y)
sleep(0.3)
task.use(train)
else:
y_pred1 = policy.predict(X)
def pred(ctx):
if ctx.total_step > 0:
y_pred2 = policy.predict(X)
# Ensure model is upgraded
assert any(y_pred1 != y_pred2)
sleep(0.3)
task.use(pred)
task.run(2)
@pytest.mark.tmp
def test_model_exchanger():
Parallel.runner(n_parallel_workers=2, startup_interval=0)(model_exchanger_main)
def model_exchanger_main_with_model_loader():
with task.start(ctx=OnlineRLContext()):
set_pkg_seed(0, use_cuda=False)
policy = MockPolicy()
X = torch.rand(10)
y = torch.rand(10)
if task.router.node_id == 0:
task.add_role(task.role.LEARNER)
else:
task.add_role(task.role.COLLECTOR)
tempdir = path.join(tempfile.gettempdir(), "test_model_loader")
model_loader = FileModelLoader(policy._model, dirname=tempdir)
task.use(ModelExchanger(policy._model, model_loader=model_loader))
try:
if task.has_role(task.role.LEARNER):
def train(ctx):
policy.train(X, y)
sleep(0.3)
task.use(train)
else:
y_pred1 = policy.predict(X)
def pred(ctx):
if ctx.total_step > 0:
y_pred2 = policy.predict(X)
# Ensure model is upgraded
assert any(y_pred1 != y_pred2)
sleep(0.3)
task.use(pred)
task.run(2)
finally:
model_loader.shutdown()
sleep(0.3)
if path.exists(tempdir):
shutil.rmtree(tempdir)
@pytest.mark.tmp
def test_model_exchanger_with_model_loader():
Parallel.runner(n_parallel_workers=2, startup_interval=0)(model_exchanger_main_with_model_loader)
def periodical_model_exchanger_main():
with task.start(ctx=OnlineRLContext()):
set_pkg_seed(0, use_cuda=False)
policy = MockPolicy()
X = torch.rand(10)
y = torch.rand(10)
if task.router.node_id == 0:
task.add_role(task.role.LEARNER)
task.use(PeriodicalModelExchanger(policy._model, mode="send", period=3))
else:
task.add_role(task.role.COLLECTOR)
task.use(PeriodicalModelExchanger(policy._model, mode="receive", period=1, stale_toleration=3))
if task.has_role(task.role.LEARNER):
def train(ctx):
policy.train(X, y)
sleep(0.3)
task.use(train)
else:
y_pred1 = policy.predict(X)
print("y_pred1: ", y_pred1)
stale = 1
def pred(ctx):
nonlocal stale
y_pred2 = policy.predict(X)
print("y_pred2: ", y_pred2)
stale += 1
assert stale <= 3 or all(y_pred1 == y_pred2)
if any(y_pred1 != y_pred2):
stale = 1
sleep(0.3)
task.use(pred)
task.run(8)
@pytest.mark.tmp
def test_periodical_model_exchanger():
Parallel.runner(n_parallel_workers=2, startup_interval=0)(periodical_model_exchanger_main)
|