-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathscheduler.py
More file actions
1471 lines (1323 loc) · 65 KB
/
Copy pathscheduler.py
File metadata and controls
1471 lines (1323 loc) · 65 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: MIT
# Copyright (C) 2024-2025, Advanced Micro Devices, Inc. All rights reserved.
"""
Scheduling logic for batching prefill and decode requests.
This module provides:
- :class:`SpecStats`: Tracks speculative-decoding acceptance rates.
- :class:`ScheduledBatch`: A frozen snapshot of sequences selected for the
next forward pass, together with their block tables and metadata.
- :class:`ScheduledBatchOutput`: Token-level outputs from a completed batch.
- :class:`Scheduler`: The main scheduling loop that manages *waiting* and
*running* queues, coordinates block allocation, and integrates with the
KV disaggregation connector for remote prefill/decode.
"""
from __future__ import annotations
import logging
import time
from collections import deque
from typing import Optional
import numpy as np
from atom.config import Config
from atom.kv_transfer.disaggregation import KVConnectorOutput
from atom.model_engine.block_manager import BlockManager
from atom.model_engine.request import RequestOutput
from atom.model_engine.sequence import Sequence, SequenceStatus, SequenceType
logger = logging.getLogger("atom")
class SpecStats:
"""Tracks speculative decoding acceptance statistics."""
__slots__ = (
"mtp_k",
"total_draft_tokens",
"distribution",
"_log_interval",
"_interval_draft_tokens",
"_interval_distribution",
)
def __init__(self, mtp_k: int, log_interval: int = 1000):
self.mtp_k = mtp_k
# Log every log_interval decode steps (in terms of draft tokens)
self._log_interval = log_interval * mtp_k
self.total_draft_tokens: int = 0
self.distribution: dict[int, int] = {k: 0 for k in range(mtp_k + 1)}
# Per-interval tracking
self._interval_draft_tokens: int = 0
self._interval_distribution: dict[int, int] = {k: 0 for k in range(mtp_k + 1)}
def update(self, num_accepted_tokens: int) -> None:
"""Record acceptance result for one sequence in one decode step."""
self.total_draft_tokens += self.mtp_k
self._interval_draft_tokens += self.mtp_k
num_bonus = num_accepted_tokens - 1
self.distribution[num_bonus] += 1
self._interval_distribution[num_bonus] += 1
if self.total_draft_tokens % self._log_interval == 0:
self._log()
self._reset_interval()
@property
def total_accepted(self) -> int:
"""Total number of accepted bonus tokens across all steps."""
return sum(k * v for k, v in self.distribution.items())
@property
def total_steps(self) -> int:
"""Total number of decode steps recorded."""
return sum(self.distribution.values())
@property
def acceptance_rate(self) -> float:
if self.total_draft_tokens == 0:
return 0.0
return self.total_accepted / self.total_draft_tokens
def get_statistics(self) -> dict:
"""Return a summary dict compatible with engine_core reporting."""
return {
"total_draft_tokens": self.total_draft_tokens,
"total_accepted_tokens": self.total_accepted,
"acceptance_rate": self.acceptance_rate,
"distribution": dict(self.distribution),
}
def reset(self) -> None:
self.total_draft_tokens = 0
self.distribution = {k: 0 for k in range(self.mtp_k + 1)}
self._reset_interval()
def _reset_interval(self) -> None:
self._interval_draft_tokens = 0
self._interval_distribution = {k: 0 for k in range(self.mtp_k + 1)}
def _log(self) -> None:
ts = self.total_steps
if ts == 0:
return
# Interval stats
iv_steps = sum(self._interval_distribution.values())
if iv_steps == 0:
self._reset_interval()
return
iv_accepted = sum(k * v for k, v in self._interval_distribution.items())
iv_rate = (
iv_accepted / self._interval_draft_tokens
if self._interval_draft_tokens > 0
else 0.0
)
logger.info(
f"[MTP Stats Interval] Average toks/fwd: {1 + iv_accepted / iv_steps:.2f}, "
f"Accepted/Total Draft tokens: {iv_accepted}/{self._interval_draft_tokens}, "
f"Acceptance rate: {iv_rate:.2%}, "
f"Accepted tokens distribution: { {k: f'{v / iv_steps:.2%}' for k, v in self._interval_distribution.items()} }"
)
logger.info(
f"[MTP Stats ] Average toks/fwd: {1 + self.total_accepted / ts:.2f}, "
f"Accepted/Total Draft tokens: {self.total_accepted}/{self.total_draft_tokens}, "
f"Acceptance rate: {self.acceptance_rate:.2%}, "
f"Accepted tokens distribution: { {k: f'{v / ts:.2%}' for k, v in self.distribution.items()} }"
)
class CacheStats:
"""Tracks prefix caching hit statistics."""
__slots__ = (
"_log_interval",
"total_requests",
"total_cached_tokens",
"total_full_tokens",
"_interval_requests",
"_interval_cached_tokens",
"_interval_full_tokens",
)
def __init__(self, log_interval: int = 100):
self._log_interval = log_interval
self.total_requests: int = 0
self.total_cached_tokens: int = 0
self.total_full_tokens: int = 0
self._interval_requests: int = 0
self._interval_cached_tokens: int = 0
self._interval_full_tokens: int = 0
def update(self, num_cached_tokens: int, num_full_tokens: int) -> None:
"""Record cache stats for one prefill sequence."""
self.total_requests += 1
self.total_cached_tokens += num_cached_tokens
self.total_full_tokens += num_full_tokens
self._interval_requests += 1
self._interval_cached_tokens += num_cached_tokens
self._interval_full_tokens += num_full_tokens
if self.total_requests % self._log_interval == 0:
self._log()
self._reset_interval()
@property
def hit_rate(self) -> float:
if self.total_full_tokens == 0:
return 0.0
return self.total_cached_tokens / self.total_full_tokens
def _reset_interval(self) -> None:
self._interval_requests = 0
self._interval_cached_tokens = 0
self._interval_full_tokens = 0
def _log(self) -> None:
iv_rate = (
self._interval_cached_tokens / self._interval_full_tokens
if self._interval_full_tokens > 0
else 0.0
)
logger.info(
f"[Cache Stats Interval] Reqs: {self._interval_requests}, "
f"Cached/Total tokens: {self._interval_cached_tokens}/{self._interval_full_tokens}, "
f"Hit rate: {iv_rate:.2%}"
)
logger.info(
f"[Cache Stats ] Reqs: {self.total_requests}, "
f"Cached/Total tokens: {self.total_cached_tokens}/{self.total_full_tokens}, "
f"Hit rate: {self.hit_rate:.2%}"
)
class ScheduledBatch:
"""Immutable snapshot of sequences selected for a single forward pass.
Holds per-sequence metadata (block tables, context lengths, temperatures)
and the flattened token array ready for the model runner.
Args:
seqs: Mapping from request ID to :class:`Sequence`.
num_scheduled_tokens: Number of new tokens per sequence.
total_tokens_num: Sum of all scheduled tokens (prefill + decode).
connector_meta_output: Optional KV connector metadata for this batch.
num_spec_step: Number of speculative decode steps (0 = disabled).
scheduled_spec_decode_tokens: Draft token IDs per request for
speculative decoding (must not use a mutable default).
"""
def __init__(
self,
seqs: dict[int, Sequence],
num_scheduled_tokens: list[int],
total_tokens_num: int,
total_tokens_num_prefill: int = 0,
total_tokens_num_decode: int = 0,
total_seqs_num: int = 0,
total_seqs_num_prefill: int = 0,
total_seqs_num_decode: int = 0,
connector_meta_output=None,
is_dummy_run: bool = False,
num_spec_step: int = 0,
scheduled_spec_decode_tokens: dict[int, np.ndarray] | None = None,
remote_kv_block_ids: list[int] | None = None,
remote_kv_seq_blocks: dict[int, list[int]] | None = None,
num_cached_tokens: list[int] | None = None,
):
if scheduled_spec_decode_tokens is None:
scheduled_spec_decode_tokens = {}
self.remote_kv_block_ids = remote_kv_block_ids or []
self.remote_kv_seq_blocks = remote_kv_seq_blocks or {}
self.req_ids = list(seqs.keys())
self.num_scheduled_tokens = np.asarray(num_scheduled_tokens, dtype=np.int32)
self.temperatures = np.asarray(
[seq.temperature for seq in seqs.values()], dtype=np.float32
)
self.return_logprobs = [seq.return_logprobs for seq in seqs.values()]
self.context_lens = np.asarray(
[seq.num_tokens for seq in seqs.values()], dtype=np.int32
)
self.num_rejected = np.asarray(
[seq.num_rejected for seq in seqs.values()], dtype=np.int32
)
self.num_bonus = np.asarray(
[seq.num_bonus_tokens for seq in seqs.values()], dtype=np.int32
)
self.per_req_cache_groups = [
seq.per_req_cache_group
for seq in seqs.values()
if seq.has_per_req_cache and seq.per_req_cache_group >= 0
]
self.top_ks = np.asarray([seq.top_k for seq in seqs.values()], dtype=np.int32)
self.top_ps = np.asarray([seq.top_p for seq in seqs.values()], dtype=np.float32)
# True if any seq in the batch is a fan-out child (SamplingParams.n>1)
# and therefore requires fresh per-row random noise at the sampler
# rather than the cached shared exponential tensor.
self.needs_independent_noise = np.asarray(
[getattr(seq, "needs_independent_noise", False) for seq in seqs.values()],
dtype=bool,
)
self.is_first_decode_without_local_prefill = [
seq.is_first_decode for seq in seqs.values()
]
self.mrope_positions_by_req = {
seq.id: seq.mrope_positions
for seq in seqs.values()
if getattr(seq, "mrope_positions", None) is not None
}
self.mrope_position_deltas = {
seq.id: getattr(seq, "mrope_position_delta", 0)
for seq in seqs.values()
if getattr(seq, "mrope_positions", None) is not None
}
self.has_mrope = bool(self.mrope_positions_by_req)
# num_cached_tokens for chunked prefill support
self.num_cached_tokens = (
num_cached_tokens
if num_cached_tokens is not None
else [seq.num_cached_tokens for seq in seqs.values()]
)
# context_lens: for prefill seqs, use num_cached_tokens + num_scheduled_tokens
self.context_lens = np.asarray(
[
(
self.num_cached_tokens[i] + num_scheduled_tokens[i]
if seq.type == SequenceType.PREFILL
else seq.num_tokens
)
for i, seq in enumerate(seqs.values())
],
dtype=np.int32,
)
# Compute token offsets: prefill uses num_cached_tokens, decode uses existing formula
self.scheduled_tokens = np.empty(total_tokens_num, dtype=np.int32)
pos = 0
for i, (seq, num) in enumerate(zip(seqs.values(), num_scheduled_tokens)):
if seq.type == SequenceType.PREFILL:
offset = self.num_cached_tokens[i]
else:
offset = seq.num_tokens - self.num_rejected[i] - num
self.scheduled_tokens[pos : pos + num] = seq.token_ids[
offset : offset + num
]
pos += num
if num_spec_step > 0 and scheduled_spec_decode_tokens is not None:
self.scheduled_spec_decode_tokens = np.asarray(
list(scheduled_spec_decode_tokens.values()), dtype=np.int32
)
self.block_tables = [
seq.block_table for seq in seqs.values() if seq.block_table
]
self.last_block_num_tokens = [
_seq.last_block_num_tokens for _seq in seqs.values()
]
# Total number of tokens scheduled for all requests.
self.total_tokens_num = total_tokens_num
self.total_tokens_num_prefill = total_tokens_num_prefill
self.total_tokens_num_decode = total_tokens_num_decode
# Total number of reqs scheduled for all requests.
self.total_seqs_num = total_seqs_num
self.total_seqs_num_prefill = total_seqs_num_prefill
self.total_seqs_num_decode = total_seqs_num_decode
self.connector_meta_output = connector_meta_output
self.finished_recving_kv_req_ids: list[int] = []
self.is_dummy_run = is_dummy_run
self.num_spec_step = num_spec_step
# Collect multimodal data from prefill sequences
self.multimodal_data = {}
for seq in seqs.values():
if getattr(seq, "multimodal_data", None) is not None:
self.multimodal_data[seq.id] = seq.multimodal_data
# Clear after first use to avoid re-sending on decode steps
seq.multimodal_data = None
self.external_request_ids = [seq.external_request_id for seq in seqs.values()]
# logger.info(f"{[el for el in scheduled_spec_decode_tokens.keys()]=}")
# logger.info(f"{self.num_scheduled_tokens=}")
# logger.info(f"{self.context_lens=}")
# logger.info(f"{[len(blk)*16 for blk in self.block_tables]=}")
# logger.info(f"{self.block_tables=}")
class ScheduledBatchOutput:
"""Token-level results from a single forward pass.
Attributes:
token_ids: Mapping of request ID -> accepted token IDs.
draft_token_ids: Speculative draft tokens (one row per request).
num_rejected: Per-request count of rejected speculative tokens.
num_bonus: Per-request count of bonus accepted tokens.
is_deferred_out: Whether output was deferred from a previous step.
"""
def __init__(
self,
req_ids: list[int],
token_ids: list[tuple[int, ...]],
num_rejected: Optional[np.ndarray],
num_bonus: Optional[np.ndarray],
draft_token_ids: Optional[np.ndarray],
is_deferred_out: bool = False,
is_prev_prefill=False,
logprobs=None,
):
self.req_ids = req_ids
self.token_ids = token_ids
self.draft_token_ids = draft_token_ids
self.num_rejected = num_rejected
self.num_bonus = num_bonus
self.is_deferred_out = is_deferred_out
self.is_prev_prefill = is_prev_prefill
self.logprobs = logprobs # Optional[dict[int, float]]
# O(1) lookup: req_id -> index (lazy-built on first access)
self._req_id_to_idx: Optional[dict[int, int]] = None
def get_idx(self, req_id: int) -> Optional[int]:
"""O(1) lookup of request index by id."""
if self._req_id_to_idx is None:
self._req_id_to_idx = {rid: i for i, rid in enumerate(self.req_ids)}
return self._req_id_to_idx.get(req_id)
class Scheduler:
"""Manages the lifecycle of inference requests through prefill and decode.
The scheduler maintains two primary queues:
- **waiting**: Newly arrived requests pending their first prefill.
- **running**: Active requests that have completed prefill and are
being decoded token-by-token.
On each :meth:`schedule` call it selects a batch of sequences that
fit within the token and sequence budget, allocates KV cache blocks
via :class:`BlockManager`, and returns a :class:`ScheduledBatch`.
Integration with the KV disaggregation connector is handled through
:meth:`_update_waiting_for_remote_kv` (decode side) and
:meth:`_update_from_kv_xfer_finished` (both sides).
"""
def __init__(self, config: Config):
self.max_num_seqs = config.max_num_seqs
self.max_num_batched_tokens = config.max_num_batched_tokens
self.max_model_len = config.max_model_len
self.bos_token_id = config.bos_token_id
self.eos_token_id = config.eos_token_id
self.stop_token_ids = config.stop_token_ids
self.block_manager = BlockManager(config)
self.waiting: deque[Sequence] = deque()
self.running: deque[Sequence] = deque()
self.config = config
# Admit-rejected seqs (those `_unschedulable_reason` flags). Drained
# by `take_rejected` each EngineCore step; routed through the same
# output_queue path as forward-finished seqs.
self._rejected: list[Sequence] = []
# KV transfer bookkeeping
self.finished_recving_kv_req_ids: list[int] = []
self.deferred_free_blocks: dict[int, Sequence] = {}
# Scheduling delay for batching efficiency
self.prev_time = 0.0
# Did we schedule a prompt at previous step?
self.prev_prompt = False
# Latency of the last prompt step
self.last_prompt_latency = 0.0
self.delay_factor = config.scheduler_delay_factor
# Speculative decoding
self.use_spec = config.speculative_config is not None
self.mtp_k: int = (
config.speculative_config.num_speculative_tokens if self.use_spec else 0
) # type: ignore
self.spec_stats: Optional[SpecStats] = (
SpecStats(mtp_k=self.mtp_k) if self.use_spec else None
)
self.cache_stats: Optional[CacheStats] = (
CacheStats() if config.enable_prefix_caching else None
)
self.enable_chunked_prefill = config.enable_chunked_prefill
# Number of running seqs currently mid-prefill (per-seq state lives in
# `Sequence.is_partial_prefill`). Maintained as a counter so Phase 1
# of `schedule()` can skip the running-queue scan entirely on
# pure-decode steps (the common case).
self._partial_prefill_count: int = 0
from atom.utils.forward_context import get_kvconnector
self.kv_connector = get_kvconnector("scheduler", config)
from atom.distributed.kv_events import (
EventPublisher as _EventPublisher,
make_publisher as _make_publisher,
)
kv_events_cfg = getattr(config, "kv_events_config", None)
parallel_cfg = getattr(config, "parallel_config", None)
dp_rank = (
getattr(parallel_cfg, "data_parallel_rank", None)
if parallel_cfg is not None
else None
)
if kv_events_cfg is not None and kv_events_cfg.enable:
self.kv_event_publisher: _EventPublisher = _make_publisher(
enabled=True,
publisher_kind=kv_events_cfg.publisher,
endpoint=kv_events_cfg.endpoint,
topic=kv_events_cfg.topic,
hwm=kv_events_cfg.hwm,
buffer_steps=kv_events_cfg.buffer_steps,
data_parallel_rank=dp_rank,
)
logger.info(
"KV event publisher enabled: kind=%s endpoint=%s dp_rank=%s",
kv_events_cfg.publisher,
kv_events_cfg.endpoint,
dp_rank,
)
else:
self.kv_event_publisher = _make_publisher(
enabled=False,
publisher_kind="null",
endpoint="",
)
# Cross-DP prefill alignment. Set by DPEngineCoreProc after
# dp_group is available. See `prefill_delayer.py` for rationale.
from atom.model_engine.prefill_delayer import PrefillDelayer
self.prefill_delayer: Optional[PrefillDelayer] = None
def set_prefill_delayer(self, delayer) -> None:
self.prefill_delayer = delayer
def _count_admittable_head_prefills(self, limit: int) -> int:
"""Count how many head prefills this rank can admit this tick.
Just having `self.waiting` non-empty is too coarse — during a
concurrent-burst workload (e.g. 1k/1k @ high concurrency) every
DP rank has a full waiting queue, so `bool(self.waiting)` is
ALWAYS True on all ranks → status="all" → delayer never engages.
But only the 1-2 ranks with free KV blocks actually admit a
prefill that tick; the other 6-7 ranks decode. That's the real
"mixed" we need to delay.
We peek the front of `waiting` (skipping a few unschedulable
entries) and check `can_allocate` + token-budget, mirroring the
same checks the admission while-loop runs below. The count is capped
at ``limit`` so the helper stays cheap for the delayer gate.
"""
if limit <= 0 or not self.waiting:
return 0
count = 0
num_batched_tokens = 0
for i, seq in enumerate(self.waiting):
if i >= 4:
break
if self._unschedulable_reason(seq) is not None:
continue
if seq.status == SequenceStatus.WAITING_FOR_REMOTE_KVS:
continue
num_new_tokens = seq.num_tokens - seq.num_cached_tokens
if num_new_tokens > self.max_num_batched_tokens:
continue
if self.block_manager.can_allocate(seq) < 0:
break # KV-pressured: definitely cannot prefill more now.
if num_batched_tokens + num_new_tokens > self.max_num_batched_tokens:
break
count += 1
if count >= limit:
break
num_batched_tokens += num_new_tokens
return count
def _prefill_delayer_readiness(self) -> tuple[bool, bool]:
"""Return the local presence and alignment bits for PrefillDelayer.
TBO prefill splitting needs at least two local prefill requests.
When TBO is enabled, wait for each DP rank to be able to admit two
requests before reporting "ready"; otherwise keep the legacy one
request threshold.
"""
required = 2 if self.config.enable_tbo else 1
count = self._count_admittable_head_prefills(required)
return count > 0, count >= required
def _kv_usage(self) -> float:
"""Fraction of KV-cache blocks currently in use ∈ [0, 1].
Used as the `token_usage` signal for PrefillDelayer's low-watermark
safety valve. Derived from BlockManager bookkeeping; cheap (no
traversal of seq tables).
"""
bm = self.block_manager
total = len(bm.blocks)
if total <= 0:
return 0.0
return len(bm.used_block_ids) / total
def publish_kv_events(self) -> None:
"""Drain BlockManager's event log and publish as one EventBatch. Called
by EngineCore at the end of each scheduler step. No-op when events are
disabled (NullEventPublisher swallows the publish call)."""
events = self.block_manager.take_events()
if events:
self.kv_event_publisher.publish(events)
def shutdown_kv_events(self) -> None:
"""Tear down the publisher background thread and ZMQ socket. Called
by EngineCore on engine shutdown."""
try:
self.kv_event_publisher.shutdown()
except Exception:
logger.exception("KV event publisher shutdown failed")
def is_finished(self):
# `_rejected` must be considered too: if a batch of seqs is all
# oversized, schedule() moves them straight from `waiting` to
# `_rejected`, leaving both `waiting` and `running` empty. Without
# this check, busy_loop's `is_finished()` short-circuits to True
# before EngineCore drains `_rejected` via take_rejected(), and
# llm.generate() blocks forever.
return not self.waiting and not self.running and not self._rejected
def add(self, seq: Sequence):
self._warn_if_unschedulable(seq)
self.waiting.append(seq)
def extend(self, seqs: list[Sequence]):
for seq in seqs:
self._warn_if_unschedulable(seq)
self.waiting.extend(seqs)
def _unschedulable_reason(self, seq: Sequence) -> Optional[str]:
"""Return a human-readable reason if `seq` is permanently unschedulable.
Only checks static (configuration-time) capacity. Dynamic conditions
that can clear up as other seqs finish (e.g. transiently full
per-req-cache pool) are NOT checked here — they're warned at submit
time (`_warn_if_unschedulable`) but not eligible for permanent drop
at schedule time, since the prefill loop's existing `can_allocate`
check will retry them later.
Permanent failure modes (each leaves the seq stuck in `waiting`
forever and would head-of-line block the prefill loop, which
`break`s on the first oversized seq):
- prompt longer than `max_model_len` → exceeds per-seq KV cache
geometry; attention backends size `block_tables` as
`max_model_len // block_size` cols and would crash with a
broadcast error at prepare-time. (Checked first since it's the
usual actionable cause.)
- prompt longer than `max_num_batched_tokens` AND chunked prefill
disabled → no single prefill forward can ever fit it (with chunked
prefill enabled, the prompt is split across steps and this is fine)
- prompt's KV blocks (+ per-req cache reservation) exceed the total
pool size → never fits even on a fully empty pool
Called at submit time (`_warn_if_unschedulable`, which logs the
reason and adds extra dynamic warnings) and at schedule time
(drops the seq before it reaches the attention backend).
"""
num_tokens = seq.num_tokens
if num_tokens > self.max_model_len:
return (
f"input tokens={num_tokens} > max_model_len={self.max_model_len}. "
f"Increase --max-model-len or shorten the prompt."
)
if not self.enable_chunked_prefill and num_tokens > self.max_num_batched_tokens:
return (
f"input tokens={num_tokens} > max_num_batched_tokens="
f"{self.max_num_batched_tokens}. Increase --max-num-batched-tokens, "
f"enable chunked prefill, or shorten the prompt."
)
bm = self.block_manager
total_blocks = len(bm.blocks)
if seq.num_blocks > total_blocks:
return (
f"needs {seq.num_blocks} KV blocks for {num_tokens} input tokens "
f"> total pool blocks={total_blocks}. Reduce prompt length or "
f"raise --gpu-memory-utilization. (Per-req state cache lives in "
f"its own pre-allocated tensor and does not consume pool blocks.)"
)
return None
def _warn_if_unschedulable(self, seq: Sequence) -> None:
"""Log a single warning at submit time for permanently-unschedulable
sequences. The seq still enters `waiting`; the prefill scheduler drops
it later (see `schedule`).
Also surfaces a dynamic configuration-time-only warning when the
model was started with zero per-req-cache slots (max_num_seqs=0) —
this is permanent if it holds at submit time, but is NOT eligible
for schedule-time drop (a future config change could create slots).
"""
reason = self._unschedulable_reason(seq)
if reason is not None:
logger.warning("Request %s will never be scheduled: %s", seq.id, reason)
return
bm = self.block_manager
# No slots ever allocated (max_num_seqs=0 effectively) AND no slots
# currently in use → seq with has_per_req_cache=True can never enter.
# We check the slot list length below; without the accounting dict we
# infer "no slots ever existed" from `num_per_req_cache_groups == 0`,
# exposed via the free list at init time (slot ids 0..N-1).
if seq.has_per_req_cache and len(bm.free_per_req_cache_groups) == 0:
# All slots are currently in-use OR no slots were ever created.
# The schedule loop handles "currently full" by waiting; only
# warn for the permanent "never created" case, identified by
# `num_per_req_cache_groups` being 0 in the config.
if getattr(self.config, "num_per_req_cache_groups", 0) == 0:
logger.warning(
"Request %s will never be scheduled: needs per-req cache "
"slot but no slots were allocated (max_num_seqs=0 for "
"this model type).",
seq.id,
)
def take_rejected(self) -> list[Sequence]:
"""Pop and return any seqs the prefill scheduler dropped because
`_unschedulable_reason` flagged them (oversized prompt, exhausted
pool, etc.). Caller (EngineCore) pushes them onto the same
output_queue as forward-finished seqs so `llm.generate()` returns
an output for them instead of blocking forever.
"""
if not self._rejected:
return []
out = self._rejected
self._rejected = []
return out
def schedule(self) -> tuple[ScheduledBatch, dict[int, Sequence]]:
"""Select the next batch of sequences for a forward pass.
Tries prefill first; if no new prefills are ready, falls back to
decoding already-running sequences.
"""
scheduled_seqs = {}
num_seqs_prefill = 0
num_batched_tokens = 0
skipped_waiting_requests: deque[Sequence] = deque()
num_scheduled_tokens: list[int] = []
scheduled_spec_decode_tokens: dict[int, np.ndarray] = {}
# ─── Cross-DP prefill alignment (PrefillDelayer) ───────────────
_delayer_allows_prefill = True
if self.prefill_delayer is not None:
_local_prefillable, _local_alignment_ready = (
self._prefill_delayer_readiness()
)
_delayer_allows_prefill = self.prefill_delayer.should_allow_prefill(
local_prefillable=_local_prefillable,
token_usage=self._kv_usage(),
local_alignment_ready=_local_alignment_ready,
)
if not self.running and not self.waiting:
return None
# ---- Phase 1: resume partial prefills from running ----
# Gated by `_delayer_allows_prefill` so cross-DP alignment still
# holds when one rank is mid-chunked-prefill: a delayer veto skips
# both Phase 1 and Phase 2 in lockstep. Inside that, skip the
# running-queue scan entirely when no seq is mid-prefill — the
# common steady-state decode case — using the counter maintained by
# postprocess / preempt / finished-removal.
if _delayer_allows_prefill and self._partial_prefill_count > 0:
for seq in self.running:
if num_seqs_prefill >= self.max_num_seqs:
break
if not seq.is_partial_prefill:
continue
remaining = seq.num_prompt_tokens - seq.num_cached_tokens
budget_remaining = self.max_num_batched_tokens - num_batched_tokens
chunk = min(remaining, budget_remaining)
if chunk <= 0:
break
num_batched_tokens += chunk
num_seqs_prefill += 1
seq.type = SequenceType.PREFILL
scheduled_seqs[seq.id] = seq
num_scheduled_tokens.append(chunk)
# ---- Phase 2: new requests from waiting ----
while (
_delayer_allows_prefill
and (self.delay_factor <= 0 or self._passed_delay(time.time()))
and self.waiting
and num_seqs_prefill < self.max_num_seqs
and num_batched_tokens < self.max_num_batched_tokens
):
seq = self.waiting.popleft()
# Drop seqs the static-capacity check at submit-time flagged as
# permanently unschedulable (oversized prompt, exhausted pool,
# etc.). They've already been warned; mark FINISHED + record the
# rejection reason and route them to `_rejected` so EngineCore
# surfaces them through the same output_queue as forward-finished
# seqs. Without this they'd reach the attention backend (where an
# oversized prompt crashes with a broadcast error) AND
# `llm.generate()` would block forever waiting for an output.
# Re-check here (not just at submit) since pool state may change.
unschedulable = self._unschedulable_reason(seq)
if unschedulable is not None:
seq.status = SequenceStatus.FINISHED
seq.leave_reason = f"unschedulable: {unschedulable}"
self._rejected.append(seq)
continue
# KV Transfer: skip request if still waiting for remote KVs
waiting_remote_to_waiting_ready = False
if seq.status == SequenceStatus.WAITING_FOR_REMOTE_KVS:
waiting_remote_to_waiting_ready = self._update_waiting_for_remote_kv(
seq
)
if waiting_remote_to_waiting_ready:
seq.status = SequenceStatus.WAITING
else:
skipped_waiting_requests.append(seq)
continue
need_to_remove_to_load_kv_async_queue = False
if self.kv_connector is not None and not waiting_remote_to_waiting_ready:
_ext_tokens, need_to_remove_to_load_kv_async_queue = (
self.kv_connector.get_num_new_matched_tokens(seq)
)
if waiting_remote_to_waiting_ready:
seq.status = SequenceStatus.RUNNING
seq.is_first_decode = True
first_token_id = (seq.kv_transfer_params or {}).get("first_token_id")
if first_token_id is not None:
seq.append_token(first_token_id)
seq._injected_t0 = first_token_id
if self.mtp_k > 0:
drafts = list(
(seq.kv_transfer_params or {}).get("draft_token_ids") or []
)[: self.mtp_k]
for d in drafts:
seq.append_token(int(d))
seq.spec_token_ids = np.asarray(drafts, dtype=np.int32)
logger.info(
"[PD-TRANSITION] seq %s: num_tokens=%d, "
"num_prompt=%d, blocks=%d, first_token=%s, "
"last_5_tids=%s",
seq.id,
seq.num_tokens,
seq.num_prompt_tokens,
len(seq.block_table),
first_token_id,
seq.token_ids[-5:],
)
self.running.append(seq)
continue
# Probe cache hits FIRST so budget check sees the real
# (post-prefix-cache) remaining token count. `can_allocate`
# excludes the last block from cache hits (prefill must forward
# at least one block to produce logits), so num_new_tokens ≥ 1
# is guaranteed.
num_cached_blocks = self.block_manager.can_allocate(seq)
if num_cached_blocks < 0:
self.waiting.appendleft(seq)
break
# Use num_tokens (not num_prompt_tokens) so preempted seqs re-forward
# their decoded tokens — preempt() frees their KV blocks but keeps
# the token_ids, so num_tokens > num_prompt_tokens and those tokens
# still need KV recomputed.
num_new_tokens = (
seq.num_tokens - num_cached_blocks * self.block_manager.block_size
)
budget_remaining = self.max_num_batched_tokens - num_batched_tokens
if self.enable_chunked_prefill:
chunk = min(num_new_tokens, budget_remaining)
else:
if num_new_tokens > budget_remaining and num_batched_tokens > 0:
self.waiting.appendleft(seq)
break
chunk = num_new_tokens
assert chunk > 0, (
f"chunk must be positive: {chunk=}, "
f"{num_new_tokens=}, {budget_remaining=}"
)
self.block_manager.allocate(seq, num_cached_blocks)
# Snapshot the genuine prefix-cache hit at admission. After this,
# num_cached_tokens is repurposed to track chunked-prefill progress
# (it grows to the full prompt length in postprocess), so it can't be
# used to report the cache hit. Set once per seq (Phase-2 admission
# only); Phase-1 resume doesn't recompute num_cached_blocks.
seq.prefix_cache_hit_tokens = (
num_cached_blocks * self.block_manager.block_size
)
if self.kv_connector is not None:
self.kv_connector.update_state_after_alloc(seq)
if need_to_remove_to_load_kv_async_queue:
skipped_waiting_requests.append(seq)
seq.status = SequenceStatus.WAITING_FOR_REMOTE_KVS
continue
if self.cache_stats:
self.cache_stats.update(seq.num_cached_tokens, seq.num_tokens)
num_batched_tokens += chunk
num_seqs_prefill += 1
seq.status = SequenceStatus.RUNNING
seq.type = SequenceType.PREFILL
self.running.append(seq)
scheduled_seqs[seq.id] = seq
num_scheduled_tokens.append(chunk)
if skipped_waiting_requests:
logger.debug(
"Re-adding %d skipped requests back to waiting queue.",
len(skipped_waiting_requests),
)
self.waiting.extend(skipped_waiting_requests)
total_tokens_num_prefill = sum(num_scheduled_tokens)
if num_seqs_prefill > 0:
num_cached_tokens_list = [
seq.num_cached_tokens for seq in scheduled_seqs.values()
]
cached_per_req = [s.num_cached_tokens for s in scheduled_seqs.values()]
logger.info(
f"Scheduled prefill batch: {num_seqs_prefill} reqs, "
f"{total_tokens_num_prefill} new tokens "
f"(cached: {cached_per_req}, new: {num_scheduled_tokens}), "
f"req_ids: {tuple(scheduled_seqs.keys())}"
)
self.prev_prompt = True
# lip: TODO for prefill/decode mixed batch
connector_meta_output = None
if self.kv_connector is not None:
connector_meta_output = self.kv_connector.build_connector_meta()
return (
ScheduledBatch(
seqs=scheduled_seqs,
num_scheduled_tokens=num_scheduled_tokens,
total_tokens_num=total_tokens_num_prefill,
total_tokens_num_prefill=total_tokens_num_prefill,
total_seqs_num=num_seqs_prefill,
total_seqs_num_prefill=num_seqs_prefill,
connector_meta_output=connector_meta_output,
num_cached_tokens=num_cached_tokens_list,
),
scheduled_seqs,
)
# --- Decode scheduling ---
num_seqs_decode = 0
num_decode_tokens = 0
tokens_per_decode_seq = self.mtp_k + 1
num_new_tokens = self.mtp_k + 1
remote_kv_blocks: set[int] = set()
remote_kv_seq_blocks: dict[int, list[int]] = {}
while self.running and num_seqs_decode < self.max_num_seqs:
if num_decode_tokens + tokens_per_decode_seq > self.max_num_batched_tokens:
break
seq = self.running.popleft()
while not self.block_manager.can_append(seq, num_new_tokens):
if self.running:
self.preempt(self.running.pop())
else:
self.preempt(seq)
break
else:
if seq.spec_token_ids.size > 0:
scheduled_spec_decode_tokens[seq.id] = seq.spec_token_ids
num_seqs_decode += 1
num_decode_tokens += num_new_tokens
# For PD first-decode: if T0 was injected, may_append is
# needed for the new position N. Without T0 injection,
# blocks were already allocated during prefill.
is_first = getattr(seq, "is_first_decode", False)
if is_first and seq.block_table:
remote_kv_blocks.update(seq.block_table)
remote_kv_seq_blocks[seq.id] = list(seq.block_table)
has_injected_t0 = (
is_first
and (seq.kv_transfer_params or {}).get("first_token_id") is not None
)
if not is_first or has_injected_t0:
self.block_manager.may_append(seq, num_new_tokens)
if is_first:
logger.info(
"[PD-FIRST-DECODE] seq %s: num_tokens=%d, "
"blocks=%d, injected_t0=%s, "
"last_block_num=%d, context_will_be=%d",
seq.id,
seq.num_tokens,
len(seq.block_table),
has_injected_t0,
seq.last_block_num_tokens,
seq.num_tokens,
)
scheduled_seqs[seq.id] = seq
seq.type = SequenceType.DECODE
num_scheduled_tokens.append(num_new_tokens)
seq.is_first_decode = False
total_tokens_num_decode = sum(num_scheduled_tokens)
if scheduled_seqs:
self.running.extendleft(reversed(scheduled_seqs.values()))
connector_meta_output = None
if self.kv_connector is not None:
connector_meta_output = self.kv_connector.build_connector_meta()
decode_batch = ScheduledBatch(
seqs=scheduled_seqs,
num_scheduled_tokens=num_scheduled_tokens,
total_tokens_num=total_tokens_num_decode,
total_tokens_num_decode=total_tokens_num_decode,
total_seqs_num=num_seqs_prefill + num_seqs_decode,
total_seqs_num_prefill=num_seqs_prefill,
total_seqs_num_decode=num_seqs_decode,
connector_meta_output=connector_meta_output,
num_spec_step=self.mtp_k,
scheduled_spec_decode_tokens=scheduled_spec_decode_tokens,