Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

perf(server): give GLiClass batches of up to eight rows a graph of their own size (#719)

svonava2044b2813be6
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md
index f87e0ea6d..540c26ae5 100644
--- a/packages/sie_server/README.md
+++ b/packages/sie_server/README.md
@@ -201,7 +201,7 @@ labels, so one graph serves every label count.
|--|--|--|
| `off` (default) | none | eager |
| `exact` | each (batch size, sequence length) seen twice; the 64 most recently used are kept | bit-identical to eager |
-| `bucketed` | sequence lengths padded up to a multiple of 64 tokens at a 1,024-token window (32 at 512), batch sizes up to a power of two: a fixed set of shapes, all kept | padding moves fp16 probabilities (see below) |
+| `bucketed` | sequence lengths padded up to a multiple of 64 tokens at a 1,024-token window (32 at 512); batches of up to eight rows keep their size, larger ones pad up to a power of two: a fixed set of shapes, all kept | padding moves fp16 probabilities (see below) |
A request can send `options={"cuda_graphs": "off"}` to run eagerly on a model
loaded with graphs. It cannot turn graphs on: any other value is refused.
@@ -263,12 +263,24 @@ the instruction set:
A top label that changed did so in every pass; the table counts each answer
once.
-Requests of several items pad their batch as well (3 items to 4, 5 to 8). Asked
-in 3- and 5-item requests and compared with eager execution of the same
-requests, the eight models that ship with graphs moved no probability by more
-than 0.0190 (`opir-multitask-large-v1.0`) and 0.0115 for every other model,
-and every top label that changed had an eager margin below the model's
-δ_eager.
+Requests of up to eight rows run at their own batch size, so only their length
+is padded; a forward of nine rows or more pads up to a power of two (9 rows to
+16) or to the largest batch the token bound allows at its length. A request of
+three questions as separate groups is three rows. The table above was measured
+when a batch padded up to a power of two (3 rows to 4, 5 to 8). With batches of
+up to eight rows keeping their size, the 384 CVE descriptions were asked again
+in 1-, 3-, 5- and 8-item requests with the weakness question's eight labels,
+and as three questions in separate groups, and compared with eager execution of
+the same requests: the eight models that ship with graphs moved no probability
+by more than 0.0127 (`opir-multitask-large-v1.0`, three questions) and 0.0098
+for every other model, and every top label that changed had an eager margin
+below the model's δ_eager (the largest was 0.0056, on
+`gliclass-instruct-base-v1.0`). Eight CVE descriptions in one batch are over
+the token bound of the DeBERTa-v3-large models and run eagerly, so the
+eight-row shapes of those four models were checked on requests of eight short
+news texts with eight labels instead: against eager execution no probability
+moved by more than 0.0083, and no top label changed. One-row forwards replay
+the same shapes as before.
`exact` changed nothing. A forward whose batch size is already a bucket (one
item, for example) scores exactly as it did before batches were padded.
@@ -294,12 +306,26 @@ Larger forwards are bound by the GPU rather than by kernel launches and run
eagerly: on an L4, a `gliclass-large-v1.0` forward stops gaining from a graph
at about 1,000 tokens, a `gliclass-base-v1.0` forward at about 2,000. In
`bucketed` mode at the 1,024-token window that leaves a fixed set of shapes,
-33 for the DeBERTa-v3-large models and 52 for the base and small ones (52 and
-71 at a 512-token window), and the model keeps a graph for every one. Once
+48 for the DeBERTa-v3-large models and 84 for the base and small ones (84 and
+136 at a 512-token window), and the model keeps a graph for every one. Once
they are recorded, every forward under the token bound replays a graph,
whatever mix of label counts, batch sizes and lengths the traffic has, and no
request's shapes push out another's.
+**Padding costs GPU time.** A replay is not bound by kernel launches, so it
+costs the GPU time of its padded shape, which grows with the tokens in it. On
+an L4, `gliclass-instruct-large-v1.0` replays three rows of 192 tokens in
+19 ms and four rows in 24 ms; eight rows of 96 tokens in 21 ms and eight rows
+of 128 tokens in 31 ms. So two paddings are kept small. A batch of up to eight
+rows keeps its size instead of padding up to a power of two. And a forward of
+eight rows or more, where short texts are bound by the GPU, buckets its length
+at half the width (32 tokens at a 1,024-token window, 16 at 512), unless the
+window's bucket pads fewer tokens. In process on an L4, eight short texts per
+request went from 31.8 to 23.3 ms on `gliclass-instruct-large-v1.0` and from
+12.4 to 11.2 ms on `gliclass-base-v3.0`, and three questions about one record
+from 25.8 to 21.3 ms and from 11.2 to 8.9 ms; one text per request did not
+change (7.8 and 3.6 ms).
+
Nothing is recorded at load. A shape is recorded the first time a request
needs it (the second time in `exact` mode), and the new graph's first replay
answers that request, which takes 52 to 66 ms against 43 ms for an eager
@@ -315,13 +341,16 @@ into one shared buffer, and the driver keeps a copy of each graph: about 7 MB
for the `gliclass-large-v1.0` encoder. The runner adds up the device memory
its graphs hold (what each recording took, plus the tables and buffers they
read) against 4% of the device's memory (900 MB on an L4). On an L4, at the
-1,024-token window, all of a model's `bucketed` shapes took 551 to 571 MB for
-the large GLiClass models, 677 MB for `opir-multitask-large-v1.0`, 761 to
-767 MB for the base models and 653 MB for `gliclass-small-v1.0`, plus about
-150 MB cached on the recording stream (its cuBLAS workspace and one warm-up
-row). Recorded while serving mixed traffic, the same shapes can take more, and
-at the 1,024-token window the budget can fill with one to three shapes left
-unrecorded; those shapes run eagerly. On a smaller GPU, where the shapes do not
+1,024-token window, all of a model's `bucketed` shapes, recorded largest
+first, took 743 to 777 MB for the large GLiClass models, 777 MB for
+`opir-multitask-large-v1.0`, 760 to 834 MB for the base models and 578 MB for
+`gliclass-small-v1.0`, plus about 150 MB cached on the recording stream (its
+cuBLAS workspace and one warm-up row). Recorded in another order, the same
+shapes take more, because the shared pool grows in steps: recorded smallest
+first, the budget fills with the largest shapes of each batch size left
+unrecorded (9 of 48 on `gliclass-instruct-large-v1.0`, 19 of 84 on
+`gliclass-base-v3.0`). Those are the shapes a graph gains least on, and they
+run eagerly. On a smaller GPU, where the shapes do not
all fit, recording stops at the budget and the graphs already recorded keep
replaying; the other shapes run eagerly. In `exact` mode, whose shapes are
unbounded, a model past its budget drops every graph, returns their memory to
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
index 8eb40af59..d973bb1fc 100644
--- a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
@@ -32,17 +32,30 @@ Two modes choose the shape:
nothing. The shapes are unbounded; a runner keeps the 64 most recently used
graphs.
- ``bucketed`` pads the length up to a bucket (a multiple of 32 tokens at a
- 512-token window, 64 at 1,024) and the batch up to a power of two, or to the
- largest batch the token bound allows at that length. Padded positions are
- masked, and padded rows are dropped before scoring. That makes the set of
- shapes small and fixed (52 for gliclass-large-v1.0, 71 for
- gliclass-base-v1.0, 33 for opir-multitask-large-v1.0), and the runner keeps
- a graph for every one, so after warm-up forwards replay whatever mix of
- batch sizes, lengths and label counts the traffic has. A longer sequence, or
- a larger batch, rounds fp16 sums differently, as when requests are batched
- together: up to 0.006 in probability on gliclass-large-v1.0 and 0.023 on
- gliclass-multilang-mini in our tests. A forward whose batch is already a
- bucket scores exactly as it did when graphs also covered the head.
+ 512-token window, 64 at 1,024). A batch of up to eight rows keeps its size;
+ a larger one pads up to a power of two, or to the largest batch the token
+ bound allows at that length. A forward of eight rows or more buckets its
+ length at half the width (see "Padding costs GPU time" below). Padded
+ positions are masked, and padded rows are dropped before scoring. That makes the set of shapes small and
+ fixed (48 at a 1,024-token window for an encoder wider than 768, 84 for a
+ narrower one), and the runner keeps a graph for every one, so after warm-up
+ forwards replay whatever mix of batch sizes, lengths and label counts the
+ traffic has. A longer sequence, or a larger batch, rounds fp16 sums
+ differently, as when requests are batched together: up to 0.006 in
+ probability on gliclass-large-v1.0 and 0.023 on gliclass-multilang-mini in
+ our tests. A forward whose batch is already a bucket scores exactly as it
+ did when graphs also covered the head.
+
+Padding costs GPU time. A replay is not bound by kernel launches, so what it
+costs is the GPU time of its padded shape, and that grows with the tokens in
+it. On an L4, a gliclass-instruct-large-v1.0 replay of three rows of 192
+tokens takes 19 ms and of four rows 24 ms; of eight rows of 96 tokens 21 ms
+and of eight rows of 128 tokens 31 ms. So a batch of up to eight rows (a
+request of three typed questions is three rows, and a labels request runs
+eight rows per forward) gets a graph of its own size instead of the next
+power of two. And a forward of eight rows or more, which the GPU bounds even
+when its rows are short, buckets its length at half the width (32 tokens at a
+1,024-token window, 16 at 512), unless the window's bucket pads fewer tokens.
While a graph is being recorded, PyTorch's caching allocator will not free
cached blocks to satisfy another allocation, so another model on the same GPU
@@ -151,6 +164,13 @@ _RECORDING_LOCK = RECORDING_LOCK
_MAX_RECORDING_FAILURES = 3
# A runner serving forwards logs its counters this often.
_SUMMARY_SECONDS = 600.0
+# Rows a ``bucketed`` batch may have without padded rows: every batch size up to
+# this many gets a graph of its own. Larger batches pad to a power of two.
+_EXACT_BATCH_ROWS = 8
+# Forwards of at least this many rows bucket their length at half the width:
+# they are the forwards whose replay the GPU bounds even at short lengths, so
+# their padded tokens cost time in proportion.
+_FINE_LENGTH_ROWS = 8
# Encoders whose forward records cleanly once the two host reads are replaced.
_ENCODERS = frozenset({"deberta-v2"})
# Poolings whose pooled vector ignores padded positions, so ``bucketed`` mode
@@ -193,9 +213,13 @@ def unsupported_reason(model: Any, device: str | torch.device) -> str | None:
return None
-def bucket_width(max_length: int) -> int:
- """Sequence-length bucket for ``bucketed`` mode: 32 tokens at a 512 window, 64 at 1,024."""
- return max(16, max_length // 16)
+def bucket_width(max_length: int, batch: int = 1) -> int:
+ """Sequence-length bucket for ``bucketed`` mode: 32 tokens at a 512 window, 64 at 1,024.
+
+ A forward of ``_FINE_LENGTH_ROWS`` rows or more buckets at half that width.
+ """
+ width = max(16, max_length // 16)
+ return width if batch < _FINE_LENGTH_ROWS else max(16, width // 2)
def token_bound(hidden_size: int) -> int:
@@ -204,24 +228,55 @@ def token_bound(hidden_size: int) -> int:
def batch_buckets(length: int, max_tokens: int) -> tuple[int, ...]:
- """Batch sizes ``bucketed`` graphs of this padded length hold: powers of two, and the largest that fits.
+ """Batch sizes that fit ``bucketed`` graphs of this padded length.
- A batch pads up to the next of these, so a batch past a power of two
- costs at most twice its rows, and one near the token bound pads only to
- the bound.
+ Every size up to ``_EXACT_BATCH_ROWS``, then powers of two, and the
+ largest that fits. A batch pads up to the next of these, so a batch of up
+ to eight rows pads no rows, a larger one costs at most twice its rows, and
+ one near the token bound pads only to the bound.
"""
largest = max_tokens // length
- sizes = [1 << power for power in range(largest.bit_length())]
- if largest and sizes[-1] != largest:
- sizes.append(largest)
- return tuple(sizes)
+ sizes = set(range(1, min(largest, _EXACT_BATCH_ROWS) + 1))
+ sizes.update(1 << power for power in range(largest.bit_length()))
+ if largest:
+ sizes.add(largest)
+ return tuple(sorted(sizes))
+
+
+def bucketed_key(batch: int, length: int, max_length: int, max_tokens: int) -> Key | None:
+ """The shape a ``bucketed`` forward of ``batch`` rows of ``length`` tokens pads to.
+
+ None when no shape under the token bound holds it. A batch of up to
+ ``_EXACT_BATCH_ROWS`` rows keeps its size and rounds its length up to the
+ window's bucket. A larger batch rounds its length up to the finer bucket
+ or to the window's, and its rows up to the next size graphs of that length
+ hold, whichever pads fewer tokens: the finer length is shorter, but its
+ next batch size can be further away.
+ """
+ best: Key | None = None
+ for rows in (batch, 1) if batch >= _FINE_LENGTH_ROWS else (batch,):
+ width = bucket_width(max_length, rows)
+ padded = min(max_length, math.ceil(length / width) * width)
+ size = next((size for size in batch_buckets(padded, max_tokens) if size >= batch), 0)
+ if size and (best is None or size * padded < best[0] * best[1]):
+ best = (size, padded)
+ return best
def bucketed_shapes(max_length: int, max_tokens: int) -> frozenset[Key]:
"""Every shape a ``bucketed`` runner can record at this window."""
- width = bucket_width(max_length)
- lengths = {min(max_length, width * step) for step in range(1, math.ceil(max_length / width) + 1)}
- return frozenset((batch, length) for length in lengths for batch in batch_buckets(length, max_tokens))
+ shapes: set[Key] = set()
+ for rows in (1, _FINE_LENGTH_ROWS):
+ width = bucket_width(max_length, rows)
+ for step in range(1, math.ceil(max_length / width) + 1):
+ length = min(max_length, width * step)
+ shapes.update(
+ (batch, length)
+ for batch in batch_buckets(length, max_tokens)
+ # Rows under the finer bucket's size pad only to the window's bucket.
+ if batch >= rows
+ )
+ return frozenset(shapes)
class _RecordingOutOfMemoryError(Exception):
@@ -255,7 +310,6 @@ class CudaGraphRunner:
self._name = name
self._pad_values = {"input_ids": pad_token_id, "attention_mask": 0, "token_type_ids": pad_token_type_id}
self._max_length = max_length
- self._bucket = bucket_width(max_length)
config = model.config
self._hidden_size = int(config.encoder_config.hidden_size)
embeddings = getattr(model.model.encoder_model, "get_input_embeddings", None)
@@ -277,6 +331,8 @@ class CudaGraphRunner:
self._failed: set[Key] = set()
self._lock = threading.RLock()
self._stream: torch.cuda.Stream | None = None
+ # Threads that have run a forward on that stream (see ``_record``).
+ self._warmed = threading.local()
self._disabled = False
# Set when the memory budget holds no more of a bucketed runner's graphs.
self._full = False
@@ -364,10 +420,9 @@ class CudaGraphRunner:
def key(self, batch: int, length: int, mode: GraphMode) -> Key | None:
"""The graph a forward of this shape would replay; None when it runs eagerly."""
if mode == "bucketed" and self._padding_safe:
- length = min(self._max_length, math.ceil(length / self._bucket) * self._bucket)
- batch = next((size for size in batch_buckets(length, self._max_tokens) if size >= batch), 0)
- if not batch:
+ if length > self._max_length:
return None
+ return bucketed_key(batch, length, self._max_length, self._max_tokens)
if batch * length > self._max_tokens or length > self._max_length:
return None
return (batch, length)
@@ -635,11 +690,15 @@ class CudaGraphRunner:
"""Record the graph for ``key``.
Recording runs on a stream of the runner's own, whose first use
- creates per-stream state (the cuBLAS handle and workspace) that cannot
- be created while recording: the first recording warms that stream up
- with one row of its inputs, the only memory left cached on it.
- Recording launches no kernels; the caller replays the graph to answer
- the forward.
+ creates state (the cuBLAS handle and workspace) that cannot be created
+ while recording. PyTorch keeps the cuBLAS handle per thread and its
+ workspace per handle and stream, and the server does not tie a model
+ to one thread: it loads and warms a model up on one and serves it on
+ another. So each thread's first recording warms that stream up with
+ one row of its inputs, the only memory left cached on it; without
+ that, the first recording of a second thread fails with
+ ``CUBLAS_STATUS_NOT_INITIALIZED``. Recording launches no kernels; the
+ caller replays the graph to answer the forward.
Raises:
_RecordingOutOfMemoryError: When the warm-up or the recording runs out
@@ -665,7 +724,7 @@ class CudaGraphRunner:
if relative_pos is not None:
self._relative_pos[padded_length] = relative_pos
hidden = self._hidden_states(key, self._dtype, device)
- warm_up = self._stream is None
+ warm_up = self._stream is None or not getattr(self._warmed, "done", False)
stream = self._stream or torch.cuda.Stream(device=device)
pool = next(iter(self._graphs.values())).graph.pool() if self._graphs else None
graph = torch.cuda.CUDAGraph()
@@ -676,6 +735,7 @@ class CudaGraphRunner:
self._model(**{name: value[:1] for name, value in static.items()})
# Kept only once warmed up, so a failed warm-up is tried again.
self._stream = stream
+ self._warmed.done = True
free_before = self._free_memory(device)
graph.capture_begin(pool=pool, capture_error_mode="thread_local")
try:
diff --git a/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py b/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py
index 38827f42f..24f9dc1cd 100644
--- a/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py
+++ b/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py
@@ -24,6 +24,7 @@ from sie_server.adapters.gliclass.cuda_graphs import (
CudaGraphRunner,
batch_buckets,
bucket_width,
+ bucketed_key,
bucketed_shapes,
segment_ids,
token_bound,
@@ -182,6 +183,13 @@ class TestShapes:
@pytest.mark.parametrize(("max_length", "width"), [(512, 32), (1024, 64), (128, 16)])
def test_bucket_width_follows_the_window(self, max_length: int, width: int) -> None:
assert bucket_width(max_length) == width
+ assert {bucket_width(max_length, batch) for batch in range(1, 8)} == {width}
+
+ @pytest.mark.parametrize(("max_length", "width"), [(512, 16), (1024, 32), (128, 16)])
+ def test_forwards_of_eight_rows_or_more_bucket_their_length_at_half_the_width(
+ self, max_length: int, width: int
+ ) -> None:
+ assert {bucket_width(max_length, batch) for batch in (8, 9, 16, 64)} == {width}
@pytest.mark.parametrize(("hidden_size", "tokens"), [(384, 2048), (768, 2048), (1024, 1024), (1536, 1024)])
def test_wider_encoders_hold_fewer_tokens(self, hidden_size: int, tokens: int) -> None:
@@ -197,35 +205,88 @@ class TestShapes:
@pytest.mark.parametrize(
("length", "tokens", "sizes"),
[
- (32, 2048, (1, 2, 4, 8, 16, 32, 64)),
- (96, 2048, (1, 2, 4, 8, 16, 21)),
- (512, 2048, (1, 2, 4)),
- (96, 1024, (1, 2, 4, 8, 10)),
- (192, 1024, (1, 2, 4, 5)),
+ (32, 2048, (1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64)),
+ (96, 2048, (1, 2, 3, 4, 5, 6, 7, 8, 16, 21)),
+ (512, 2048, (1, 2, 3, 4)),
+ (96, 1024, (1, 2, 3, 4, 5, 6, 7, 8, 10)),
+ (192, 1024, (1, 2, 3, 4, 5)),
(512, 1024, (1, 2)),
(1024, 1024, (1,)),
],
)
- def test_batch_buckets_are_powers_of_two_and_the_largest_that_fits(
+ def test_batch_buckets_are_every_size_up_to_eight_then_powers_of_two_and_the_largest_that_fits(
self, length: int, tokens: int, sizes: tuple[int, ...]
) -> None:
assert batch_buckets(length, tokens) == sizes
- def test_bucketed_batches_pad_up_to_their_bucket(self) -> None:
- runner = _Runner() # a DeBERTa-large-wide encoder: 1,024 tokens
+ def test_batches_of_up_to_eight_rows_keep_their_size(self) -> None:
+ runner = _Runner() # a DeBERTa-large-wide encoder: 1,024 tokens, 32-token buckets at this 512 window
- assert [runner.key(batch, 100, "bucketed") for batch in (1, 2, 3, 4, 5, 8)] == [
+ assert [runner.key(batch, 100, "bucketed") for batch in (1, 2, 3, 4, 5, 6, 7)] == [
(1, 128),
(2, 128),
+ (3, 128),
(4, 128),
- (4, 128),
- (8, 128),
- (8, 128),
+ (5, 128),
+ (6, 128),
+ (7, 128),
]
- assert runner.key(9, 100, "bucketed") is None # 9 x 128 tokens: over the bound
assert runner.key(5, 190, "bucketed") == (5, 192) # the largest batch at 192 tokens
assert runner.key(3, 100, "exact") == (3, 100) # exact mode never pads
+ def test_eight_rows_or_more_pad_their_length_to_a_finer_bucket(self) -> None:
+ runner = _Runner() # 16-token buckets for eight rows or more at this 512 window
+
+ assert runner.key(8, 100, "bucketed") == (8, 112)
+ assert runner.key(8, 97, "bucketed") == (8, 112)
+ assert runner.key(8, 96, "bucketed") == (8, 96)
+ assert runner.key(9, 100, "bucketed") == (9, 112) # the largest batch at 112 tokens
+ assert runner.key(10, 100, "bucketed") is None # 10 x 112 tokens: over the bound
+ assert runner.key(9, 60, "bucketed") == (16, 64) # past eight rows, up to a power of two
+ # Where the finer length's next batch size pads more tokens than the window's bucket does, the window's wins:
+ # 9 rows of 65 tokens fit 12 x 80 or 10 x 96 tokens, the same 960, and the shorter rows are kept;
+ narrow = _Runner(_model(hidden_size=768))
+ assert runner.key(9, 65, "bucketed") == (12, 80)
+ # 9 rows of 129 tokens fit 14 x 144 (2,016 tokens) or 12 x 160 (1,920).
+ assert narrow.key(9, 129, "bucketed") == (12, 160)
+ wide_window = CudaGraphRunner(_model(), pad_token_id=0, max_length=1024)
+ assert wide_window.key(8, 91, "bucketed") == (8, 96) # 32-token buckets at a 1,024 window
+ assert wide_window.key(7, 91, "bucketed") == (7, 128) # under eight rows: 64-token buckets
+
+ @pytest.mark.parametrize(
+ ("max_length", "hidden_size"),
+ [(1024, 1024), (1024, 768), (512, 1024), (512, 768)],
+ ids=["large-1024", "base-1024", "large-512", "base-512"],
+ )
+ def test_no_forward_pads_more_than_it_did_with_power_of_two_batches(
+ self, max_length: int, hidden_size: int
+ ) -> None:
+ # The shapes before batches of up to eight rows kept their size: the length to the
+ # window's bucket, the batch to a power of two or the largest that fits.
+ tokens = token_bound(hidden_size)
+ width = bucket_width(max_length)
+
+ def before(batch: int, length: int) -> tuple[int, int] | None:
+ padded = min(max_length, -(-length // width) * width)
+ largest = tokens // padded
+ sizes = [1 << power for power in range(largest.bit_length())]
+ if largest and sizes[-1] != largest:
+ sizes.append(largest)
+ size = next((size for size in sizes if size >= batch), 0)
+ return (size, padded) if size else None
+
+ for batch in range(1, 70):
+ for length in range(1, max_length + 1):
+ old, new = before(batch, length), bucketed_key(batch, length, max_length, tokens)
+ if old is None:
+ continue
+ # Every forward that had a graph still has one, of no more tokens and no longer rows.
+ assert new is not None, (batch, length)
+ assert new[0] * new[1] <= old[0] * old[1], (batch, length)
+ assert new[1] <= old[1], (batch, length)
+ assert new[0] >= batch, (batch, length)
+ assert new[1] >= length, (batch, length)
+
def test_shapes_past_the_token_bound_run_eagerly(self) -> None:
runner = _Runner()
@@ -237,7 +298,7 @@ class TestShapes:
narrow = _Runner(_model(hidden_size=768))
assert narrow.key(4, 512, "exact") == (4, 512)
- assert narrow.key(9, 100, "bucketed") == (16, 128)
+ assert narrow.key(9, 100, "bucketed") == (16, 112)
assert narrow.key(65, 32, "bucketed") is None
def test_the_token_bound_does_not_grow_with_the_window(self) -> None:
@@ -249,7 +310,7 @@ class TestShapes:
@pytest.mark.parametrize(
("max_length", "hidden_size", "count"),
- [(1024, 1024, 33), (1024, 768, 52), (512, 1024, 52), (512, 768, 71)],
+ [(1024, 1024, 48), (1024, 768, 84), (512, 1024, 84), (512, 768, 136)],
ids=["large-1024", "base-1024", "large-512", "base-512"],
)
def test_every_bucketed_forward_maps_into_a_small_fixed_set(
@@ -308,7 +369,7 @@ class TestRecordingPolicy:
answers = [runner.run(_inputs(3, 100), classes, "bucketed") for classes in range(1, 101)]
- assert runner.recorded == [(4, 128)]
+ assert runner.recorded == [(3, 128)]
assert runner.head_classes == list(range(1, 101)) # the head scores each forward's own label slots
assert all(answer is not None and answer.shape == (3, classes) for classes, answer in enumerate(answers, 1))
@@ -319,13 +380,13 @@ class TestRecordingPolicy:
assert runner.head_classes == [None]
- def test_batch_sizes_share_their_bucket(self) -> None:
+ def test_batch_sizes_past_eight_rows_share_their_bucket(self) -> None:
runner = _Runner()
- for batch in (3, 4, 5, 6, 7, 8):
- runner.run(_inputs(batch, 100), 4, "bucketed")
+ for batch in (3, 4, 8, 9, 12, 16):
+ runner.run(_inputs(batch, 60), 4, "bucketed")
- assert runner.recorded == [(4, 128), (8, 128)]
+ assert runner.recorded == [(3, 64), (4, 64), (8, 64), (16, 64)]
def test_after_warm_up_every_bucketed_forward_replays_whatever_the_mix(self) -> None:
# Shape cycling: random batch sizes, lengths and label counts for ten
@@ -335,13 +396,13 @@ class TestRecordingPolicy:
rng = random.Random(0) # noqa: S311 -- a reproducible traffic mix, not a secret
for step in range(12_000):
runner.now = step * 0.05
- runner.run(_inputs(rng.randint(1, 32), rng.randint(1, 512)), rng.randint(1, 100), "bucketed")
+ runner.run(_inputs(rng.randint(1, 64), rng.randint(1, 512)), rng.randint(1, 100), "bucketed")
assert len(runner.recorded) == len(set(runner.recorded)) == shapes # each shape once: nothing evicted
assert runner.graph_count == shapes
replayed, eager = runner.stats.replayed, dict(runner.stats.eager)
for _ in range(1000):
- runner.run(_inputs(rng.randint(1, 32), rng.randint(1, 512)), rng.randint(1, 100), "bucketed")
+ runner.run(_inputs(rng.randint(1, 64), rng.randint(1, 512)), rng.randint(1, 100), "bucketed")
new_eager = {reason: count - eager.get(reason, 0) for reason, count in runner.stats.eager.items()}
# Only forwards past the token bound run eagerly; every other forward replays.
assert {reason for reason, count in new_eager.items() if count} <= {"too_large"}
@@ -360,7 +421,7 @@ class TestRecordingPolicy:
assert set(runner._relative_pos) == {64, 96}
def test_recording_is_rationed_in_time(self) -> None:
- runner = _Runner(_model(hidden_size=768)) # 71 shapes
+ runner = _Runner(_model(hidden_size=768)) # 136 shapes
shapes = sorted(bucketed_shapes(512, 2048))
# Every call is a new shape: sixteen record at once, then none while time stands still.
@@ -406,7 +467,7 @@ class TestRecordingPolicy:
assert runner.recorded == [(1, 32), (1, 64), (1, 96)] # the third went over; no more
assert runner.graph_count == 3
assert runner.stats.eager == {"budget_full": 1}
- assert "3 of 52 shapes recorded" in caplog.text
+ assert "3 of 84 shapes recorded" in caplog.text
runner.run(_inputs(1, 32), 4, "bucketed")
assert runner.replayed[-1] == (1, 32) # graphs it holds keep replaying
runner.clear() # an out-of-memory error or unload starts over
@@ -822,7 +883,7 @@ def test_the_adapter_passes_its_label_slots_to_the_head() -> None:
assert logits.shape == (3, 3)
assert runner.head_classes == [3]
- assert runner.recorded == [(4, 128)]
+ assert runner.recorded == [(3, 128)]
class TestOperatorSetting:
diff --git a/packages/sie_server/tests/adapters/test_gliclass_parity.py b/packages/sie_server/tests/adapters/test_gliclass_parity.py
index 0c86946d1..489f46cad 100644
--- a/packages/sie_server/tests/adapters/test_gliclass_parity.py
+++ b/packages/sie_server/tests/adapters/test_gliclass_parity.py
@@ -9,6 +9,7 @@ score like one labels request per group.
from __future__ import annotations
+import threading
import time
from typing import Any
@@ -642,6 +643,32 @@ def test_a_forward_that_cannot_be_recorded_falls_back_to_eager(monkeypatch: pyte
assert _outputs(rig.adapter.extract(items, labels=_LABELS)) == eager
+def test_a_thread_other_than_the_first_records_a_graph() -> None:
+ # The server loads and warms a model up on one thread and serves it on
+ # another: every thread that records must be able to, though PyTorch keeps
+ # a cuBLAS handle per thread and none can be created while recording.
+ if not torch.cuda.is_available():
+ pytest.skip("requires CUDA")
+ rig = _Rig(prompt_first=True, scorer="mlp", device="cuda:0", dtype=torch.float16, cuda_graphs="bucketed")
+ runner = rig.adapter._graphs
+ assert runner is not None
+ one, three = [Item(text=_TEXTS[0])], [Item(text=text) for text in _TEXTS[:3]]
+ eager = _scores(rig.adapter.extract(three, labels=_LABELS, options=_EAGER))
+ rig.adapter.extract(one, labels=_LABELS) # one row: the first graph, recorded on this thread
+ assert (runner.stats.recorded, runner.stats.recording_failures) == (1, 0)
+
+ served: list[Any] = []
+ serving = threading.Thread(target=lambda: served.append(rig.adapter.extract(three, labels=_LABELS)))
+ serving.start()
+ serving.join()
+ # Three rows: a second graph, recorded on a thread that has no cuBLAS handle yet.
+ assert (runner.stats.recorded, runner.stats.recording_failures) == (2, 0)
+ assert not runner.disabled
+ for expected, got in zip(eager, _scores(served[0]), strict=True):
+ assert got == pytest.approx(expected, abs=2e-2)
+
+
@pytest.mark.parametrize("mode", ["exact", "bucketed"])
def test_cuda_graphs_run_eagerly_on_cpu(mode: str) -> None:
items = [Item(text=text) for text in _TEXTS]