File size: 9,152 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import multiprocessing as mp
import pytest
from threading import Lock
from time import sleep, time
import random
import dataclasses
from ding.framework import task, Context, Parallel


@dataclasses.dataclass
class TestContext(Context):
    pipeline: list = dataclasses.field(default_factory=list)


@pytest.mark.unittest
def test_serial_pipeline():

    def step0(ctx):
        ctx.pipeline.append(0)

    def step1(ctx):
        ctx.pipeline.append(1)

    # Execute step1, step2 twice
    with task.start(ctx=TestContext()):
        for _ in range(2):
            task.forward(step0)
            task.forward(step1)
        assert task.ctx.pipeline == [0, 1, 0, 1]

        # Renew and execute step1, step2
        task.renew()
        assert task.ctx.total_step == 1
        task.forward(step0)
        task.forward(step1)
        assert task.ctx.pipeline == [0, 1]

        # Test context inheritance
        task.renew()


@pytest.mark.unittest
def test_serial_yield_pipeline():

    def step0(ctx):
        ctx.pipeline.append(0)
        yield
        ctx.pipeline.append(0)

    def step1(ctx):
        ctx.pipeline.append(1)

    with task.start(ctx=TestContext()):
        task.forward(step0)
        task.forward(step1)
        task.backward()
        assert task.ctx.pipeline == [0, 1, 0]
        assert len(task._backward_stack) == 0


@pytest.mark.unittest
def test_async_pipeline():

    def step0(ctx):
        ctx.pipeline.append(0)

    def step1(ctx):
        ctx.pipeline.append(1)

    # Execute step1, step2 twice
    with task.start(async_mode=True, ctx=TestContext()):
        for _ in range(2):
            task.forward(step0)
            sleep(0.1)
            task.forward(step1)
            sleep(0.1)
        task.backward()
        assert task.ctx.pipeline == [0, 1, 0, 1]
        task.renew()
        assert task.ctx.total_step == 1


@pytest.mark.unittest
def test_async_yield_pipeline():

    def step0(ctx):
        sleep(0.1)
        ctx.pipeline.append(0)
        yield
        ctx.pipeline.append(0)

    def step1(ctx):
        sleep(0.2)
        ctx.pipeline.append(1)

    with task.start(async_mode=True, ctx=TestContext()):
        task.forward(step0)
        task.forward(step1)
        sleep(0.3)
        task.backward().sync()
        assert task.ctx.pipeline == [0, 1, 0]
        assert len(task._backward_stack) == 0


def parallel_main():
    sync_count = 0

    def on_count():
        nonlocal sync_count
        sync_count += 1

    def counter(task):

        def _counter(ctx):
            sleep(0.2 + random.random() / 10)
            task.emit("count", only_remote=True)

        return _counter

    with task.start():
        task.on("count", on_count)
        task.use(counter(task))
        task.run(max_step=10)
        assert sync_count > 0


@pytest.mark.tmp
def test_parallel_pipeline():
    Parallel.runner(n_parallel_workers=2, startup_interval=0.1)(parallel_main)


@pytest.mark.tmp
def test_emit():
    with task.start():
        greets = []
        task.on("Greeting", lambda msg: greets.append(msg))

        def step1(ctx):
            task.emit("Greeting", "Hi")

        task.use(step1)
        task.run(max_step=10)
        sleep(0.1)
    assert len(greets) == 10


def emit_remote_main():
    with task.start():
        greets = []
        if task.router.node_id == 0:
            task.on("Greeting", lambda msg: greets.append(msg))
            for _ in range(20):
                if greets:
                    break
                sleep(0.1)
            assert len(greets) > 0
        else:
            for _ in range(20):
                task.emit("Greeting", "Hi", only_remote=True)
                sleep(0.1)
            assert len(greets) == 0


@pytest.mark.tmp
def test_emit_remote():
    Parallel.runner(n_parallel_workers=2, startup_interval=0.1)(emit_remote_main)


@pytest.mark.tmp
def test_wait_for():
    # Wait for will only work in async or parallel mode
    with task.start(async_mode=True, n_async_workers=2):
        greets = []

        def step1(_):
            hi = task.wait_for("Greeting")[0][0]
            if hi:
                greets.append(hi)

        def step2(_):
            task.emit("Greeting", "Hi")

        task.use(step1)
        task.use(step2)
        task.run(max_step=10)

    assert len(greets) == 10
    assert all(map(lambda hi: hi == "Hi", greets))

    # Test timeout exception
    with task.start(async_mode=True, n_async_workers=2):

        def step1(_):
            task.wait_for("Greeting", timeout=0.3, ignore_timeout_exception=False)

        task.use(step1)
        with pytest.raises(TimeoutError):
            task.run(max_step=1)


