|
| 1 | +"""A time-sliced trainer's turn takes in the requests that queue for its model while it waits or runs, so an optim_step |
| 2 | +sent right after its forward_backward runs in the same turn instead of waiting for a turn of its own.""" |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import contextlib |
| 6 | +import os |
| 7 | +import sys |
| 8 | +import time |
| 9 | +import unittest |
| 10 | +from unittest.mock import patch |
| 11 | + |
| 12 | +from server.store import InMemoryStore |
| 13 | +from server.training_requests_processor import TrainingRequestsProcessor |
| 14 | +from tests.test_fft_batch_failure import SlicerStub |
| 15 | +from tests.test_telemetry import ScriptedTrainer, request |
| 16 | + |
| 17 | + |
| 18 | +class QueueStore(InMemoryStore): |
| 19 | + """The model's queue as a list of batches: get_requests_for_model takes the next one, queued counts what waits.""" |
| 20 | + |
| 21 | + def __init__(self, *batches): |
| 22 | + super().__init__() |
| 23 | + self.batches = [list(b) for b in batches] |
| 24 | + self.futures = {} |
| 25 | + self.fetches = 0 |
| 26 | + |
| 27 | + async def get_requests_for_model(self, model_id): |
| 28 | + self.fetches += 1 |
| 29 | + return self.batches.pop(0) if self.batches else [] |
| 30 | + |
| 31 | + async def queued(self, model_id): |
| 32 | + return len(self.batches[0]) if self.batches else 0 |
| 33 | + |
| 34 | + async def set_result(self, request_id, result): |
| 35 | + self.futures[request_id] = result |
| 36 | + |
| 37 | + |
| 38 | +class CountingSlicer(SlicerStub): |
| 39 | + def __init__(self): |
| 40 | + self.turns = 0 |
| 41 | + |
| 42 | + @contextlib.asynccontextmanager |
| 43 | + async def acquire(self, workload): |
| 44 | + self.turns += 1 |
| 45 | + yield |
| 46 | + |
| 47 | + |
| 48 | +def serve(store, slicer): |
| 49 | + with patch.dict(os.environ, {"REDIS_URL": "redis://test"}): |
| 50 | + processor = TrainingRequestsProcessor(store, ScriptedTrainer(), "run-a", time_slicer=slicer) |
| 51 | + asyncio.run(processor.run_once()) |
| 52 | + return processor |
| 53 | + |
| 54 | + |
| 55 | +class TurnDrainTest(unittest.TestCase): |
| 56 | + def test_a_request_queued_during_the_turn_runs_in_it(self) -> None: |
| 57 | + store, slicer = QueueStore([request("fb-1", "forward_backward", data=[])], [request("os-1", "optim_step")]), CountingSlicer() |
| 58 | + serve(store, slicer) |
| 59 | + self.assertEqual(slicer.turns, 1) |
| 60 | + self.assertEqual(sorted(store.futures), ["fb-1", "os-1"]) |
| 61 | + self.assertNotEqual(store.futures["os-1"].get("type"), "RequestFailedResponse") |
| 62 | + |
| 63 | + def test_the_drain_keeps_going_while_requests_keep_queueing(self) -> None: |
| 64 | + batches = [[request(f"fb-{i}", "forward_backward", data=[])] for i in range(3)] + [[request("os-1", "optim_step")]] |
| 65 | + store, slicer = QueueStore(*batches), CountingSlicer() |
| 66 | + serve(store, slicer) |
| 67 | + self.assertEqual((slicer.turns, sorted(store.futures)), (1, ["fb-0", "fb-1", "fb-2", "os-1"])) |
| 68 | + |
| 69 | + def test_no_budget_means_no_drain(self) -> None: |
| 70 | + store, slicer = QueueStore([request("fb-1", "forward_backward", data=[])], [request("os-1", "optim_step")]), CountingSlicer() |
| 71 | + # the class's own module: another test re-imports this module, so a reference taken at import may be stale |
| 72 | + with patch.object(sys.modules[TrainingRequestsProcessor.__module__], "TURN_DRAIN_SECONDS", 0): |
| 73 | + serve(store, slicer) |
| 74 | + self.assertEqual(sorted(store.futures), ["fb-1"], "the optim_step waits for the next batch") |
| 75 | + self.assertEqual(len(store.batches), 1) |
| 76 | + |
| 77 | + def test_a_save_ends_the_drain(self) -> None: |
| 78 | + # The save in the first batch runs after the turn's GPU ops; nothing queued behind it may run before it. |
| 79 | + first = [request("os-1", "optim_step"), request("sv-1", "save_weights_for_sampler", path="x")] |
| 80 | + store, slicer = QueueStore(first, [request("fb-2", "forward_backward", data=[])]), CountingSlicer() |
| 81 | + with patch.object(TrainingRequestsProcessor, "handle_request", new=_answer): |
| 82 | + serve(store, slicer) |
| 83 | + self.assertEqual(store.fetches, 1) |
| 84 | + self.assertEqual(len(store.batches), 1, "fb-2 stays queued for the next batch") |
| 85 | + |
| 86 | + def test_an_empty_queue_is_not_waited_on(self) -> None: |
| 87 | + store, slicer = QueueStore([request("fb-1", "forward_backward", data=[])]), CountingSlicer() |
| 88 | + serve(store, slicer) |
| 89 | + self.assertEqual(store.fetches, 1, "an empty queue is checked with queued(), never with the blocking pop") |
| 90 | + |
| 91 | + def test_a_shutdown_taken_while_draining_is_honoured(self) -> None: |
| 92 | + store = QueueStore([request("fb-1", "forward_backward", data=[])], [{"request_id": "sd", "op": "shutdown_workers", "model_id": "run-a"}]) |
| 93 | + with patch.object(TrainingRequestsProcessor, "exit_gracefully") as exit_gracefully: |
| 94 | + serve(store, CountingSlicer()) |
| 95 | + exit_gracefully.assert_called_once() |
| 96 | + |
| 97 | + |
| 98 | +async def _answer(self, r): |
| 99 | + """Answers any request, so a save needs no real checkpoint.""" |
| 100 | + return r["request_id"], {"type": "ok"} |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == "__main__": |
| 104 | + unittest.main() |
| 105 | + |
| 106 | + |
| 107 | +class LongBatchTest(unittest.TestCase): |
| 108 | + def test_the_budget_starts_after_the_turns_own_batch(self) -> None: |
| 109 | + # A forward_backward that runs longer than the whole budget must still let its queued optim_step join the turn. |
| 110 | + class SlowTrainer(ScriptedTrainer): |
| 111 | + def forward_backward(self, *args, **kwargs): |
| 112 | + time.sleep(0.2) |
| 113 | + return super().forward_backward(*args, **kwargs) |
| 114 | + |
| 115 | + store, slicer = QueueStore([request("fb-1", "forward_backward", data=[])], [request("os-1", "optim_step")]), CountingSlicer() |
| 116 | + with ( |
| 117 | + patch.object(sys.modules[TrainingRequestsProcessor.__module__], "TURN_DRAIN_SECONDS", 0.05), |
| 118 | + patch.dict(os.environ, {"REDIS_URL": "redis://test"}), |
| 119 | + ): |
| 120 | + processor = TrainingRequestsProcessor(store, SlowTrainer(), "run-a", time_slicer=slicer) |
| 121 | + asyncio.run(processor.run_once()) |
| 122 | + self.assertEqual((slicer.turns, sorted(store.futures)), (1, ["fb-1", "os-1"])) |
0 commit comments