@pytest.mark.tmp
def test_async_exception():
    with task.start(async_mode=True, n_async_workers=2):

        def step1(_):
            task.wait_for("any_event")  # Never end

        def step2(_):
            sleep(0.3)
            raise Exception("Oh")

        task.use(step1)
        task.use(step2)
        with pytest.raises(Exception):
            task.run(max_step=2)

        assert task.ctx.total_step == 0


def early_stop_main():
    with task.start():
        task.use(lambda _: sleep(0.5))
        if task.match_labels("node.0"):
            task.run(max_step=10)
        else:
            task.run(max_step=2)
        assert task.ctx.total_step < 7


@pytest.mark.tmp
def test_early_stop():
    Parallel.runner(n_parallel_workers=2, startup_interval=0.1)(early_stop_main)


@pytest.mark.tmp
def test_parallel_in_sequencial():
    result = []

    def fast(_):
        result.append("fast")

    def slow(_):
        sleep(0.1)
        result.append("slow")

    with task.start():
        task.use(lambda _: result.append("begin"))
        task.use(task.parallel(slow, fast))
        task.run(max_step=1)
        assert result == ["begin", "fast", "slow"]


@pytest.mark.tmp
def test_serial_in_parallel():
    result = []

    def fast(_):
        result.append("fast")

    def slow(_):
        sleep(0.1)
        result.append("slow")

    with task.start(async_mode=True):
        task.use(lambda _: result.append("begin"))
        task.use(task.serial(slow, fast))
        task.run(max_step=1)

        assert result == ["begin", "slow", "fast"]


@pytest.mark.unittest
def test_nested_middleware():
    """
    When there is a yield in the middleware,
    calling this middleware in another will lead to an unexpected result.
    Use task.forward or task.wrap can fix this problem.
    """
    result = []

    def child():

        def _child(ctx: Context):
            result.append(3 * ctx.total_step)
            yield
            result.append(2 + 3 * ctx.total_step)

        return _child

    def mother():
        _child = task.wrap(child())

        def _mother(ctx: Context):
            child_back = _child(ctx)
            result.append(1 + 3 * ctx.total_step)
            child_back()

        return _mother

    with task.start():
        task.use(mother())
        task.run(2)
        assert result == [0, 1, 2, 3, 4, 5]


@pytest.mark.unittest
def test_use_lock():

    def slow(ctx):
        sleep(0.1)
        ctx.result = "slow"

    def fast(ctx):
        ctx.result = "fast"

    with task.start(async_mode=True):
        # The lock will turn async middleware into serial
        task.use(slow, lock=True)
        task.use(fast, lock=True)
        task.run(1)
        assert task.ctx.result == "fast"

    # With custom lock, it will not affect the inner lock of task
    lock = Lock()

    def slowest(ctx):
        sleep(0.3)
        ctx.result = "slowest"

    with task.start(async_mode=True):
        task.use(slow, lock=lock)
        # If it receives other locks, it will not be the last one to finish execution
        task.use(slowest, lock=True)
        task.use(fast, lock=lock)
        task.run(1)
        assert task.ctx.result == "slowest"


def broadcast_finish_main():
    with task.start():

        def tick(ctx: Context):
            if task.router.node_id == 1 and ctx.total_step == 1:
                task.finish = True
            sleep(1)

        task.use(tick)
        task.run(20)


def broadcast_main_target():
    Parallel.runner(
        n_parallel_workers=1, protocol="tcp", address="127.0.0.1", topology="mesh", ports=50555, startup_interval=0.1
    )(broadcast_finish_main)


def broadcast_secondary_target():
    "Start two standalone processes and connect to the main process."
    Parallel.runner(
        n_parallel_workers=2,
        protocol="tcp",
        address="127.0.0.1",
        topology="alone",
        ports=50556,
        attach_to=["tcp://127.0.0.1:50555"],
        node_ids=[1, 2],
        startup_interval=0.1
    )(broadcast_finish_main)


@pytest.mark.tmp  # gitlab ci and local test pass, github always fail
@pytest.mark.timeout(10)
def test_broadcast_finish():
    start = time()
    ctx = mp.get_context("spawn")
    main_process = ctx.Process(target=broadcast_main_target)
    secondary_process = ctx.Process(target=broadcast_secondary_target)
    main_process.start()
    secondary_process.start()
    main_process.join()
    secondary_process.join()
    assert (time() - start) < 10