codekingpro commited on
Commit
3462044
·
verified ·
1 Parent(s): b7f0a8b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/__init__.cpython-311.pyc +0 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/candidate_generator.cpython-311.pyc +0 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/stopping_criteria.cpython-311.pyc +0 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/streamers.cpython-311.pyc +0 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/watermarking.cpython-311.pyc +0 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__init__.py +29 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/cache.cpython-311.pyc +0 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/cache_manager.cpython-311.pyc +0 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/cb_logits_processors.cpython-311.pyc +0 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/continuous_api.cpython-311.pyc +0 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/cache.py +704 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/cache_manager.py +533 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/cb_logits_processors.py +325 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/continuous_api.py +1387 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/input_outputs.py +821 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/offloading_manager.py +307 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/requests.py +361 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/scheduler.py +431 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/utils.py +217 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/__init__.cpython-311.pyc +0 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/accelerate.cpython-311.pyc +0 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/aqlm.cpython-311.pyc +0 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/awq.cpython-311.pyc +0 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/bitnet.cpython-311.pyc +0 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/bitsandbytes.cpython-311.pyc +0 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/deepspeed.cpython-311.pyc +0 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/eager_paged.cpython-311.pyc +0 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/eetq.cpython-311.pyc +0 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/executorch.cpython-311.pyc +0 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fbgemm_fp8.cpython-311.pyc +0 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/finegrained_fp8.cpython-311.pyc +0 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/flash_attention.cpython-311.pyc +0 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/flash_paged.cpython-311.pyc +0 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/flex_attention.cpython-311.pyc +0 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fouroversix.cpython-311.pyc +0 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fp_quant.cpython-311.pyc +0 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fsdp.cpython-311.pyc +0 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/ggml.cpython-311.pyc +0 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/higgs.cpython-311.pyc +0 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/hqq.cpython-311.pyc +0 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/hub_kernels.cpython-311.pyc +0 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/liger.cpython-311.pyc +0 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/metal_quantization.cpython-311.pyc +0 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/mistral.cpython-311.pyc +0 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/moe.cpython-311.pyc +0 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/mxfp4.cpython-311.pyc +0 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/neftune.cpython-311.pyc +0 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/npu_flash_attention.cpython-311.pyc +0 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/peft.cpython-311.pyc +0 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/quanto.cpython-311.pyc +0 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (5.04 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/candidate_generator.cpython-311.pyc ADDED
Binary file (76.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/stopping_criteria.cpython-311.pyc ADDED
Binary file (33.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/streamers.cpython-311.pyc ADDED
Binary file (16.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/__pycache__/watermarking.cpython-311.pyc ADDED
Binary file (29.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from .cache import PagedAttentionCache
15
+ from .continuous_api import ContinuousBatchingManager, ContinuousMixin
16
+ from .requests import RequestState, RequestStatus
17
+ from .scheduler import FIFOScheduler, PrefillFirstScheduler, Scheduler
18
+
19
+
20
+ __all__ = [
21
+ "ContinuousBatchingManager",
22
+ "ContinuousMixin",
23
+ "FIFOScheduler",
24
+ "PagedAttentionCache",
25
+ "PrefillFirstScheduler",
26
+ "RequestState",
27
+ "RequestStatus",
28
+ "Scheduler",
29
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/cache.cpython-311.pyc ADDED
Binary file (39 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/cache_manager.cpython-311.pyc ADDED
Binary file (31.7 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/cb_logits_processors.cpython-311.pyc ADDED
Binary file (21.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/__pycache__/continuous_api.cpython-311.pyc ADDED
Binary file (73.6 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/cache.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ from math import floor, gcd, sqrt
16
+ from typing import Any
17
+
18
+ import torch
19
+
20
+ from ...configuration_utils import PreTrainedConfig
21
+ from ...generation.configuration_utils import ContinuousBatchingConfig
22
+ from ...utils.generic import is_flash_attention_requested
23
+ from ...utils.metrics import attach_tracer, traced
24
+ from .cache_manager import BlockManager, CacheAllocator, FullAttentionCacheAllocator, SlidingAttentionCacheAllocator
25
+ from .requests import RequestState, RequestStatus, get_device_and_memory_breakdown, logger
26
+
27
+
28
+ def group_layers_by_attn_type(config: PreTrainedConfig) -> tuple[list[list[int]], list[str]]:
29
+ """
30
+ Group layers depending on the attention mix, according to VLLM's hybrid allocator rules:
31
+ - Layers in each group need to have the same type of attention
32
+ - All groups have the same number of layers
33
+
34
+ For a model with the following layer types: ["sliding", "full", "full", "sliding", "full", "full", "full", "full"]
35
+ We would get four groups: [0, 3], [1, 2], [4,5] and [6,7].
36
+ """
37
+ # If the config has no layer_type attribute, it means all layers are the same attention type
38
+ layer_types = getattr(config, "layer_types", None)
39
+ if layer_types is None:
40
+ attn_type = "sliding_attention" if getattr(config, "sliding_window", None) is not None else "full_attention"
41
+ layer_types = [attn_type for _ in range(config.num_hidden_layers)]
42
+
43
+ # We then count the number of layers of each type
44
+ layer_counts = {}
45
+ for i, layer_type in enumerate(layer_types):
46
+ layer_counts[layer_type] = layer_counts.get(layer_type, []) + [i]
47
+
48
+ # The size of all groups is the greatest common divisor of the number of layers of each type
49
+ group_size = gcd(*[len(indices) for indices in layer_counts.values()])
50
+
51
+ # We then group the layers by type
52
+ layer_groups = []
53
+ for layer_type, indices in layer_counts.items():
54
+ for i in range(0, len(indices), group_size):
55
+ layer_groups.append(indices[i : i + group_size])
56
+ # And note the layer types
57
+ group_types = [layer_types[lg[0]] for lg in layer_groups]
58
+ return layer_groups, group_types
59
+
60
+
61
+ @attach_tracer()
62
+ class PagedAttentionCache:
63
+ """
64
+ Manages the cache for a paged attention mechanism, inspired by VLLM's hybrid allocator. The cache relies on making
65
+ groups of layers to reduce the complexity of cache management and fragmentation.
66
+
67
+ The cache uses a three-level hierarchy:
68
+ - Pages: The smallest unit of cache, a page has a size of [num_heads, head_size], which is the space needed to
69
+ store the key or value states for one token and one layer. For a model with only full-attention layers, to store
70
+ the KV cache of one token, we need `2 * num_layers` pages: key and values each take `num_layers` pages.
71
+ Pages are grouped into blocks:
72
+ - Blocks: A block is a collection of `block_size` pages, serving as the allocation unit to reduce management
73
+ complexity and fragmentation. Cache is allocated and freed block by block, not page by page. One block is
74
+ allocated to one layer group, which only has one attention type, like full-attention or sliding-attention.
75
+ If all layers in the model have the same attention type, then all layers will be in the same group. There is
76
+ more than one group if and only if the model has a mixed attention types, like layers with full-attention and
77
+ layers with sliding-attention.
78
+ - Cache tensors: The physical supports for the cache. There are as many cache tensors as there are layer in a
79
+ layer group, and the shape of the cache tensor is `[num_blocks * block_size, num_heads, head_size]`.
80
+
81
+ Grouping layers into groups is useful because when we allocate one block to a group N, the block allocated is the
82
+ same for all layers in group N, equivalently it is allocated across all cache tensors. This allows us to
83
+ efficiently allocate and free blocks, and to efficiently read and write key and value states.
84
+
85
+ For instance, imagine we have 8 blocks of cache and a model with two layer groups: a full-attention group with 3
86
+ layers and a sliding-attention group with 3 layers. At creation time, the physical cache tensors look like this:
87
+
88
+ cache_tensor_0: □ □ □ □ □ □ □ □
89
+ cache_tensor_1: □ □ □ □ □ □ □ □
90
+ cache_tensor_2: □ □ □ □ □ □ □ □
91
+
92
+ where □ means the blocks is not allocated to any layer group yet. We have 3 cache tensors because there are
93
+ 3 layers per group.
94
+ We allocate 1 block to each group, after allocation, the cache tensors look like this:
95
+
96
+ cache_tensor_0: ✖ ◉ □ □ □ □ □ □
97
+ cache_tensor_1: ✖ ◉ □ □ □ □ □ □
98
+ cache_tensor_2: ✖ ◉ □ □ □ □ □ □
99
+
100
+ where ✖ means the block is allocated to the full-attention group, and ◉ means the block is allocated to the
101
+ sliding-attention group.
102
+ Now, if we continue to generate, and the sliding window has been reached, we only need to allocate a new block
103
+ for the full-attention group, and the cache tensors look like this:
104
+
105
+ cache_tensor_0: ✖ ◉ ✖ □ □ □ □ □
106
+ cache_tensor_1: ✖ ◉ ✖ □ □ □ □ □
107
+ cache_tensor_2: ✖ ◉ ✖ □ □ □ □ □
108
+
109
+ And after further generation, when we need a new block allocated:
110
+
111
+ cache_tensor_0: ✖ ◉ ✖ ✖ □ □ □ □
112
+ cache_tensor_1: ✖ ◉ ✖ ✖ □ □ □ □
113
+ cache_tensor_2: ✖ ◉ ✖ ✖ □ □ □ □
114
+
115
+ This would not have been possible if all layers were in the same group: we would have had to allocate a new block
116
+ for the sliding-attention group, although it is not needed.
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ config: PreTrainedConfig,
122
+ continuous_batching_config: ContinuousBatchingConfig,
123
+ device: torch.device | str,
124
+ dtype: torch.dtype = torch.float16,
125
+ tp_size: int | None = None,
126
+ ) -> None:
127
+ """Initialize a paged attention cache for efficient memory usage. Also turns in prefix sharing if the model has
128
+ only full attention layers.
129
+
130
+ Args:
131
+ config: Model configuration
132
+ continuous_batching_config: Continuous batching configuration containing cache parameters
133
+ device: Device for the cache tensors
134
+ dtype: Data type of the cache
135
+ tp_size: Tensor parallelism size
136
+ """
137
+ self.config = config
138
+ self.dtype = dtype
139
+ self.device = device
140
+
141
+ # Extract model dimensions
142
+ kv_heads = getattr(config, "num_key_value_heads", None)
143
+ self.num_key_value_heads: int = kv_heads if kv_heads is not None else config.num_attention_heads
144
+ head_dim = getattr(config, "head_dim", None)
145
+ self.head_dim: int = head_dim if head_dim is not None else config.hidden_size // config.num_attention_heads
146
+
147
+ # Extract cache dimensions. Default used to be 32, now it's 256 to be compatible with flash_with_kvcache.
148
+ self.block_size = continuous_batching_config.block_size
149
+ if self.block_size <= 0:
150
+ raise ValueError(f"Block size must be positive, but got {self.block_size}")
151
+
152
+ # Group layers depending on the attention mix
153
+ layer_groups, group_types = group_layers_by_attn_type(config)
154
+ group_size = len(layer_groups[0])
155
+ self.num_groups = len(layer_groups)
156
+
157
+ self.sliding_windows = {}
158
+ self.layer_index_to_group_indices = {}
159
+ for i, group in enumerate(layer_groups):
160
+ sliding_window = config.sliding_window if group_types[i] == "sliding_attention" else 1
161
+ for j, layer in enumerate(group):
162
+ self.layer_index_to_group_indices[layer] = (i, j)
163
+ self.sliding_windows[layer] = sliding_window
164
+
165
+ # Handle TP (or dont)
166
+ if tp_size is not None and tp_size > 1:
167
+ if self.num_key_value_heads % tp_size != 0:
168
+ raise ValueError(
169
+ f"Number of key value heads {self.num_key_value_heads} must be divisible by tensor parallel size {tp_size}."
170
+ )
171
+ # If the model is using tensor parallelism, we need to adjust the number of heads accordingly.
172
+ # self.num_key_value_heads //= tp_size # TODO: why is this commented out?
173
+
174
+ # Infer number of blocks and max batch tokens
175
+ page_size = self.head_dim * self.num_key_value_heads
176
+
177
+ if is_flash_attention_requested(self.config):
178
+ num_attention_masks = 0 # only used to compute the default memory footprint args
179
+ elif "sliding_attention" in group_types:
180
+ # TODO: when we generalize to allow for block-attn, we can use `num_attention_masks=sum(set(group_types))`
181
+ num_attention_masks = 2
182
+ else:
183
+ num_attention_masks = 1
184
+
185
+ # Peak activations coefficients (for number of blocks and number of batch tokens)
186
+ q_bytes_per_token = config.num_attention_heads * self.head_dim
187
+ lm_head_peak = (
188
+ 0, # number of blocks does not affect the LM head peak activation
189
+ config.hidden_size + 2 * config.vocab_size, # hidden states + logits
190
+ )
191
+ attention_peak = (
192
+ 2 * page_size, # old K and V, read from cache (in the worst case scenario: whole cache is read)
193
+ config.hidden_size + q_bytes_per_token + 2 * page_size, # hidden state + Q + new K and V
194
+ )
195
+
196
+ memory_handler = PagedAttentionMemoryHandler(
197
+ continuous_batching_config=continuous_batching_config,
198
+ page_size=page_size,
199
+ num_groups=self.num_groups,
200
+ group_size=group_size,
201
+ activation_peaks=[lm_head_peak, attention_peak],
202
+ num_attention_masks=num_attention_masks,
203
+ )
204
+
205
+ # If somehow the max memory percent is not yet resolved, resolve it conservatively
206
+ if continuous_batching_config.max_memory_percent is None:
207
+ continuous_batching_config.resolve_max_memory_percent(has_logit_processors=True)
208
+
209
+ num_blocks, max_batch_tokens = memory_handler.infer_num_blocks_and_max_batch_tokens(
210
+ num_blocks=continuous_batching_config.num_blocks,
211
+ max_batch_tokens=continuous_batching_config.max_batch_tokens,
212
+ max_memory_percent=continuous_batching_config.max_memory_percent,
213
+ cache_dtype=self.dtype,
214
+ )
215
+
216
+ # Add the inferred attributes to the class
217
+ self.num_blocks = num_blocks
218
+ self.max_batch_tokens = max_batch_tokens
219
+ self.num_pages = self.num_blocks * self.block_size
220
+ logger.info(
221
+ f"PagedAttentionCache initialized with {self.num_blocks = }, {self.block_size = }, {page_size = }, "
222
+ f"{self.max_batch_tokens = } {num_attention_masks = }"
223
+ )
224
+
225
+ # If max_blocks_per_request is not set, the default value is 16 max blocks. With default block size of 256, this
226
+ # means a max sequence length of 4096 tokens for the fast decode path.
227
+ max_blocks_per_request = continuous_batching_config.max_blocks_per_request
228
+ if max_blocks_per_request is None:
229
+ max_blocks_per_request = 0
230
+ # logger.info( TODO: uncomment when we have good defaults
231
+ # f"max_blocks_per_request was not set, using {max_blocks_per_request}. This means max sequence "
232
+ # f"length for the decode fast path is {max_blocks_per_request * self.block_size}."
233
+ # )
234
+ self.max_blocks_per_request = max_blocks_per_request
235
+
236
+ # Initialize the cache
237
+ self.key_cache: list[torch.Tensor] = []
238
+ self.value_cache: list[torch.Tensor] = []
239
+ # We add two extra blocks to the cache as a padding zone that no BlockManager ever allocates from: one for the
240
+ # sentinel index (marks the spot of a new token in the read indices) and one for the trash index (for padding,
241
+ # block is never used so writes are silently discarded)
242
+ self.cache_shape = ((num_blocks + 2) * self.block_size, self.num_key_value_heads, self.head_dim)
243
+ self.sentinel_index = self.cache_shape[0] - 1
244
+ self.trash_index = self.sentinel_index - 1
245
+ for _ in range(group_size):
246
+ new_layer_key_cache = torch.empty(self.cache_shape, dtype=self.dtype, device=self.device)
247
+ new_layer_value_cache = torch.empty(self.cache_shape, dtype=self.dtype, device=self.device)
248
+ torch._dynamo.mark_static_address(new_layer_key_cache)
249
+ torch._dynamo.mark_static_address(new_layer_value_cache)
250
+ self.key_cache.append(new_layer_key_cache)
251
+ self.value_cache.append(new_layer_value_cache)
252
+ logger.info(f"{self.cache_shape = } {self.key_cache[0].shape = } {self.key_cache[0].numel() = }")
253
+
254
+ # Block management data structures
255
+ self.allow_block_sharing = continuous_batching_config.allow_block_sharing
256
+ self.group_cache_managers: list[CacheAllocator] = []
257
+ self.num_full_attention_groups = 0
258
+ self.num_sliding_attention_groups = 0
259
+ self.max_sliding_window_blocks_per_request = 0
260
+
261
+ for i, group_type in enumerate(group_types):
262
+ if group_type == "full_attention":
263
+ cm = FullAttentionCacheAllocator(i, self.block_size, allow_block_sharing=self.allow_block_sharing)
264
+ self.num_full_attention_groups += 1
265
+ elif group_type == "sliding_attention":
266
+ cm = SlidingAttentionCacheAllocator(
267
+ i, self.block_size, config.sliding_window, self.sentinel_index, self.trash_index
268
+ )
269
+ self.num_sliding_attention_groups += 1
270
+ self.max_sliding_window_blocks_per_request = cm._max_blocks_per_request
271
+ else:
272
+ raise ValueError(f"Invalid group type: {group_type}")
273
+ self.group_cache_managers.append(cm)
274
+
275
+ # We only use prefix sharing if the whole model has only full attention layers and block sharing is allowed
276
+ self.use_prefix_sharing = self.allow_block_sharing and group_types == ["full_attention"]
277
+ self._block_manager = BlockManager(num_blocks, self.block_size)
278
+ self._total_prefix_length: int = 0 # a counter to measure the impact of prefix sharing, also used in tests
279
+
280
+ # For block table support, we lazy init the name of the block table key
281
+ self._block_table_key = None
282
+
283
+ def will_allocation_be_successful(self, num_requested_blocks: int, allocated_blocks: int) -> bool:
284
+ """Returns a boolean indicating if the allocation of (num_requested_blocks) blocks will be successful. The
285
+ number of newly allocated blocks needed is predicted by the following rules:
286
+ - for full attention groups: since there is no sliding window for full attention layers, one requested block is
287
+ always equivalent to one newly allocated block for EACH full attention group
288
+ - for sliding window groups: because of the sliding window, the number of blocks allocated to a request is
289
+ capped. Using the number of already (allocated_blocks) we can compute the number of new blocks to actually
290
+ allocate to the request, which can be lower than the number of requested blocks. That number is the same for
291
+ all sliding window groups, as only one sliding window size is supported.
292
+ """
293
+ # This is not in a branch, because it is very rare to have zero full attention layer
294
+ needed_blocks = num_requested_blocks * self.num_full_attention_groups
295
+ # Only take this branch if the model has sliding window attention layers
296
+ if self.num_sliding_attention_groups:
297
+ blocks_left = max(self.max_sliding_window_blocks_per_request - allocated_blocks, 0)
298
+ needed_blocks += min(blocks_left, num_requested_blocks) * self.num_sliding_attention_groups
299
+ return needed_blocks <= self.get_num_free_blocks()
300
+
301
+ @traced
302
+ def allocate_blocks(self, n_blocks: int, request_id: str, allocated_blocks: int) -> int | None:
303
+ """Allocate cache blocks across all layer groups for a given request. Actual allocation is done by the cache
304
+ managers, and this method only returns the maximum number of blocks actually allocated across all managers."""
305
+ # First check allocation will be successful before starting, to avoid partial allocations
306
+ if not self.will_allocation_be_successful(n_blocks, allocated_blocks):
307
+ return None
308
+ # Allocate blocks across all cache managers
309
+ max_allocated = 0
310
+ for cm in self.group_cache_managers:
311
+ num_allocated_blocks = cm.allocate_blocks(n_blocks, request_id, self._block_manager)
312
+ if num_allocated_blocks is None:
313
+ raise ValueError(f"Failed to allocate {n_blocks} blocks for request {request_id}")
314
+ max_allocated = max(max_allocated, num_allocated_blocks)
315
+ return max_allocated
316
+
317
+ @traced
318
+ def free_blocks(self, request_id: str) -> None:
319
+ """Free all allocated cache blocks for a given request across all layer groups. Actual deallocation is done
320
+ by the cache managers."""
321
+ for cm in self.group_cache_managers:
322
+ cm.free_blocks(request_id, self._block_manager)
323
+
324
+ def get_num_free_blocks(self) -> int:
325
+ """Get the current number of unallocated blocks available for new requests."""
326
+ return self._block_manager.num_free_blocks
327
+
328
+ @traced
329
+ def extend_read_and_write_indices(
330
+ self,
331
+ request_id: str,
332
+ past_length: int,
333
+ query_length: int,
334
+ read_index: list[list[int]] | None,
335
+ write_index: list[list[int]],
336
+ ) -> None:
337
+ """Retrieve physical cache indices for reading KV states in the cache across all layer groups. This method
338
+ coordinates with all cache managers to build the complete set of read indices needed for attention computation.
339
+ When read_index is None, the batch has no cache reads and we only compute the write indices.
340
+ """
341
+ # Write indices are always computed
342
+ for cm, write_indices in zip(self.group_cache_managers, write_index):
343
+ write_indices.extend(cm.get_write_indices(request_id, past_length, query_length))
344
+ # Read indices are only computed if there are cache indices
345
+ if read_index is not None:
346
+ for cm, read_indices in zip(self.group_cache_managers, read_index):
347
+ read_indices.extend(cm.get_read_indices(request_id, past_length, query_length))
348
+
349
+ def fill_block_table(
350
+ self, request_id: str, past_length: int, query_length: int, block_table: torch.Tensor
351
+ ) -> None:
352
+ for i, cm in enumerate(self.group_cache_managers):
353
+ cm.fill_block_table(request_id, past_length, query_length, block_table[i])
354
+
355
+ @traced
356
+ def get_seqlens_k(self, past_length: int, query_length: int) -> dict[str, int]:
357
+ """Retrieve the key sequence length for the given request_id across all layer types. Returns a dictionary of
358
+ layer types to their corresponding key sequence lengths."""
359
+ seqlens_k = {}
360
+ if self.num_full_attention_groups > 0:
361
+ seqlens_k["full_attention"] = past_length + query_length
362
+ if self.num_sliding_attention_groups > 0:
363
+ seqlens_k["sliding_attention"] = query_length + min(past_length, self.config.sliding_window - 1)
364
+ # NOTE: when we add more attention types / different sliding windows, we can go back to looping over CMs
365
+ return seqlens_k
366
+
367
+ @traced
368
+ def update(
369
+ self,
370
+ key_states: torch.Tensor, # shape [1, num_kv_heads, seqlen_kv, head_dim]
371
+ value_states: torch.Tensor, # shape [1, num_kv_heads, seqlen_kv, head_dim]
372
+ layer_idx: int,
373
+ read_index: list[torch.Tensor], # shape [num_layer_groups, seqlen_kv + past_length]
374
+ write_index: list[torch.Tensor], # shape [num_layer_groups, seqlen_q]
375
+ ) -> tuple[torch.Tensor, torch.Tensor]: # shape [seqlen_kv + past_length, num_kv_heads, head_dim]
376
+ """Update the cache with new key-value states for a specific layer, and retrieves the relevant KV states from
377
+ the cache for attention computation. The behavior differs based on the layer's attention type:
378
+
379
+ - Full attention: New KV states are written to cache, then complete sequence is read from cache
380
+ - Sliding window: Old KV is read from cache along with extra spaces for the new KV, then new KV is written to
381
+ cache. This is because new KV might overwrite the old KV, so we need to read the old KV first.
382
+
383
+ When the layer's read index is empty, the batch has no cache reads (all requests are non-chunked prefills): we
384
+ only write to the cache and return the input KV states directly, skipping the index_select read-back.
385
+
386
+ Returns the complete KV states (cached + new) for attention computation.
387
+ """
388
+ # Retrieve the layer write index and the relevant cache tensors
389
+ group_idx, layer_idx_in_group = self.layer_index_to_group_indices[layer_idx]
390
+ layer_read_index = read_index[group_idx]
391
+ layer_write_index = write_index[group_idx]
392
+ k_cache = self.key_cache[layer_idx_in_group]
393
+ v_cache = self.value_cache[layer_idx_in_group]
394
+ # Transpose the key and value states to match the cache shape, after which shape is [seqlen_kv, num_kv_heads, head_dim]
395
+ key_states = key_states.transpose(1, 2).squeeze(0)
396
+ value_states = value_states.transpose(1, 2).squeeze(0)
397
+
398
+ # Case: write-only, no cache read. The input KV states already contain everything the attention needs.
399
+ if layer_read_index.numel() == 0:
400
+ k_cache.index_copy_(0, layer_write_index, key_states)
401
+ v_cache.index_copy_(0, layer_write_index, value_states)
402
+ return key_states, value_states
403
+
404
+ # Case: full attention
405
+ sliding_window = self.sliding_windows[layer_idx]
406
+ if sliding_window == 1:
407
+ k_cache.index_copy_(0, layer_write_index, key_states)
408
+ v_cache.index_copy_(0, layer_write_index, value_states)
409
+ key_states_with_cache = torch.index_select(k_cache, 0, layer_read_index)
410
+ value_states_with_cache = torch.index_select(v_cache, 0, layer_read_index)
411
+
412
+ # Case: sliding window -- we need to be careful of read/write order because of chunked prefill, because it's
413
+ # the only case where you may write over cache you need to use
414
+ else:
415
+ # Sentinel positions in read_index mark new-token slots; index_select reads garbage there,
416
+ # then masked_scatter_ overwrites them with the actual new key/value states.
417
+ mask = (layer_read_index == self.sentinel_index).unsqueeze(-1).unsqueeze(-1)
418
+ key_states_with_cache = torch.index_select(k_cache, 0, layer_read_index)
419
+ key_states_with_cache.masked_scatter_(mask, key_states)
420
+ value_states_with_cache = torch.index_select(v_cache, 0, layer_read_index)
421
+ value_states_with_cache.masked_scatter_(mask, value_states)
422
+ # Write new KV values to the cache (padding slots in write_index point to the trash position)
423
+ k_cache.index_copy_(0, layer_write_index, key_states)
424
+ v_cache.index_copy_(0, layer_write_index, value_states)
425
+
426
+ # Return the new KV values
427
+ return key_states_with_cache, value_states_with_cache
428
+
429
+ def get_block_table_key(self, flash_attn_with_kvcache_fn: Any) -> str:
430
+ """A function to get the name of the block table key for the given flash_attn_with_kvcache_fn. The function's
431
+ signature is only inspected once. This is necessary because different version of flash have different names for
432
+ the block table key."""
433
+ if self._block_table_key is None:
434
+ kwarg_names = inspect.signature(flash_attn_with_kvcache_fn).parameters.keys()
435
+ if "block_table" in kwarg_names:
436
+ self._block_table_key = "block_table"
437
+ elif "page_table" in kwarg_names:
438
+ self._block_table_key = "page_table"
439
+ else:
440
+ raise ValueError(
441
+ f"flash_attn_with_kvcache_fn does not have a block_table or page_table argument: {inspect.signature(flash_attn_with_kvcache_fn)}"
442
+ )
443
+ return self._block_table_key
444
+
445
+ def search_prefix_match(self, request_id: str, prompt_ids: list[int]) -> int:
446
+ """Searches for a prefix match in the cache for the given (prompts_ids). If one is found, we reference the
447
+ matching blocks in the (request_id), increase the reference count of the blocks and return the number of blocks
448
+ that match. If no prefix match is found, we return 0."""
449
+ current_hash = None
450
+ allocated_blocks = []
451
+ for b in range(len(prompt_ids) // self.block_size):
452
+ tokens = prompt_ids[b * self.block_size : (b + 1) * self.block_size]
453
+ # Prefix sharing is only supported when there is only one full attention layer group, so group_id=0.
454
+ current_hash = self._block_manager.compute_hash(current_hash, tokens, group_id=0)
455
+ block_id = self._block_manager._hash_to_id.get(current_hash)
456
+ if block_id is not None:
457
+ allocated_blocks.append(block_id)
458
+ self._block_manager.increase_ref_count(block_id)
459
+ else:
460
+ break
461
+ # If we found a matching prefix, we reference the blocks in the request
462
+ if allocated_blocks:
463
+ logger.debug(f"Found prefix match for request {request_id} with {len(allocated_blocks)} blocks")
464
+ cm = self.group_cache_managers[0]
465
+ cm.block_table[request_id] = allocated_blocks
466
+
467
+ prefix_length = len(allocated_blocks) * self.block_size
468
+ self._total_prefix_length += prefix_length
469
+ return prefix_length
470
+
471
+ def mark_shareable_blocks_as_complete(self, state: RequestState, num_complete_blocks: int) -> None:
472
+ """Marks the blocks allocated to a request (state) as complete if they are shareable and they have been computed
473
+ in the forward pass. A complete block is a block where the KV cache has been fully computed: if the block has
474
+ enough space to hold the cache for N tokens, the block is marked as complete when the cache data is present for
475
+ the N tokens. If block sharing is off, this is a no-op."""
476
+ # The status can be FINISHED in async mode, because batch N+1 offloaded the request before batch N was over. So
477
+ # we need to check for this case to avoid looking in the block table for blocks that no longer exist.
478
+ if num_complete_blocks == 0 or state.status == RequestStatus.FINISHED:
479
+ return None
480
+ for cm in self.group_cache_managers:
481
+ if cm.uses_block_sharing:
482
+ self._block_manager.mark_shareable_blocks_as_complete(
483
+ num_complete_blocks=num_complete_blocks,
484
+ allocated_blocks=cm.block_table[state.request_id],
485
+ prompt_ids=(state.initial_tokens + state.generated_tokens),
486
+ )
487
+
488
+ def copy_cache(self, list_source_blocks: list[int], list_forked_blocks: list[int]) -> None:
489
+ """Copy the cache from the source blocks to the forked blocks."""
490
+ source_blocks = torch.tensor(list_source_blocks, device=self.device, dtype=torch.int32)
491
+ forked_blocks = torch.tensor(list_forked_blocks, device=self.device, dtype=torch.int32)
492
+ for key_cache, value_cache in zip(self.key_cache, self.value_cache):
493
+ key_cache = key_cache.view(-1, self.block_size, self.num_key_value_heads, self.head_dim)
494
+ value_cache = value_cache.view(-1, self.block_size, self.num_key_value_heads, self.head_dim)
495
+ key_cache[forked_blocks] = key_cache[source_blocks]
496
+ value_cache[forked_blocks] = value_cache[source_blocks]
497
+ # FIXME: consolidate the cache into a single tensor of shape (group_size, 2, *self.k_or_v_cache_shape)
498
+ # This will allow for better .update and a single copy instead of one per cache tensor
499
+
500
+ def fork_request(self, source_request_id: str, destination_request_ids: list[str]) -> tuple[list[int], list[int]]:
501
+ """Fork the cache of a request (state) into the one of a list of requests with the given (dst_request_ids)."""
502
+ # These lists will be the accumulators for the source and destination blocks for the cache copy
503
+ source_blocks, destination_blocks = [], []
504
+ # Main fork loop
505
+ for cm in self.group_cache_managers:
506
+ src_blocks, dst_blocks = cm.fork_blocks(source_request_id, destination_request_ids, self._block_manager)
507
+ source_blocks.extend(src_blocks)
508
+ destination_blocks.extend(dst_blocks)
509
+ return source_blocks, destination_blocks
510
+
511
+ def free_all_requests(self) -> None:
512
+ """Free all blocks allocated to requests across all cache managers. This preserves prefix hashes in the block
513
+ manager (blocks become initialized rather than uninitialized if they were complete), allowing prefix sharing
514
+ to work across generation sessions."""
515
+ all_request_ids = set()
516
+ for cm in self.group_cache_managers:
517
+ all_request_ids.update(cm.block_table.keys())
518
+ for request_id in all_request_ids:
519
+ self.free_blocks(request_id)
520
+
521
+
522
+ # TODO: rework computation with the groups and their sizes
523
+ class PagedAttentionMemoryHandler:
524
+ """Determines the optimal number of pages (N) and max batch tokens (M) for the paged attention cache, given
525
+ available GPU memory. The relation between N and number of blocks is: num_blocks = N // block_size.
526
+
527
+ The memory footprint is a polynomial in N and M, where each term maps to a tensor allocated in
528
+ ``ContinuousBatchingIOs._setup_static_tensors`` or ``PagedAttentionCache.__init__``:
529
+
530
+ memory(N, M) = coeff_n · N + coeff_m · M + coeff_nm · N·M + coeff_mm · M²
531
+
532
+ See ``_equation_coefficients`` for the breakdown. All three solving modes (auto, fixed-N, fixed-M) reduce to
533
+ solving this equation, which is at most quadratic in one variable.
534
+ """
535
+
536
+ _activation_dtype = torch.bfloat16
537
+ _input_dtype = torch.int32
538
+ _upper_bound_max_batch_tokens = 1024
539
+ _upper_bound_num_blocks = 4096
540
+
541
+ def __init__(
542
+ self,
543
+ continuous_batching_config: ContinuousBatchingConfig,
544
+ page_size: int,
545
+ num_groups: int,
546
+ group_size: int,
547
+ activation_peaks: list[tuple[int, int]],
548
+ num_attention_masks: int,
549
+ ) -> None:
550
+ """Initialize the memory handler. `activation_peaks` is a list of `(Δcn, Δcm)` pairs giving the activation memory
551
+ contributions proportional to N (pages) and M (batch tokens) for each peak. Memory must satisfy the constraint
552
+ at every peak, so we solve each polynomial independently and take the most restrictive result."""
553
+ self.block_size = continuous_batching_config.block_size
554
+ self.page_size = page_size
555
+ self.num_groups = num_groups
556
+ self.group_size = group_size
557
+ self.activation_peaks = activation_peaks
558
+ self.num_attention_masks = num_attention_masks
559
+ self.max_blocks_per_request = continuous_batching_config.max_blocks_per_request
560
+ if self.max_blocks_per_request is None:
561
+ self.max_blocks_per_request = continuous_batching_config.fallback_max_blocks_per_request
562
+ # This is the number of output rows for the output_ids tensor
563
+ self.num_output_rows = 2 if continuous_batching_config.return_logprobs else 1
564
+ # This account for the set of 2 IOs if async batching is used
565
+ self.io_multiplier = 2 if continuous_batching_config.use_async_batching else 1
566
+
567
+ @staticmethod
568
+ def get_available_memory(max_memory_percent: float = 1.0) -> int:
569
+ """Calculate available GPU memory for cache allocation, accounting for already allocated tensors."""
570
+ _, total, reserved, allocated = get_device_and_memory_breakdown()
571
+ available_memory = total - max(allocated, reserved)
572
+ available_memory = int(available_memory * max_memory_percent)
573
+ return available_memory
574
+
575
+ # Formatting is disabled because of comment indentation, which improves readability.
576
+ # fmt: off
577
+ def _equation_coefficients(
578
+ self, peak: tuple[int, int], cache_dtype: torch.dtype
579
+ ) -> tuple[int, int, int, int]:
580
+ """Returns `(coeff_n, coeff_m, coeff_nm, coeff_mm)` for the memory polynomial of a single activation peak.
581
+ `peak = (Δcn, Δcm)` is the peak-specific activation contribution; the rest of the coefficients are shared
582
+ across peaks. Each addend is annotated with the tensor it corresponds to in
583
+ `ContinuousBatchingIOs._setup_static_tensors` (or the forward pass, for activation terms).
584
+ """
585
+ i = self._input_dtype.itemsize # int32
586
+ a = self._activation_dtype.itemsize # bfloat16
587
+ c = cache_dtype.itemsize
588
+ k = self.io_multiplier # 1 sync, 2 async (IO tensors only)
589
+ delta_n, delta_m = peak
590
+
591
+ # -- N terms: cost per cache page --------------------------------------------------
592
+ coeff_n = (
593
+ 2 * self.group_size * self.page_size * c # kv_cache: 2 * group_size * [N, page_size] * cache_dtype
594
+ + k * self.num_groups * 8 # read_index: [num_groups, N + M] (N part only, int64)
595
+ + delta_n * a # activation peak: N-proportional part
596
+ )
597
+ # -- M terms: cost per batch token -------------------------------------------------
598
+ coeff_m = (
599
+ delta_m * a # activation peak: M-proportional part
600
+ + k * 7 * i # bulk_input: [7, M] int32, packed as 7 rows
601
+ + k * self.num_output_rows * i # output_ids: [num_output_rows, M] int32
602
+ + k * self.num_groups # block_table: [bt_groups, M, max_blocks_per_req] int32
603
+ * self.max_blocks_per_request * i # (zero when fast-decode is off)
604
+ + k * self.num_groups * 8 # write_index: [num_groups, M] int64
605
+ + k * self.num_groups * 8 # read_index: [num_groups, N + M] (M part only, int64)
606
+ )
607
+ # -- N·M terms: cost per (page × batch token) --------------------------------------
608
+ coeff_nm = k * self.num_attention_masks * a # attention_mask: [1, 1, M, N + M] (N·M part only)
609
+ # -- M² terms: cost per (batch token squared) --------------------------------------
610
+ coeff_mm = k * self.num_attention_masks * a # attention_mask: [1, 1, M, N + M] (M² part only)
611
+
612
+ return coeff_n, coeff_m, coeff_nm, coeff_mm
613
+ # fmt: on
614
+
615
+ @staticmethod
616
+ def _solve_quadratic(a: float, b: float, c: float) -> float:
617
+ """Largest positive root of a·x² + b·x + c = 0. Falls back to linear when a == 0."""
618
+ if a == 0:
619
+ return -c / b
620
+ discriminant = b**2 - 4 * a * c
621
+ if discriminant < 0:
622
+ raise ValueError(f"No real solution (discriminant = {discriminant})")
623
+ root = (-b + sqrt(discriminant)) / (2 * a)
624
+ if root < 0:
625
+ raise ValueError(f"No positive solution (root = {root})")
626
+ return root
627
+
628
+ def _solve_for_peak(
629
+ self,
630
+ peak: tuple[int, int],
631
+ available: int,
632
+ num_blocks: int | None,
633
+ max_batch_tokens: int | None,
634
+ cache_dtype: torch.dtype,
635
+ ) -> tuple[int, int]:
636
+ """Solve for `(num_blocks, max_batch_tokens)` against one activation peak's memory polynomial. Clamps to upper
637
+ bounds. Either input may be None; whichever is None is solved for."""
638
+ cn, cm, cnm, cmm = self._equation_coefficients(peak, cache_dtype)
639
+
640
+ if num_blocks is None and max_batch_tokens is None:
641
+ # Substitute M = m·N → (coeff_nm·m + coeff_mm·m²)·N² + (coeff_n + coeff_m·m)·N − avail = 0
642
+ m = 0.01
643
+ num_pages = self._solve_quadratic(cnm * m + cmm * m**2, cn + cm * m, -available)
644
+ max_batch_tokens = int(num_pages * m)
645
+ if max_batch_tokens > self._upper_bound_max_batch_tokens:
646
+ max_batch_tokens = self._upper_bound_max_batch_tokens
647
+ # If max_batch_tokens is clamped, we recompute num_blocks below to get a higher value
648
+ num_blocks = None
649
+ else:
650
+ num_blocks = min(floor(num_pages) // self.block_size, self._upper_bound_num_blocks)
651
+
652
+ if num_blocks is None:
653
+ # M given → linear in N: (coeff_n + coeff_nm·M)·N = avail − coeff_m·M − coeff_mm·M²
654
+ M = max_batch_tokens
655
+ num_pages = floor((available - cm * M - cmm * M**2) / (cn + cnm * M))
656
+ num_blocks = min(num_pages // self.block_size, self._upper_bound_num_blocks)
657
+ elif max_batch_tokens is None:
658
+ # N given → quadratic in M: coeff_mm·M² + (coeff_m + coeff_nm·N)·M + (coeff_n·N − avail) = 0
659
+ N = num_blocks * self.block_size
660
+ M = self._solve_quadratic(cmm, cm + cnm * N, cn * N - available)
661
+ max_batch_tokens = min(floor(M), self._upper_bound_max_batch_tokens)
662
+
663
+ return num_blocks, max_batch_tokens
664
+
665
+ def infer_num_blocks_and_max_batch_tokens(
666
+ self,
667
+ num_blocks: int | None = None,
668
+ max_batch_tokens: int | None = None,
669
+ max_memory_percent: float = 0.9,
670
+ cache_dtype: torch.dtype = torch.float16,
671
+ ) -> tuple[int, int]:
672
+ """Solve for the missing variable(s) in the memory polynomial (see ``_equation_coefficients``). There is one
673
+ polynomial per activation peak; we solve each independently and take the most restrictive (smallest) result.
674
+ When both `N` and `M` are unknown, assumes `M = m·N` (m = 0.01, i.e. one batch fills ~1 % of the cache) and
675
+ solves the resulting quadratic in N.
676
+ """
677
+ available = self.get_available_memory(max_memory_percent)
678
+ logger.info(f"Cache memory: {available}")
679
+ # Solve each peak independently, then take the element-wise min (tightest constraint wins)
680
+ acc_num_blocks = float("inf")
681
+ acc_max_batch_tokens = float("inf")
682
+ for peak in self.activation_peaks:
683
+ n_blocks, m_batch_tokens = self._solve_for_peak(peak, available, num_blocks, max_batch_tokens, cache_dtype)
684
+ acc_num_blocks = min(acc_num_blocks, n_blocks)
685
+ acc_max_batch_tokens = min(acc_max_batch_tokens, m_batch_tokens)
686
+ # Now update the value (cannot update in loop, it would overwrite the user-passed values)
687
+ num_blocks, max_batch_tokens = acc_num_blocks, acc_max_batch_tokens
688
+ # Validate
689
+ memory_footprint = self.compute_memory_footprint(num_blocks, max_batch_tokens, cache_dtype)
690
+ if memory_footprint > available:
691
+ raise MemoryError(f"Memory footprint {memory_footprint} is more than available memory {available}")
692
+ return num_blocks, max_batch_tokens
693
+
694
+ def compute_memory_footprint(self, num_blocks: int, max_batch_tokens: int, cache_dtype: torch.dtype) -> int:
695
+ """Evaluate the memory polynomial at concrete (N, M) values, taking the max across activation peaks."""
696
+ N = num_blocks * self.block_size
697
+ M = max_batch_tokens
698
+
699
+ max_memory_footprint = 0
700
+ for peak in self.activation_peaks:
701
+ cn, cm, cnm, cmm = self._equation_coefficients(peak, cache_dtype)
702
+ memory_footprint = cn * N + cm * M + cnm * N * M + cmm * M * M
703
+ max_memory_footprint = max(max_memory_footprint, memory_footprint)
704
+ return max_memory_footprint
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/cache_manager.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from abc import ABC, abstractmethod
15
+ from collections import deque
16
+ from collections.abc import Iterator
17
+ from math import ceil
18
+ from typing import TypeVar
19
+
20
+ import torch
21
+
22
+ from .requests import logger
23
+
24
+
25
+ T = TypeVar("T")
26
+
27
+
28
+ def reverse_enumerate(xs: list[T]) -> Iterator[tuple[int, T]]:
29
+ index = len(xs) - 1
30
+ for x in xs[::-1]:
31
+ yield index, x
32
+ index -= 1
33
+
34
+
35
+ class Block: # TODO: rename to ShareableBlock and update the docs
36
+ """A class to represent a block managed by the block manager. We say that a block is complete when the physical KV
37
+ cache it points to is fully computed. A block can have a parent, which is the block that came before in the
38
+ sequence. Once a block is complete, it is given a hash, which takes into account the tokens ids of the block, the
39
+ layer (group_id) it belong to and its parent's hash (if there is a parent)."""
40
+
41
+ def __init__(self, id_: int, parent_id: int | None, group_id: int) -> None:
42
+ self.id: int = id_
43
+ self.parent_id: int | None = parent_id
44
+ self.group_id: int = group_id
45
+ self.hash: int | None = None
46
+ self.ref_count: int = 1
47
+
48
+ def __repr__(self) -> str:
49
+ return f"Block(id={self.id}, parent_id={self.parent_id}, group_id={self.group_id}, hash={self.hash}, ref_count={self.ref_count})"
50
+
51
+ @property
52
+ def is_complete(self) -> bool:
53
+ return self.hash is not None
54
+
55
+
56
+ class BlockManager:
57
+ """A class to manage the number of free blocks and block re-use. When a block becomes in use, a flag is passed to
58
+ determine if the block is shareable or not. If it is, then a Block object is created and kept track of internally.
59
+ It can have the following states:
60
+ - in use: one or more requests references this block, thus it cannot be written over. The number of requests
61
+ referencing this block is stored as ref_count in the Block object.
62
+ - un-initialized: the block points to a space in the KV cache tensor that contains no data yet. Those blocks can
63
+ be given as free blocks to new requests without any overhead.
64
+ - initialized: the block is complete and was used by one or more request that are finished. It contains KV cache
65
+ data and its hash is stored in the hash table. If a new request needs a block with the same hash, we increase
66
+ the ref_count of the block and remove it from the list of initialized blocks, because it is now in use.
67
+ Still, the block can be freed if no un-initialized blocks are left. In that case, we remove its hash from the
68
+ hash table.
69
+ If the block is not shareable, we just use the block manager as a FIFO structure where blocks are either free or in
70
+ use. Sharability is determined by the type of cache allocator: blocks created for full attention layers are
71
+ shareable, while blocks created for sliding window attention layers are not.
72
+ There is no structure to keep track of the blocks in use: if a block is neither un-initialized nor initialized,
73
+ it is in use.
74
+ """
75
+
76
+ def __init__(self, num_blocks: int, block_size: int) -> None:
77
+ """Initializes the block manager with a given number of blocks (num_blocks) of size (block_size)."""
78
+ self.num_blocks = num_blocks
79
+ self.block_size = block_size
80
+ self._uninit_block_ids = deque(range(num_blocks))
81
+ self._init_block_ids: dict[int, None] = {} # effectively act as an ordered set
82
+ self._hash_to_id: dict[int, int] = {}
83
+ self._id_to_block: dict[int, Block] = {}
84
+
85
+ @property
86
+ def num_free_blocks(self) -> int:
87
+ """Returns the number of free blocks left. Both initialized and uninitialized blocks are considered free."""
88
+ return len(self._uninit_block_ids) + len(self._init_block_ids)
89
+
90
+ def has_enough_free_blocks(self, n_blocks: int) -> bool:
91
+ """Checks if there are enough free blocks to allocate the requested number of blocks (n_blocks). If there are
92
+ not enough uninitialized blocks, we uninitialize the required number of initialized blocks."""
93
+ # Exit early if there are enough uninitialized blocks
94
+ if len(self._uninit_block_ids) >= n_blocks:
95
+ return True
96
+ # Exit early if even after uninitializing all initialized blocks, there are not enough free blocks
97
+ block_to_uninitialize = n_blocks - len(self._uninit_block_ids)
98
+ if len(self._init_block_ids) < block_to_uninitialize:
99
+ return False
100
+ # Uninitialize the required amount of blocks
101
+ for _ in range(block_to_uninitialize):
102
+ id_to_uninitialize = self._init_block_ids.popitem()[0]
103
+ block = self._id_to_block[id_to_uninitialize]
104
+ # Since the block is initialized it must have a hash, thus no need to check .hash is not None
105
+ self._hash_to_id.pop(block.hash) # ty:ignore[invalid-argument-type]
106
+ self._uninit_block_ids.append(id_to_uninitialize)
107
+ return True
108
+
109
+ def get_free_blocks(
110
+ self, n_blocks: int, last_block_id: int | None, shareable: bool, group_id: int
111
+ ) -> list[int] | None:
112
+ """Returns a list of (n_blocks) free block and mark them as no longuer free in the internal data structures.
113
+ If the (shareable) flag is set to True, a Block object is created to keep track of the block, with the
114
+ (last_block_id) to indicate the last block id in the sequence, also named the parent block. If the manager
115
+ cannot find enough free blocks, it returns None."""
116
+ if not self.has_enough_free_blocks(n_blocks):
117
+ return None
118
+ allocated_block_ids = [self._uninit_block_ids.popleft() for _ in range(n_blocks)]
119
+ # If the block is shareable, we keep track of the allocated blocks as partial blocks
120
+ if shareable:
121
+ for block_id in allocated_block_ids:
122
+ block = Block(block_id, last_block_id, group_id)
123
+ self._id_to_block[block_id] = block
124
+ last_block_id = block_id
125
+ # In both cases, we return the allocated block ids
126
+ return allocated_block_ids
127
+
128
+ def fork_blocks(
129
+ self, parent_blocks: list[int], num_forks: int, shareable: bool, group_id: int
130
+ ) -> tuple[list[list[int]] | None, list[int], list[int]]:
131
+ """Fork a given list of (parent_blocks) as many times as (num_forks). If the blocks are (shareable), we use
132
+ reference on the blocks that are complete. Otherwise, we allocate new blocks and keep track of their indices to
133
+ later copy the physical cache. For instance, when forking 4 blocks for 2 children:
134
+
135
+ Parent blocks: [0, 1, 2, 3], with all blocks being complete except the last one (block 3).
136
+
137
+ ----------------------------------------- IF BLOCKS ARE NOT SHAREABLE -----------------------------------------
138
+
139
+ Forked blocks lists: [[5, 6, 7, 8], [9, 10, 11, 12]]
140
+ Copy source: [0, 1, 2, 3, 0, 1, 2, 3]
141
+ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
142
+ Copy destination: [5, 6, 7, 8, 9, 10, 11, 12] → 8 blocks are newly allocated and copied
143
+
144
+ ----------------------------------------- IF BLOCKS ARE SHAREABLE ---------------------------------------------
145
+
146
+ Forked blocks lists: [[0, 1, 2, 5], [0, 1, 2, 6]]
147
+ Copy source: [ 3, 3] (block 3 is not complete so it's copied, not referenced)
148
+ ↓ ↓
149
+ Copy destination: [ 5, 6] → only 2 blocks are newly allocated and copied
150
+ """
151
+ # First phase: reference all complete blocks
152
+ forked_by_reference = []
153
+
154
+ if shareable:
155
+ for block_id in parent_blocks:
156
+ block = self._id_to_block[block_id]
157
+ if block.is_complete:
158
+ forked_by_reference.append(block.id)
159
+ block.ref_count += num_forks
160
+ else:
161
+ break
162
+
163
+ # Early return if we have forked all blocks by reference
164
+ blocks_to_copy = len(parent_blocks) - len(forked_by_reference)
165
+ if blocks_to_copy == 0:
166
+ return [forked_by_reference[:] for _ in range(num_forks)], [], []
167
+
168
+ # From now on, each child will have its own list of blocks
169
+ forked_blocks_lists = []
170
+ copy_src = []
171
+ copy_dst = []
172
+
173
+ # Second phase: allocate new blocks if needed
174
+ parent_id = forked_by_reference[-1] if forked_by_reference else None
175
+ for _ in range(num_forks):
176
+ allocated_block_ids = self.get_free_blocks(blocks_to_copy, parent_id, shareable, group_id)
177
+ if allocated_block_ids is None:
178
+ return None, [], []
179
+ forked_blocks_lists.append(forked_by_reference + allocated_block_ids)
180
+ copy_src.extend(parent_blocks[-blocks_to_copy:])
181
+ copy_dst.extend(allocated_block_ids)
182
+ return forked_blocks_lists, copy_src, copy_dst
183
+
184
+ def increase_ref_count(self, block_id: int) -> None:
185
+ """Increases the reference count of a given (block_id)."""
186
+ block = self._id_to_block[block_id]
187
+ block.ref_count += 1
188
+ if block.ref_count == 1:
189
+ self._init_block_ids.pop(block_id)
190
+
191
+ def decrease_ref_count(self, block_id: int) -> None:
192
+ """Decreases the reference count of a given (block_id). If the reference count reaches 0, the block is no longer
193
+ in use, and becomes initialized (if it was complete) or uninitialized (if it was incomplete)."""
194
+ block = self._id_to_block[block_id]
195
+ block.ref_count -= 1
196
+ if block.ref_count == 0:
197
+ if block.is_complete:
198
+ self._init_block_ids[block_id] = None
199
+ else:
200
+ self._id_to_block.pop(block_id)
201
+ self._uninit_block_ids.append(block_id)
202
+
203
+ def free_blocks(self, blocks: list[int], shareable: bool) -> None:
204
+ """Marks a list of (blocks) as free. If the blocks were not (shareable), we simply add them to the uninitialized
205
+ blocks queue. Otherwise, their new state depends on whether they are complete."""
206
+ if shareable:
207
+ for block_id in blocks:
208
+ self.decrease_ref_count(block_id)
209
+ else:
210
+ self._uninit_block_ids.extend(blocks)
211
+
212
+ def uninitialize_unshared_block(self, block_id: int) -> None:
213
+ """Marks a block as uninitialized. Raises an error if the block has more than one reference."""
214
+ # Make sure the block has only one reference and remove it from the block table
215
+ block = self._id_to_block.pop(block_id)
216
+ if block.ref_count > 1:
217
+ raise RuntimeError(f"Block {block_id} has more than one reference: {block.ref_count = }")
218
+ # Add the block to the uninitialized blocks queue
219
+ self._uninit_block_ids.append(block_id)
220
+
221
+ def mark_shareable_blocks_as_complete(
222
+ self, num_complete_blocks: int, allocated_blocks: list[int], prompt_ids: list[int]
223
+ ) -> None:
224
+ """Among the list of (allocated_blocks), mark (num_complete_blocks) incomplete blocks as now complete. The list
225
+ of (prompt_ids) is used to compute the hash of the new block."""
226
+ # Look for the first complete block, starting from the last block in the sequence
227
+ parent_hash = None
228
+ incomplete_blocks: list[tuple[int, Block]] = []
229
+ for i, block_id in reverse_enumerate(allocated_blocks):
230
+ block = self._id_to_block[block_id]
231
+ if block.is_complete:
232
+ parent_hash = block.hash
233
+ break
234
+ incomplete_blocks.append((i, block))
235
+
236
+ # Now go through the incomplete blocks and updated them
237
+ new_parent_id = None
238
+ while incomplete_blocks:
239
+ i, block = incomplete_blocks.pop()
240
+
241
+ # If the parent id has been updated, we apply the change
242
+ if new_parent_id is not None:
243
+ block.parent_id = new_parent_id
244
+ new_parent_id = None
245
+
246
+ # If we have set the hash for all complete blocks, we can stop
247
+ if num_complete_blocks == 0:
248
+ break
249
+
250
+ # Otherwise, we compute the hash
251
+ num_complete_blocks -= 1
252
+ tokens = prompt_ids[i * self.block_size : (i + 1) * self.block_size]
253
+ block.hash = self.compute_hash(parent_hash, tokens, block.group_id)
254
+
255
+ existing_block_id = self._hash_to_id.get(block.hash)
256
+ # If their was a different block with the same hash, we reference the existing block instead
257
+ if existing_block_id is not None:
258
+ if existing_block_id == block.id:
259
+ # This should not happen, but is not a problem in itself, so we just log a warning
260
+ logger.warning(f"Block {block.id} was marked as complete more than once")
261
+ else:
262
+ logger.debug(f"Found existing block {existing_block_id} for block {block.id}")
263
+ allocated_blocks[i] = existing_block_id
264
+ new_parent_id = existing_block_id
265
+ self.increase_ref_count(existing_block_id)
266
+ self.uninitialize_unshared_block(block.id)
267
+
268
+ # Otherwise, we add the completed block to the hash table
269
+ else:
270
+ logger.debug(f"Adding new block {block.id} (group {block.group_id}) with hash {block.hash}")
271
+ self._hash_to_id[block.hash] = block.id
272
+
273
+ # Update loop variables
274
+ parent_hash = block.hash
275
+
276
+ def compute_hash(self, parent_hash: int | None, tokens: list[int], group_id: int) -> int:
277
+ """Computes the hash of a block identified by the (tokens) it contains, its (parent_hash) and the layer
278
+ (group_id) it belong to. If the block has no parent, the parent hash is None."""
279
+ return hash((parent_hash, tuple(tokens), group_id))
280
+
281
+
282
+ class CacheAllocator(ABC):
283
+ """Abstract base class for cache managers. Cache managers keep track of per-request cache allocations, determine
284
+ when a new physical block needs to be allocated and compute physical indices for reading or writing to the cache."""
285
+
286
+ _index: int
287
+ block_table: dict[str, list[int]] # request_id -> list of block_ids allocated to the request
288
+ uses_block_sharing: bool # flag to determine if the blocks are shareable
289
+
290
+ @abstractmethod
291
+ def allocate_blocks(self, n_blocks: int, request_id: str, block_manager: BlockManager) -> int | None:
292
+ """Allocates (n_blocks) for a given (request_id) using the (block_manager). Returns the num of blocks allocated
293
+ if successful and None otherwise."""
294
+
295
+ def free_blocks(self, request_id: str, block_manager: BlockManager) -> None:
296
+ """Frees all blocks associated with a (request_id) using the (block_manager)."""
297
+ if request_id in self.block_table:
298
+ blocks_to_free = self.block_table.pop(request_id)
299
+ block_manager.free_blocks(blocks_to_free, shareable=self.uses_block_sharing)
300
+ else:
301
+ logger.warning(
302
+ f"CacheAllocator {self._index} attempted to free blocks for non-existent request_id: {request_id}"
303
+ )
304
+
305
+ @abstractmethod
306
+ def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
307
+ """Returns the physical indices of where to read request_id's cache in the cache tensor."""
308
+
309
+ @abstractmethod
310
+ def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
311
+ """Returns the physical indices of where to write request_id's cache in the cache tensor."""
312
+
313
+ @abstractmethod
314
+ def fill_block_table(
315
+ self, request_id: str, past_length: int, query_length: int, block_table: torch.Tensor
316
+ ) -> None:
317
+ """Fills the block table for a given request_id, past_length and query_length."""
318
+
319
+ def fork_blocks(
320
+ self, parent_request_id: str, children_request_ids: list[str], block_manager: BlockManager
321
+ ) -> tuple[list[int], list[int]]:
322
+ """Forks the cache blocks of a (parent_request_id) to a list of (children_request_ids). To manage the blocks,
323
+ the (block_manager) is used. When forking, the child's block are either shared with the parent, or they need to
324
+ be copied from the parent. Hence we return two lists of blocks that need to be copied: one for the source and
325
+ one for the destination."""
326
+
327
+ # Sanity checks
328
+ if parent_request_id not in self.block_table:
329
+ raise ValueError(f"No block table found for request {parent_request_id}")
330
+
331
+ # Actual forking
332
+ parent_blocks = self.block_table[parent_request_id]
333
+ list_forked_blocks, copy_src, copy_dst = block_manager.fork_blocks(
334
+ parent_blocks=parent_blocks,
335
+ num_forks=len(children_request_ids),
336
+ shareable=self.uses_block_sharing,
337
+ group_id=self._index,
338
+ )
339
+ if list_forked_blocks is None:
340
+ raise ValueError(f"Failed to fork blocks for request {parent_request_id}")
341
+
342
+ # Update the block table for all children requests
343
+ for children_request_id, forked_blocks in zip(children_request_ids, list_forked_blocks):
344
+ if children_request_id in self.block_table:
345
+ raise ValueError(f"Block table already exists for request {children_request_id}")
346
+ self.block_table[children_request_id] = forked_blocks
347
+ return copy_src, copy_dst
348
+
349
+
350
+ class FullAttentionCacheAllocator(CacheAllocator):
351
+ """Cache manager for a group of full attention layers."""
352
+
353
+ def __init__(self, index: int, block_size: int, allow_block_sharing: bool) -> None:
354
+ """Initializes the cache manager for a group of full attention layers.
355
+ Args:
356
+ - index: the index of the associated layer group
357
+ - block_size: the size of the blocks in the cache
358
+ """
359
+ self._index = index
360
+ self.uses_block_sharing = allow_block_sharing
361
+ self.block_size = block_size
362
+ self.block_table = {}
363
+
364
+ def allocate_blocks(self, n_blocks: int, request_id: str, block_manager: BlockManager) -> int | None:
365
+ """Allocate (n_blocks) for a given (request_id) using the (block_manager). Returns the number of blocks
366
+ allocated if successful and None otherwise. For group of full attention layers, we always allocate the number of
367
+ requested blocks."""
368
+ # Make sure the request_id is in the block table and get the first block id
369
+ block_table = self.block_table.get(request_id, [])
370
+ if block_table:
371
+ last_block_id = block_table[-1]
372
+ else:
373
+ self.block_table[request_id] = block_table # TODO: check the impact of making this a deque
374
+ last_block_id = None
375
+ # Actual allocation, return early if failed
376
+ allocated_blocks = block_manager.get_free_blocks(n_blocks, last_block_id, self.uses_block_sharing, self._index)
377
+ if allocated_blocks is None:
378
+ return None
379
+ block_table.extend(allocated_blocks)
380
+ return n_blocks
381
+
382
+ def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
383
+ """Returns the physical indices of where to read request_id's cache. For a group of full attention layers, we
384
+ first write the new cache to the cache tensor and then read the entire cache from the beginning to the end."""
385
+ # Retrieve the block table for the request and raise an error if it doesn't exist
386
+ block_table = self.block_table.get(request_id)
387
+ if block_table is None:
388
+ raise ValueError(f"No block table found for request {request_id}")
389
+ # Compute auxiliary variable so we can perform only two loops
390
+ total_length = past_length + query_length
391
+ num_full_blocks = total_length // self.block_size
392
+ remainder = total_length % self.block_size
393
+ # Compute the physical indices
394
+ physical_indices = []
395
+ for b in range(num_full_blocks):
396
+ start = block_table[b] * self.block_size
397
+ physical_indices.extend(range(start, start + self.block_size))
398
+ if remainder:
399
+ start = block_table[num_full_blocks] * self.block_size
400
+ physical_indices.extend(range(start, start + remainder))
401
+ return physical_indices
402
+
403
+ def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
404
+ """Returns the physical indices for writing to the cache. For a group of full attention layers, we write the new
405
+ cache as a continuation of the existing cache for the same request."""
406
+ block_table = self.block_table.get(request_id)
407
+ if block_table is None:
408
+ raise ValueError(f"No block table found for request {request_id}")
409
+ # Compute auxiliary variables so we can perform only one loop
410
+ start_block = past_length // self.block_size
411
+ start_offset = past_length % self.block_size
412
+ end_pos = past_length + query_length
413
+ end_block = (end_pos - 1) // self.block_size # -1 because if end_pos == block_size, we still end on block 0
414
+ # Compute the physical indices
415
+ physical_indices = []
416
+ for b in range(start_block, end_block + 1):
417
+ block_start = block_table[b] * self.block_size
418
+ # First block may start mid-block, last block may end mid-block
419
+ local_start = start_offset if b == start_block else 0
420
+ local_end = (end_pos - 1) % self.block_size + 1 if b == end_block else self.block_size
421
+ physical_indices.extend(range(block_start + local_start, block_start + local_end))
422
+ return physical_indices
423
+
424
+ def fill_block_table(
425
+ self, request_id: str, past_length: int, query_length: int, block_table: torch.Tensor
426
+ ) -> None:
427
+ """Fills the block table for a given request_id, past_length and query_length."""
428
+ request_blocks = self.block_table.get(request_id)
429
+ if request_blocks is None:
430
+ raise ValueError(f"No block table found for request {request_id}")
431
+ total_length = past_length + query_length
432
+ # Use ceiling division to include the partial block at the end
433
+ num_blocks_needed = (total_length + self.block_size - 1) // self.block_size
434
+ block_table[:num_blocks_needed] = torch.tensor(
435
+ request_blocks[:num_blocks_needed], device=block_table.device, dtype=block_table.dtype
436
+ )
437
+ # TODO: this creates a lot of H2D transfers when not using async batching, but we will update to always using
438
+ # an IO pair in the future or a CPU-side block table. This also entails a small memory allocation.
439
+
440
+
441
+ class SlidingAttentionCacheAllocator(CacheAllocator):
442
+ """Cache manager for sliding window attention layers."""
443
+
444
+ def __init__(
445
+ self, index: int, block_size: int, sliding_window: int, sentinel_index: int, trash_index: int
446
+ ) -> None:
447
+ """Initializes the cache manager for a group of sliding window attention layers. ``sentinel_index`` and
448
+ ``trash_index`` are valid cache positions in the padding zone, used instead of -1 in read and write indices
449
+ respectively so that index_select/index_copy_ never receive negative values.
450
+ """
451
+ self._index = index
452
+ self.uses_block_sharing = False
453
+ self.block_size = block_size
454
+ self.sliding_window = sliding_window
455
+ self.sentinel_index = sentinel_index
456
+ self.trash_index = trash_index
457
+ self._max_blocks_per_request = ceil(self.sliding_window / self.block_size)
458
+ self.block_table = {}
459
+
460
+ def allocate_blocks(self, n_blocks: int, request_id: str, block_manager: BlockManager) -> int | None:
461
+ """Allocate (n_blocks) for a given (request_id) using the (block_manager). Returns the number of blocks
462
+ allocated otherwise. For group of sliding window attention layers, we only allocate up to the point where we can
463
+ fit an entire sliding window in the cache tensor."""
464
+ if request_id not in self.block_table:
465
+ self.block_table[request_id] = []
466
+ # Early return if we are already at the max number of blocks per request
467
+ already_allocated = len(self.block_table[request_id])
468
+ if already_allocated == self._max_blocks_per_request:
469
+ return 0
470
+ # Compute actual number of blocks to allocate
471
+ after_allocation = min(already_allocated + n_blocks, self._max_blocks_per_request)
472
+ actual_n_blocks = after_allocation - already_allocated
473
+ # Classic allocation
474
+ allocated_blocks = block_manager.get_free_blocks(
475
+ actual_n_blocks, None, self.uses_block_sharing, self._index
476
+ ) # no block sharing w/ sliding window
477
+ if allocated_blocks is None:
478
+ return None
479
+ self.block_table[request_id].extend(allocated_blocks)
480
+ return actual_n_blocks
481
+
482
+ def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
483
+ """Returns the physical indices of where to read request_id's cache in the cache tensor.
484
+ For a group of sliding window attention layers, we read from the cache tensor before writing on it, because the
485
+ new cache can overwrite the old one. To form the cache + new key / values states, we read the at most
486
+ sliding_window - 1 cache page and then manually add the new key / values states after. Hence the sentinel
487
+ indices which indicate where to store the new key or values indices."""
488
+ # Retrieve the block table for the request and raise an error if it doesn't exist
489
+ block_table = self.block_table.get(request_id)
490
+ if block_table is None:
491
+ raise ValueError(f"No block table found for request {request_id}")
492
+ # Apply sliding window
493
+ start_index = 0 if past_length < self.sliding_window else past_length % self.sliding_window
494
+ cache_length = min(past_length, self.sliding_window - 1)
495
+ # Compute the physical indices
496
+ physical_indices = []
497
+ for i in range(start_index, start_index + cache_length):
498
+ i %= self.sliding_window
499
+ block_idx = i // self.block_size
500
+ block_offset = i % self.block_size
501
+ physical_index = block_table[block_idx] * self.block_size + block_offset
502
+ physical_indices.append(physical_index)
503
+ return physical_indices + [self.sentinel_index] * query_length
504
+
505
+ def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
506
+ """Returns the physical indices of where to write request_id's cache in the cache tensor. For a group of
507
+ sliding window attention layers, we write the new cache in rolling-buffer kind of way: if we reach the end of
508
+ the allocated physical cache, we start writing from the beginning of the physical cache again."""
509
+ # Retrieve the block table for the request and raise an error if it doesn't exist
510
+ block_table = self.block_table.get(request_id)
511
+ if block_table is None:
512
+ raise ValueError(f"No block table found for request {request_id}")
513
+ # Apply sliding window
514
+ start_index = past_length % self.sliding_window
515
+ cache_length = min(query_length, self.sliding_window)
516
+ padding_length = query_length - cache_length
517
+ # Compute the physical indices
518
+ physical_indices = []
519
+ for i in range(start_index, start_index + cache_length):
520
+ i %= self.sliding_window
521
+ block_idx = i // self.block_size
522
+ block_offset = i % self.block_size
523
+ physical_index = block_table[block_idx] * self.block_size + block_offset
524
+ physical_indices.append(physical_index)
525
+ if padding_length > 0:
526
+ physical_indices = [self.trash_index] * padding_length + physical_indices
527
+ return physical_indices
528
+
529
+ # TODO: implement this
530
+ def fill_block_table(
531
+ self, request_id: str, past_length: int, query_length: int, block_table: torch.Tensor
532
+ ) -> None:
533
+ raise NotImplementedError("Sliding window attention layers do not support block table")
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/cb_logits_processors.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from abc import ABC, abstractmethod
15
+
16
+ import torch
17
+
18
+ from ..logits_process import (
19
+ LogitsProcessorList,
20
+ TemperatureLogitsWarper,
21
+ TopKLogitsWarper,
22
+ TopPLogitsWarper,
23
+ )
24
+ from .requests import FutureRequestState, logger
25
+
26
+
27
+ # Abstract base class for all continuous batching logits processors
28
+ class ContinuousBatchingLogitsProcessor(ABC):
29
+ # Kwargs that this processor uses, mapped to their expected type. Only the type is checked at runtime, value-range
30
+ # validation (e.g. temperature > 0) is not performed to keep a light API. You can open a PR if this is needed.
31
+ supported_kwargs: dict[str, type]
32
+ # Kwargs that this processor recognizes but ignores
33
+ ignored_kwargs: tuple[str, ...]
34
+
35
+ @abstractmethod
36
+ def fill_defaults(self, int32_tensor: torch.Tensor) -> None:
37
+ """Fills the given tensor int32 tensor with the default values for this processor."""
38
+ pass
39
+
40
+ @abstractmethod
41
+ def prepare_tensor_args(self, requests_in_batch: list[FutureRequestState]) -> torch.Tensor:
42
+ pass
43
+
44
+ @abstractmethod
45
+ def __call__(self, scores: torch.FloatTensor, tensor_arg: torch.Tensor) -> torch.FloatTensor:
46
+ """Applies the logits processor in a per-token manner.
47
+ Args:
48
+ - scores (torch.FloatTensor): The scores to process, with shape [num_tokens, vocab_size]
49
+ - tensor_arg (torch.Tensor): The tensor argument to use for the logits processor, with shape
50
+ [max_num_tokens] and dtype torch.int32. The dtype might not be representative of the actual data, for
51
+ instance it's common to have a float32 tensor viewed as int32 (eg. temperature)
52
+ Returns:
53
+ - torch.FloatTensor: The processed scores, with shape [num_tokens, vocab_size]
54
+ """
55
+ pass
56
+
57
+
58
+ # Main class for managing a list of processors (CB version or not) for batched generation
59
+ class ContinuousBatchingLogitsProcessorList:
60
+ """A class to hold logits processors for continuous batching (CB).
61
+
62
+ Each processor has a base class, which is the one used in regular `generate` and some have a per-request version
63
+ adapted for CB. The list of logits processors present is generated using the `_get_logits_processor` method from
64
+ the model, which will only include processors if their presence is required by the generation config. For instance,
65
+ if you want to use temperature scaling, you need to specify a temperature that's neither None nor 1.0. Otherwise
66
+ no processors will be created for temperature, and per-request temperature scaling will not be available.
67
+
68
+ On support of base processors:
69
+ Some base processors are not supported by CB and will be dropped when this class is instantiated. Some
70
+ processors have not yet been categorized as supported or not and will be kept but with a warning. All processors
71
+ can be kept by setting the flag `drop_unsupported_processors` to False.
72
+ On per-request processors:
73
+ Some base processors have a per-request version adapted for CB and will be converted to their per-request
74
+ version when this class is instantiated. This is the default behavior unless the flag `per_request_processors`
75
+ is set to False.
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ logits_processor: LogitsProcessorList,
81
+ per_request_processors: bool = False,
82
+ drop_unsupported_processors: bool = True,
83
+ ) -> None:
84
+ self.logits_processor = logits_processor
85
+ self.tensors_required = 0 # number of tensors required to store CB logits processors arguments
86
+ # If needed, convert compatible logits processors to their per-request versions
87
+ if per_request_processors:
88
+ self._convert_to_per_request_processors()
89
+ # Validate and optionally filter processors based on their CB support
90
+ self._validate_processors(drop_unsupported_processors)
91
+ self._retrieve_processors_kwargs()
92
+ # Static boolean to know if there is any logits processing to do. Helps with torch.compile().
93
+ self.do_processing = len(self.logits_processor) > 0
94
+
95
+ def __repr__(self) -> str:
96
+ return f"ContinuousBatchingLogitsProcessorList(logits_processor={self.logits_processor}, tensors_required={self.tensors_required})"
97
+
98
+ def clear(self) -> None:
99
+ self.logits_processor = LogitsProcessorList()
100
+ self.tensors_required = 0
101
+ self.supported_keys = {}
102
+ self.ignored_keys = set()
103
+ self.do_processing = False
104
+
105
+ def _convert_to_per_request_processors(self) -> None:
106
+ """Replaces the compatible logits processors with their per-request versions."""
107
+ for i, processor in enumerate(self.logits_processor):
108
+ for regular_cls, cb_cls in CLASSIC_TO_CB_PROCESSORS_MAP.items():
109
+ if isinstance(processor, regular_cls):
110
+ self.logits_processor[i] = cb_cls(processor)
111
+ self.tensors_required += 1 # in the future, this might be more than 1 (will be stored in mapping)
112
+ break
113
+
114
+ def _validate_processors(self, drop_unsupported: bool) -> None:
115
+ """Validates the logits processors and optionally removes unsupported ones. When drop_unsupported is True,
116
+ processors explicitly marked as unsupported are removed. Otherwise, all processors are kept but warnings are
117
+ logged for unsupported or unknown ones.
118
+ """
119
+ filtered_processors = []
120
+ for processor in self.logits_processor:
121
+ class_name = processor.__class__.__name__
122
+ supported = getattr(processor, "supports_continuous_batching", None)
123
+
124
+ # Keep all ContinuousBatchingLogitsProcessor or supported processors
125
+ if isinstance(processor, ContinuousBatchingLogitsProcessor) or supported:
126
+ filtered_processors.append(processor)
127
+ # Keep processors with support status unknown
128
+ elif supported is None:
129
+ logger.warning(f"Processor {class_name} might not be supported by CB.")
130
+ filtered_processors.append(processor)
131
+ # Otherwise, processor is not supported, then behavior depends on the flag drop_unsupported
132
+ elif drop_unsupported:
133
+ logger.warning(f"Processor {class_name} isn't supported by CB. Dropping it.")
134
+ else:
135
+ logger.warning(f"Processor {class_name} isn't supported by CB. Kept it because {drop_unsupported = }.")
136
+ filtered_processors.append(processor)
137
+
138
+ # Update the list of logits processors (preserve LogitsProcessorList type)
139
+ self.logits_processor = LogitsProcessorList(filtered_processors)
140
+
141
+ def _retrieve_processors_kwargs(self) -> None:
142
+ """Retrieves the supported (with types) and ignored kwargs from continuous batching processors."""
143
+ self.supported_keys: dict[str, type] = {}
144
+ self.ignored_keys = set()
145
+ for processor in self.logits_processor:
146
+ if isinstance(processor, ContinuousBatchingLogitsProcessor):
147
+ self.supported_keys.update(processor.supported_kwargs)
148
+ self.ignored_keys.update(processor.ignored_kwargs)
149
+
150
+ def check_kwargs(self, kwargs: dict) -> None:
151
+ """Checks that the provided kwargs are compatible with the current CB processors. Warn for ignored kwargs."""
152
+ if not kwargs:
153
+ return None
154
+ # Validate types for supported keys, detect unsupported keys
155
+ problematic_keys = set()
156
+ for key, value in kwargs.items():
157
+ if key not in self.supported_keys:
158
+ problematic_keys.add(key)
159
+ else:
160
+ expected_type = self.supported_keys[key]
161
+ if not isinstance(value, expected_type):
162
+ raise TypeError(
163
+ f"logit_processor_kwargs['{key}'] has type {type(value).__name__}, expected {expected_type.__name__}"
164
+ )
165
+ # Stop if there are only supported keys
166
+ if not problematic_keys:
167
+ return
168
+ # Check if there are unknown keys
169
+ unknown_keys = problematic_keys - self.ignored_keys
170
+ if unknown_keys:
171
+ raise ValueError(
172
+ f"Unknown logit_processor_kwargs: {unknown_keys}. {self.supported_keys = } and {self.ignored_keys = }"
173
+ "If you expect a key to not be ignored, make sure its default value (in the generation config) is not "
174
+ "None. Eg. if temperature is None or 1.0 at creation time, no processor will be created for temperature"
175
+ )
176
+ # If there are none, throw a warning about the ignored keys
177
+ logger.warning(
178
+ f"Ignored logit_processor_kwargs: {problematic_keys}. {self.supported_keys = } and {self.ignored_keys = }"
179
+ )
180
+
181
+ def fill_defaults(self, int32_tensor: torch.Tensor) -> None:
182
+ """Fills the given tensor int32 tensor with the default values for this processor."""
183
+ i = 0
184
+ for processor in self.logits_processor:
185
+ if isinstance(processor, ContinuousBatchingLogitsProcessor):
186
+ processor.fill_defaults(int32_tensor[i])
187
+ i += 1
188
+
189
+ def prepare_tensor_args(
190
+ self, requests_in_batch: list[FutureRequestState], arg_storage: torch.Tensor
191
+ ) -> torch.Tensor:
192
+ current_arg_id = 0
193
+ for processor in self.logits_processor:
194
+ if isinstance(processor, ContinuousBatchingLogitsProcessor):
195
+ tensorized_arg = processor.prepare_tensor_args(requests_in_batch)
196
+ arg_storage[current_arg_id, : tensorized_arg.size(0)] = tensorized_arg.to(arg_storage.device)
197
+ current_arg_id += 1
198
+ return arg_storage
199
+
200
+ def __call__(
201
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor, logits_processor_args: torch.Tensor
202
+ ) -> torch.FloatTensor:
203
+ current_arg_id = 0
204
+ for processor in self.logits_processor:
205
+ if isinstance(processor, ContinuousBatchingLogitsProcessor):
206
+ scores = processor(scores, logits_processor_args[current_arg_id])
207
+ current_arg_id += 1
208
+ else:
209
+ scores = processor(input_ids, scores)
210
+ return scores
211
+
212
+
213
+ # Here are all the continuous batching logits processors that are supported
214
+ class ContinuousBatchingTemperatureLogitsWarper(ContinuousBatchingLogitsProcessor):
215
+ supported_kwargs: dict[str, type] = {"temperature": float}
216
+ ignored_kwargs: tuple[str, ...] = ()
217
+
218
+ def __init__(self, temperature_processor: TemperatureLogitsWarper) -> None:
219
+ self.temperature = temperature_processor.temperature
220
+
221
+ def fill_defaults(self, int32_tensor: torch.Tensor) -> None:
222
+ """Fills the given tensor int32 tensor with the default temperature."""
223
+ default = torch.empty_like(int32_tensor, dtype=torch.float32)
224
+ default.fill_(self.temperature)
225
+ int32_tensor.copy_(default.view(dtype=torch.int32))
226
+
227
+ def prepare_tensor_args(self, requests_in_batch: list[FutureRequestState]) -> torch.Tensor:
228
+ data = []
229
+ for request in requests_in_batch:
230
+ temp = request.state.logit_processor_kwargs.get("temperature", self.temperature)
231
+ data.extend([temp] * request.query_length)
232
+ tensorized = torch.tensor(data, dtype=torch.float32, device="cpu")
233
+ # View the output with the bulk storage dtype (int32) but keeps the underlying data the same
234
+ return tensorized.view(dtype=torch.int32)
235
+
236
+ def __call__(self, scores: torch.FloatTensor, tensor_arg: torch.Tensor) -> torch.FloatTensor:
237
+ temperatures = tensor_arg[: scores.size(0)].view(dtype=torch.float32) # shape [N]
238
+ return scores / temperatures.unsqueeze(-1) # broadcast [N, 1] over [N, V]
239
+
240
+
241
+ class ContinuousBatchingTopKLogitsWarper(ContinuousBatchingLogitsProcessor):
242
+ supported_kwargs: dict[str, type] = {"top_k": int}
243
+ ignored_kwargs: tuple[str, ...] = ("filter_value", "min_tokens_to_keep")
244
+
245
+ def __init__(self, top_k_processor: TopKLogitsWarper):
246
+ self.top_k = top_k_processor.top_k
247
+ self.filter_value = top_k_processor.filter_value
248
+ self.min_tokens_to_keep = top_k_processor.min_tokens_to_keep
249
+
250
+ def fill_defaults(self, int32_tensor: torch.Tensor) -> None:
251
+ """Fills the given tensor int32 tensor with the default top_k."""
252
+ int32_tensor.fill_(self.top_k)
253
+
254
+ def prepare_tensor_args(self, requests_in_batch: list[FutureRequestState]) -> torch.Tensor:
255
+ top_ks = []
256
+ for request in requests_in_batch:
257
+ top_k = request.state.logit_processor_kwargs.get("top_k", self.top_k)
258
+ top_k = max(top_k, self.min_tokens_to_keep)
259
+ top_ks.extend([top_k] * request.query_length)
260
+ # Prepare tensor arg with int32 as the main type
261
+ tensor_args = torch.tensor(top_ks, dtype=torch.int32, device="cpu")
262
+ return tensor_args
263
+
264
+ def __call__(self, scores: torch.FloatTensor, tensor_arg: torch.Tensor) -> torch.FloatTensor:
265
+ """Applies top-k selection to the scores tensor (shape [N, V])."""
266
+ top_k = tensor_arg[: scores.size(0)] # shape [N]
267
+ # Sort descending, get threshold at position (top_k - 1) which is the k-th largest
268
+ sorted_scores = torch.sort(scores, dim=-1, descending=True)[0] # [N, V]
269
+ top_k_indices = (top_k - 1).unsqueeze(-1).to(dtype=torch.int64) # [N, 1]
270
+ thresholds = sorted_scores.gather(dim=-1, index=top_k_indices) # [N, 1]
271
+ return scores.masked_fill(scores < thresholds, self.filter_value)
272
+
273
+
274
+ class ContinuousBatchingTopPLogitsWarper(ContinuousBatchingLogitsProcessor):
275
+ supported_kwargs: dict[str, type] = {"top_p": float}
276
+ ignored_kwargs: tuple[str, ...] = ("filter_value", "min_tokens_to_keep")
277
+
278
+ def __init__(self, top_p_processor: TopPLogitsWarper):
279
+ self.top_p = top_p_processor.top_p
280
+ self.filter_value = top_p_processor.filter_value
281
+ self.min_tokens_to_keep = top_p_processor.min_tokens_to_keep
282
+
283
+ def fill_defaults(self, int32_tensor: torch.Tensor) -> None:
284
+ """Fills the given tensor int32 tensor with the default top_p."""
285
+ default = torch.empty_like(int32_tensor, dtype=torch.float32)
286
+ default.fill_(self.top_p)
287
+ int32_tensor.copy_(default.view(dtype=torch.int32))
288
+
289
+ def prepare_tensor_args(self, requests_in_batch: list[FutureRequestState]) -> torch.Tensor:
290
+ top_ps = []
291
+ for request in requests_in_batch:
292
+ # Retrieve config for this request
293
+ top_p = request.state.logit_processor_kwargs.get("top_p", self.top_p)
294
+ top_ps.extend([top_p] * request.query_length)
295
+ # Store top_p as float32 viewed as int32 to match the bulk storage dtype
296
+ tensorized = torch.tensor(top_ps, dtype=torch.float32, device="cpu")
297
+ return tensorized.view(dtype=torch.int32)
298
+
299
+ def __call__(self, scores: torch.FloatTensor, tensor_arg: torch.Tensor) -> torch.FloatTensor:
300
+ """Applies top-p (nucleus) sampling to the scores tensor (shape [N, V])."""
301
+ top_p = tensor_arg[: scores.size(0)].view(dtype=torch.float32) # shape [N]
302
+
303
+ # Sort logits in ascending order
304
+ sorted_logits, sorted_indices = torch.sort(scores, descending=False, dim=-1) # [N, V]
305
+ cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1) # [N, V]
306
+
307
+ # Remove tokens with cumulative probability <= (1 - top_p)
308
+ threshold = (1 - top_p).unsqueeze(-1) # [N, 1]
309
+ sorted_indices_to_remove = cumulative_probs <= threshold # [N, V]
310
+
311
+ # Keep at least min_tokens_to_keep (always keep the last tokens in sorted order = highest prob)
312
+ sorted_indices_to_remove[..., -self.min_tokens_to_keep :] = False
313
+
314
+ # Scatter sorted mask back to original indexing
315
+ indices_to_remove = sorted_indices_to_remove.scatter(-1, sorted_indices, sorted_indices_to_remove)
316
+ return scores.masked_fill(indices_to_remove, self.filter_value)
317
+
318
+
319
+ # TODO: add non-per-request CB variants so the memory-efficient warpers work when `per_request_processors=False`.
320
+ # TODO: fuse temperature + top-k + top-p into a single pass to reuse the softmax/sort and cut activation peak.
321
+ CLASSIC_TO_CB_PROCESSORS_MAP = {
322
+ TemperatureLogitsWarper: ContinuousBatchingTemperatureLogitsWarper,
323
+ TopKLogitsWarper: ContinuousBatchingTopKLogitsWarper,
324
+ TopPLogitsWarper: ContinuousBatchingTopPLogitsWarper,
325
+ }
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/continuous_api.py ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team.
2
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import asyncio
16
+ import gc
17
+ import queue
18
+ import threading
19
+ from abc import abstractmethod
20
+ from collections.abc import Callable, Generator
21
+ from contextlib import contextmanager, nullcontext
22
+ from math import ceil
23
+ from time import perf_counter
24
+ from typing import Any
25
+
26
+ import torch
27
+ from torch import nn
28
+ from tqdm import tqdm
29
+ from tqdm.contrib.logging import logging_redirect_tqdm
30
+
31
+ from ...configuration_utils import PretrainedConfig
32
+ from ...generation.configuration_utils import ContinuousBatchingConfig, GenerationConfig
33
+ from ...modeling_flash_attention_utils import lazy_import_paged_flash_attention
34
+ from ...utils.generic import is_flash_attention_requested
35
+ from ...utils.logging import logging
36
+ from ...utils.metrics import ContinuousBatchProcessorMetrics, attach_tracer, traced
37
+ from ..logits_process import LogitsProcessorList
38
+ from .cache import PagedAttentionCache
39
+ from .cb_logits_processors import ContinuousBatchingLogitsProcessorList
40
+ from .input_outputs import ContinuousBatchingAsyncIOs, ContinuousBatchingIOs
41
+ from .offloading_manager import OffloadingManager
42
+ from .requests import GenerationOutput, RequestState, RequestStatus, logger
43
+ from .scheduler import SCHEDULER_MAPPING, FIFOScheduler, Scheduler
44
+ from .utils import WorkloadHints, attn_mask_is_needed, create_warmup_future_states, pad_to_interval, pad_to_pow2
45
+
46
+
47
+ """
48
+ To enable cuda graphs, we need the dimensions of all tensors to be static, which is counter-intuitive for CB. In CB, as
49
+ generation goes on, there are two dimensions that change:
50
+ - the number of queries tokens (Q), which can vary from batch to batch
51
+ - the number of keys/values tokens (KV), which grows as the cache does
52
+
53
+ To solve this, we slice along those dimensions to fixed lengths. The size of the slices is controlled by interval sizes:
54
+ - q_padding_interval_size: the padding granularity for queries (in tokens)
55
+ - kv_padding_interval_size: the padding granularity for KV cache (in tokens)
56
+
57
+ For example, with q_padding_interval_size=64 and an actual query length of 100, we pad to 128 tokens.
58
+
59
+ Smaller intervals mean finer granularity and thus less padding, but more unique graph signatures. Since graphs take
60
+ memory and time to create, we use an LRU cache with a fixed size to limit memory usage. Good defaults:
61
+ - Q: 64 tokens gives ~4 graphs for max_batch_tokens=256, which is a good balance
62
+ - KV: 8192 tokens (256 blocks at block_size=32) gives reasonable granularity for large caches
63
+
64
+ The maximum number of cached graphs is controlled by max_cached_graphs (default 32), which uses LRU eviction.
65
+ All defaults are stored in ContinuousBatchingConfig.resolve_sentinel_values().
66
+ """
67
+
68
+
69
+ # We cannot use `PreTrainedModel` for circular import reasons, so this helps keep track of the basic types
70
+ class ProtoPretrainedModel(nn.Module):
71
+ config: PretrainedConfig
72
+ dtype: torch.dtype
73
+ device: torch.device
74
+
75
+ @abstractmethod
76
+ def set_attn_implementation(self, attn_implementation: str) -> None:
77
+ pass
78
+
79
+ @abstractmethod
80
+ def _get_logits_processor(self, generation_config: GenerationConfig) -> LogitsProcessorList:
81
+ pass
82
+
83
+
84
+ class OutputRouter:
85
+ """Dedicated object for routing generation outputs to the right destination.
86
+
87
+ When an async handler is registered for a request, the output is forwarded
88
+ to that handler via ``call_soon_threadsafe``. Otherwise the output is placed
89
+ on the shared ``output_queue``.
90
+ """
91
+
92
+ def __init__(self) -> None:
93
+ self.output_queue = queue.Queue()
94
+ self.result_handlers: dict[str, tuple[Callable, asyncio.AbstractEventLoop]] = {}
95
+ self._lock = threading.Lock()
96
+
97
+ def deliver(self, output: GenerationOutput) -> None:
98
+ """Route a single output to its registered handler or the output_queue."""
99
+ with self._lock:
100
+ entry = self.result_handlers.get(output.request_id)
101
+ if entry is not None:
102
+ callback, loop = entry
103
+ loop.call_soon_threadsafe(callback, output)
104
+ else:
105
+ self.output_queue.put(output)
106
+
107
+ def deliver_batch(self, outputs: list[GenerationOutput]) -> None:
108
+ """Route a batch of outputs, using a single ``call_soon_threadsafe`` to minimize cross-thread overhead.
109
+
110
+ Outputs without a registered handler fall back to the shared ``output_queue``.
111
+ """
112
+ callbacks: list[tuple[Callable, GenerationOutput]] = []
113
+ loop = None
114
+ with self._lock:
115
+ for output in outputs:
116
+ entry = self.result_handlers.get(output.request_id)
117
+ if entry is not None:
118
+ callback, loop = entry
119
+ callbacks.append((callback, output))
120
+ else:
121
+ self.output_queue.put(output)
122
+ if callbacks and loop is not None:
123
+
124
+ def _run_batch(batch=callbacks):
125
+ for cb, out in batch:
126
+ cb(out)
127
+
128
+ loop.call_soon_threadsafe(_run_batch)
129
+
130
+
131
+ # Continuous Batch Processor (Internal Logic)
132
+ @attach_tracer()
133
+ class ContinuousBatchProcessor:
134
+ inputs_and_outputs: ContinuousBatchingIOs | ContinuousBatchingAsyncIOs
135
+ scheduler: Scheduler
136
+
137
+ def __init__(
138
+ self,
139
+ cache: PagedAttentionCache,
140
+ config: PretrainedConfig,
141
+ generation_config: GenerationConfig,
142
+ continuous_batching_config: ContinuousBatchingConfig,
143
+ logit_processor: ContinuousBatchingLogitsProcessorList,
144
+ input_queue: queue.Queue,
145
+ output_router: OutputRouter,
146
+ stop_event: threading.Event,
147
+ model_device: torch.device,
148
+ model_dtype: torch.dtype,
149
+ scheduler: Scheduler,
150
+ ) -> None:
151
+ """Initialize the continuous batch processor.
152
+
153
+ Args:
154
+ cache: A [`PagedAttentionCache`] object
155
+ config: The model configuration
156
+ generation_config: The generation configuration
157
+ continuous_batching_config: The continuous batching configuration
158
+ logit_processor: The [`ContinuousBatchingLogitsProcessorList`] object used to process the logits.
159
+ input_queue: Queue for incoming requests
160
+ output_router: An [`OutputRouter`] object that routes outputs to handlers or the output queue.
161
+ stop_event: Event to signal processing should stop
162
+ model_device: Device for model inputs/outputs
163
+ model_dtype: Data type for model inputs/outputs
164
+ scheduler: The [`Scheduler`] to use
165
+ """
166
+ self.cache = cache
167
+ self.config = config
168
+ self.cb_config = continuous_batching_config
169
+ self.logit_processor = logit_processor
170
+ self.input_queue = input_queue
171
+ self.output_router = output_router
172
+ self.stop_event = stop_event
173
+ self.model_device = model_device
174
+ self.model_dtype = model_dtype
175
+ self.scheduler = scheduler
176
+
177
+ # Generation-related attributes
178
+ self.do_sample = getattr(generation_config, "do_sample", True)
179
+ self.return_logprobs = continuous_batching_config.return_logprobs
180
+
181
+ # Retrieve the size of the sliding window if there is one
182
+ self.sliding_window = 1 if getattr(config, "sliding_window", None) is None else config.sliding_window
183
+ # Cuda graphs for the generation step
184
+ self.q_padding_interval_size = self.cb_config.q_padding_interval_size
185
+ self.kv_padding_interval_size = self.cb_config.kv_padding_interval_size
186
+ self.use_cuda_graph_varlen, self.use_cuda_graph_decode = self.cb_config.get_cuda_graph_booleans()
187
+
188
+ # Set up metrics collector
189
+ self.max_batch_tokens = cache.max_batch_tokens
190
+ self.metrics = ContinuousBatchProcessorMetrics(cache.max_batch_tokens)
191
+
192
+ # If the user turned on the decode fast path (ie. using a block table), check if it is available
193
+ self._ensure_decode_fast_path_is_available() # this needs to happen before self.inputs_and_outputs is created
194
+
195
+ # Resolve compile behavior
196
+ self.cb_config.resolve_compile_configs(
197
+ fallback_compile_config=getattr(generation_config, "compile_config", None),
198
+ is_flash_attn=is_flash_attention_requested(config=config),
199
+ decode_fast_path_available=self.cache.max_blocks_per_request > 0,
200
+ )
201
+ varlen_config, decode_config = self.cb_config.varlen_compile_config, self.cb_config.decode_compile_config
202
+
203
+ # Compile the varlen path if config provided
204
+ self._compiled_varlen = None
205
+ if varlen_config is not None:
206
+ self._compiled_varlen = torch.compile(self._forward_process_and_sample, **varlen_config.to_dict())
207
+
208
+ # Compile the decode path if config provided
209
+ self._compiled_decode = None
210
+ if decode_config is not None:
211
+ self._compiled_decode = torch.compile(self._forward_process_and_sample, **decode_config.to_dict())
212
+
213
+ # Padding is turned on when either cuda graphs or compile is used
214
+ use_cuda_graphs = self.use_cuda_graph_varlen or self.use_cuda_graph_decode
215
+ self._pad_inputs = use_cuda_graphs or (varlen_config is not None or decode_config is not None)
216
+ # Set up the graph pool. This allows all graphs to share the same memory pool, greatly saving memory.
217
+ self.graph_pool = torch.cuda.graph_pool_handle() if use_cuda_graphs else None
218
+
219
+ # Setup inputs and outputs
220
+ io_kwargs = {
221
+ "cache": cache,
222
+ "config": config,
223
+ "device": model_device,
224
+ "model_dtype": model_dtype,
225
+ "return_logprobs": self.return_logprobs,
226
+ "logit_processor": self.logit_processor,
227
+ "use_cuda_graph_varlen": self.use_cuda_graph_varlen,
228
+ }
229
+ self.use_async_batching = self.cb_config.use_async_batching
230
+
231
+ if self.use_async_batching:
232
+ # Since in async there are 2 IO pairs, there are also 2 graph buffers: we divide the max_cached_graphs by 2
233
+ io_kwargs["max_graphs"] = ceil(self.cb_config.max_cached_graphs / 2)
234
+ self.inputs_and_outputs = ContinuousBatchingAsyncIOs(**io_kwargs)
235
+ else:
236
+ io_kwargs["max_graphs"] = self.cb_config.max_cached_graphs
237
+ self.inputs_and_outputs = ContinuousBatchingIOs(**io_kwargs)
238
+
239
+ # Offloading manager: handles CPU offloading, soft reset, and restoration
240
+ self.offloading_manager = OffloadingManager(
241
+ cache=cache,
242
+ scheduler=scheduler,
243
+ cpu_offload_space_gib=continuous_batching_config.cpu_offload_space,
244
+ safety_threshold=continuous_batching_config.cpu_offload_space_safety_threshold,
245
+ compute_stream=self.inputs_and_outputs.compute_stream,
246
+ )
247
+
248
+ def __repr__(self) -> str:
249
+ return (
250
+ f"ContinuousBatchProcessor(input_queue={self.input_queue}, "
251
+ f"active_requests={self.scheduler.active_requests}, waiting_requests={self.scheduler.waiting_requests})"
252
+ + self.inputs_and_outputs.get_model_kwargs().__repr__()
253
+ )
254
+
255
+ def __del__(self) -> None:
256
+ self.inputs_and_outputs = None # clean up CUDA graphs in priority
257
+ gc.collect()
258
+ if torch.cuda.is_available():
259
+ torch.cuda.empty_cache()
260
+
261
+ def _ensure_decode_fast_path_is_available(self) -> None:
262
+ """Ensures the decode fast path is available. If it is not, set the max blocks per request to 0. If it is
263
+ available, and no user-provided max blocks per request, set it to the fallback default."""
264
+ # First, set max blocks per request to 32 if it needs to be auto-inferred
265
+ user_requested = self.cb_config.max_blocks_per_request is not None
266
+ if not user_requested:
267
+ self.cache.max_blocks_per_request = self.cb_config.fallback_max_blocks_per_request
268
+ logger_warning = lambda x: x # silences warning for user_requested=False # noqa: E731
269
+ else:
270
+ logger_warning = logger.warning
271
+
272
+ # Then, if the decode fast path is not turned off, check if it is available
273
+ if self.cache.max_blocks_per_request != 0:
274
+ # NOTE: block table should be available with FA2 and FA3, but there seems to be an issue with FA2 atm
275
+ if is_flash_attention_requested(self.config, version=3):
276
+ flash_attn_with_kvcache = lazy_import_paged_flash_attention(self.config._attn_implementation)[1]
277
+ conditions = [
278
+ self.cache.num_sliding_attention_groups == 0, # TODO: add support for sliding window layers
279
+ torch.cuda.is_available(), # Block table is only supported on CUDA
280
+ flash_attn_with_kvcache is not None, # The `flash_attn_with_kvcache` fn is needed
281
+ ]
282
+ # Throw a warning only if the decode fast path was requested by the user
283
+ if not all(conditions):
284
+ logger_warning(
285
+ f"Although {self.cache.max_blocks_per_request = }, the decode fast path is not available "
286
+ f"because the one condition is not met: {conditions}."
287
+ )
288
+ self.cache.max_blocks_per_request = 0
289
+ # Specific warning for attn implementation other than FA3
290
+ else:
291
+ logger_warning(
292
+ f"Although {self.cache.max_blocks_per_request = }, the decode fast path is not available "
293
+ f"because the attention implementation is not FA3. Got {self.config._attn_implementation = }."
294
+ )
295
+ self.cache.max_blocks_per_request = 0
296
+
297
+ def reset(self) -> None:
298
+ """Reset the batch processor for a new generation loop."""
299
+ self.offloading_manager.reset()
300
+ self.scheduler.reset()
301
+ self.inputs_and_outputs.reset()
302
+ self.cache.free_all_requests()
303
+ self.metrics = ContinuousBatchProcessorMetrics(self.cache.max_batch_tokens)
304
+
305
+ @traced
306
+ def _get_new_requests(self) -> None:
307
+ """Pull new requests from the input queue and add to waiting list."""
308
+ while not self.input_queue.empty():
309
+ try:
310
+ state = self.input_queue.get_nowait()
311
+ if state is None: # Sentinel value
312
+ continue
313
+ self.logit_processor.check_kwargs(state.logit_processor_kwargs)
314
+ self.scheduler.add_waiting_request(state)
315
+
316
+ except queue.Empty:
317
+ break
318
+ except Exception as e:
319
+ logger.error(f"Error processing new request: {e}", exc_info=True)
320
+ state: RequestState = locals().get("state")
321
+ if state is not None:
322
+ self._handle_request_error(e, state)
323
+
324
+ @traced
325
+ def _handle_request_error(self, error: Exception, state: RequestState) -> None:
326
+ """Handle general request processing error."""
327
+ state.status = RequestStatus.FAILED
328
+ state.error = str(error)
329
+
330
+ # Include any generated tokens if this is an active request
331
+ if isinstance(state.request_id, str):
332
+ state.generated_tokens = self.scheduler.get_active_request_static_outputs(state.request_id)
333
+ else:
334
+ state.generated_tokens = []
335
+
336
+ self.metrics.record_request_completion(state.created_time, state.request_id)
337
+ self.output_router.deliver(state.to_generation_output())
338
+
339
+ def maybe_pad_inputs(self, num_q_tokens: int, max_kv_read: int, use_decode_fast_path: bool) -> tuple[int, int]:
340
+ """Pads the inputs sizes for the next batch if it is needed. Often it is, for max performance."""
341
+ if self._pad_inputs:
342
+ # For varlen batches, we pad using interval sizes
343
+ if not use_decode_fast_path:
344
+ num_q_tokens = pad_to_interval(num_q_tokens, self.q_padding_interval_size, self.max_batch_tokens)
345
+ max_kv_read = pad_to_interval(max_kv_read, self.kv_padding_interval_size, self.cache.num_pages)
346
+ # For decode fast path batches, we pad using powers of 2 and use no KV
347
+ else:
348
+ num_q_tokens = pad_to_pow2(num_q_tokens, self.max_batch_tokens)
349
+ max_kv_read = 0
350
+ return num_q_tokens, max_kv_read
351
+
352
+ @traced
353
+ def prepare_next_batch(self) -> bool:
354
+ """Prepare tensors and metadata for the next model forward pass. Returns True if there are requests to process,
355
+ False otherwise."""
356
+
357
+ # Get new requests from the queue, stop if there are no pending requests
358
+ self._get_new_requests()
359
+ cancelled_states = self.scheduler.clear_cancelled_requests()
360
+ # Also free CPU-offloaded cache for cancelled states. This is CPU-only, so it isn't batched like D2H transfers
361
+ for state in cancelled_states:
362
+ self.offloading_manager.free_request_cpu_cache(state)
363
+ if not self.scheduler.has_pending_requests():
364
+ return False
365
+ self.metrics.record_queue_metrics(len(self.scheduler.active_requests), len(self.scheduler.waiting_requests))
366
+
367
+ # Schedule the next batch of requests
368
+ requests_in_batch, use_decode_fast_path, num_q_tokens, max_kv_read = self.scheduler.schedule_batch(
369
+ self.max_batch_tokens, self.cache.num_pages
370
+ )
371
+ # If requests_in_batch is None, it means we need to offload some requests if possible
372
+ if requests_in_batch is None:
373
+ if len(self.scheduler.active_requests) > 1:
374
+ self.offloading_manager.offload_one_request()
375
+ return False
376
+ else:
377
+ raise RuntimeError("No requests can be scheduled and no request can be offloaded.")
378
+ # If it's an empty list, it means we have no requests to process
379
+ if not requests_in_batch:
380
+ return False
381
+
382
+ # Restore any CPU-offloaded requests that were just scheduled
383
+ self.offloading_manager.restore_scheduled_requests(requests_in_batch)
384
+
385
+ # Otherwise, we can continue with the non-empty batch and log in the dimensions before padding
386
+ self.metrics.record_batch_metrics(requests_in_batch)
387
+ logger.debug(
388
+ f"Scheduled: {len(requests_in_batch)}, Waiting: {len(self.scheduler.waiting_requests)}, "
389
+ f"Active: {len(self.scheduler.active_requests)}. cum Q: {num_q_tokens}. "
390
+ f"cum KV: {max_kv_read}, free blocks: {self.cache.get_num_free_blocks()}"
391
+ )
392
+
393
+ # If inputs are static sized, eg. for compile, we find the padded sizes of the queries and keys/values
394
+ num_q_tokens, max_kv_read = self.maybe_pad_inputs(num_q_tokens, max_kv_read, use_decode_fast_path)
395
+
396
+ self.inputs_and_outputs.prepare_batch_tensors(
397
+ requests_in_batch, self.logit_processor, use_decode_fast_path, num_q_tokens, max_kv_read
398
+ )
399
+ self.metrics.record_kv_cache_memory_metrics(self.cache)
400
+ return True
401
+
402
+ @traced
403
+ def update_batch(self) -> None:
404
+ """Update request states based on generated tokens."""
405
+ requests_in_batch, new_tokens, logprobs = self.inputs_and_outputs.prepare_batch_update()
406
+ current_logits_index = 0
407
+ pending_outputs = []
408
+ for future_state in requests_in_batch:
409
+ state = future_state.state
410
+ # Early return if the request was finished or offloaded between scheduling and update (async mode)
411
+ if state.status in (RequestStatus.FINISHED, RequestStatus.PENDING):
412
+ if self.use_async_batching:
413
+ # Skip this request, but still consume its token from new_tokens if it had one
414
+ if future_state.has_new_token:
415
+ current_logits_index += 1
416
+ continue
417
+ raise RuntimeError(f"Tried to update {state.status.name} request {state.request_id} in sync mode.")
418
+ # If the request has a new token, it means prefill has already ended or just finished
419
+ if future_state.has_new_token:
420
+ # If there is just one temporary token, it means prefill just ended
421
+ if state.generated_len() == 0:
422
+ self.metrics.record_ttft_metric(state.created_time, state.request_id)
423
+ state.status = RequestStatus.DECODING
424
+
425
+ token = new_tokens[current_logits_index]
426
+ logprob = logprobs[current_logits_index] if logprobs is not None else None
427
+ current_logits_index += 1
428
+
429
+ # Update the request and stop if it is complete
430
+ is_finished = state.update_and_check_completion(token, logprob)
431
+ # We mark the completed blocks as such
432
+ self.cache.mark_shareable_blocks_as_complete(state, future_state.complete_blocks)
433
+ if is_finished:
434
+ self.metrics.record_request_completion(state.created_time, state.request_id)
435
+ self.scheduler.finish_request(state.request_id)
436
+ self.scheduler.block_new_requests = False
437
+ if state.streaming or state.status == RequestStatus.FINISHED:
438
+ pending_outputs.append(state.to_generation_output())
439
+ # Otherwise, the request is still prefilling, but the prefill has been split
440
+ elif state.status == RequestStatus.PREFILLING:
441
+ self.cache.mark_shareable_blocks_as_complete(state, future_state.complete_blocks)
442
+
443
+ if pending_outputs:
444
+ self.output_router.deliver_batch(pending_outputs)
445
+
446
+ # If some requests need to be forked, we do it now
447
+ copy_source, copy_destination = [], []
448
+ while self.scheduler._requests_to_fork:
449
+ # Get the number of children and reset it so it's not forked again
450
+ state_to_fork = self.scheduler._requests_to_fork.pop()
451
+ num_children = state_to_fork.num_children
452
+ state_to_fork.num_children = 0
453
+ # Create the new request and add them to the scheduler
454
+ new_request_ids = [f"{state_to_fork.request_id}__child#{i}" for i in range(num_children)]
455
+ for new_request_id in new_request_ids:
456
+ self.scheduler.active_requests[new_request_id] = state_to_fork.fork(new_request_id)
457
+ # Fork the cache
458
+ copy_src, copy_dst = self.cache.fork_request(state_to_fork.request_id, new_request_ids)
459
+ copy_source.extend(copy_src)
460
+ copy_destination.extend(copy_dst)
461
+ # FIXME: if fork cant be done, create a new pending request without forking instead of crashing everything
462
+
463
+ # The copy induced by the fork is done in one go (if it's even needed)
464
+ if copy_source:
465
+ # FIXME: this will avoid any race condition, but it can cause issue when using async batching with a sliding
466
+ # window model. Fix will be fixed in a PR in the near future (tempfix, v5.3)
467
+ compute_stream = self.inputs_and_outputs.compute_stream
468
+ maybe_stream = torch.cuda.stream(compute_stream) if compute_stream is not None else nullcontext()
469
+ with maybe_stream:
470
+ self.cache.copy_cache(copy_source, copy_destination)
471
+
472
+ @traced
473
+ def has_pending_requests(self) -> bool:
474
+ """Check if there are any active or waiting requests."""
475
+ return self.scheduler.has_pending_requests()
476
+
477
+ @traced
478
+ def handle_batch_error(self, error):
479
+ """Handle errors during batch processing."""
480
+ failed_future_states = self.inputs_and_outputs.prepare_batch_update()[0]
481
+ for future_state in failed_future_states:
482
+ self._handle_request_error(error, future_state.state)
483
+ self.scheduler.finish_request(future_state.state.request_id)
484
+
485
+ @traced
486
+ def fail_all_requests(self, error: Exception) -> None:
487
+ """Fail all active requests with the given error."""
488
+
489
+ requests = list(self.scheduler.active_requests.values())
490
+ for state in requests:
491
+ self._handle_request_error(error, state)
492
+ self.scheduler.finish_request(state.request_id)
493
+
494
+ # Also fail any requests in the waiting queue
495
+ self.offloading_manager.free_all_waiting_cpu_caches()
496
+ for req_id in list(self.scheduler.waiting_requests.keys()):
497
+ state = self.scheduler.waiting_requests.pop(req_id)
498
+ self._handle_request_error(error, state)
499
+
500
+ # Clear the ordering queue
501
+ self.scheduler.waiting_requests_order.clear()
502
+
503
+ @traced
504
+ @torch.no_grad()
505
+ def _generation_step(self, model: nn.Module) -> None:
506
+ """Perform a single generation step."""
507
+
508
+ # Retrieve the model kwargs with or without padding
509
+ batch_data = self.inputs_and_outputs.get_model_kwargs(use_padding=self._pad_inputs)
510
+ carry_over_ids, prev_output_ids, output_ids = self.inputs_and_outputs.get_cb_kwargs()
511
+ compute_stream = self.inputs_and_outputs.compute_stream
512
+
513
+ # Get the appropriate forward function (compiled or not, based on current path)
514
+ if self.inputs_and_outputs.use_block_table:
515
+ forward_fn = self._forward_process_and_sample if self._compiled_decode is None else self._compiled_decode
516
+ use_cuda_graph = self.use_cuda_graph_decode
517
+ else:
518
+ forward_fn = self._forward_process_and_sample if self._compiled_varlen is None else self._compiled_varlen
519
+ use_cuda_graph = self.use_cuda_graph_varlen
520
+
521
+ # If we are not using cuda graphs, we perform the generation step and return
522
+ if not use_cuda_graph:
523
+ maybe_stream = torch.cuda.stream(compute_stream) if compute_stream is not None else nullcontext()
524
+ with maybe_stream:
525
+ forward_fn(model, batch_data, carry_over_ids, prev_output_ids, output_ids)
526
+
527
+ # Otherwise, we use create or replay the graph (cuda is available in this path)
528
+ else:
529
+ graph = self.inputs_and_outputs.get_graph()
530
+ # Case: the graph already exists, so we replay it
531
+ if graph is not None:
532
+ with torch.cuda.stream(compute_stream):
533
+ graph.replay()
534
+ # Otherwise, the graph does not exist, so we create it
535
+ else:
536
+ args = (model, batch_data, carry_over_ids, prev_output_ids, output_ids)
537
+ self.capture_graph(forward_fn, compute_stream, *args)
538
+
539
+ # In any case, we transfer the outputs to the host
540
+ self.inputs_and_outputs.retrieve_device_outputs()
541
+
542
+ def capture_graph(self, forward_fn: Any, compute_stream: torch.cuda.Stream, *args) -> None:
543
+ # Warmup (ensures the right result is computed before capturing the graph)
544
+ with torch.cuda.stream(compute_stream):
545
+ forward_fn(*args)
546
+ # Capture
547
+ graph = torch.cuda.CUDAGraph()
548
+ # Continuous batching can run multiple manager threads concurrently in one process, but PyTorch's
549
+ # default capture mode ("global") errors on CUDA actions from other threads. This means capture can be
550
+ # invalidated even when each manager uses a different device. To avoid this, we use "thread_local" mode.
551
+ with torch.cuda.graph(graph, stream=compute_stream, pool=self.graph_pool, capture_error_mode="thread_local"):
552
+ forward_fn(*args)
553
+ # Store
554
+ self.inputs_and_outputs.set_graph(graph)
555
+
556
+ @traced
557
+ def _forward_process_and_sample(
558
+ self,
559
+ model: nn.Module,
560
+ batch_data: dict,
561
+ carry_over_ids: torch.Tensor,
562
+ prev_output_ids: torch.Tensor,
563
+ output_ids: torch.Tensor,
564
+ ) -> None:
565
+ """This function performs the forward pass, logits processing, and sampling; which are broken down into smaller
566
+ function to be easier to trace with OpenTelemetry."""
567
+ self.inputs_and_outputs.carry_over_tokens(batch_data["input_ids"], carry_over_ids, prev_output_ids)
568
+ logits = self._model_forward(model, batch_data).float() # convert to fp32 to match generate
569
+ scores = self._process_logit(batch_data, logits) if self.logit_processor.do_processing else logits
570
+ self._sample(scores, batch_data["logits_indices"], output_ids)
571
+
572
+ @traced(span_name="model_forward")
573
+ def _model_forward(self, model: nn.Module, batch_data: dict) -> torch.Tensor:
574
+ return model(**batch_data).logits
575
+
576
+ @traced(span_name="logit_processing")
577
+ def _process_logit(self, batch_data: dict, logits: torch.Tensor) -> torch.Tensor:
578
+ # Handle shape compatibility: logit processors expect 2D tensors [batch_size, vocab_size]
579
+ # but continuous batching always produces 3D tensors [batch_size, seq_len, vocab_size]
580
+ batch_size, seq_len, vocab_size = logits.shape
581
+ logits_2d = logits.view(batch_size * seq_len, vocab_size)
582
+ input_ids_2d = batch_data["input_ids"].view(batch_size * seq_len)
583
+ # Process with 2D tensors
584
+ processed_logits_2d = self.logit_processor(input_ids_2d, logits_2d, batch_data["logits_processor_args"])
585
+ # Reshape back to 3D
586
+ return processed_logits_2d.view(batch_size, seq_len, vocab_size)
587
+
588
+ @traced(span_name="sampling")
589
+ def _sample(self, scores: torch.Tensor, logits_indices: torch.Tensor, output_ids: torch.Tensor) -> None:
590
+ # Apply softmax if we are sampling or if we are generating log probabilities
591
+ if self.do_sample or self.return_logprobs:
592
+ probs = nn.functional.softmax(scores[0], dim=-1) # shape [seq_len, vocab_size]
593
+ # Otherwise just remove the batch size dimension, which is always 1
594
+ else:
595
+ probs = scores.squeeze(0) # shape [seq_len, vocab_size]
596
+
597
+ # Retrieve next tokens through sampling or argmax
598
+ if self.do_sample:
599
+ next_tokens = torch.multinomial(probs, num_samples=1) # shape [seq_len, 1]
600
+ else:
601
+ next_tokens = torch.argmax(probs, dim=-1, keepdim=True) # shape [seq_len, 1]
602
+
603
+ # Maybe retrieve log probabilities
604
+ if self.return_logprobs:
605
+ per_token_probs = probs.gather(dim=1, index=next_tokens).squeeze(-1)
606
+ logprobs = per_token_probs.log() # shape [seq_len]
607
+ # And always remove the extra dimension for the gather
608
+ next_tokens = next_tokens.squeeze(-1) # shape [seq_len]
609
+
610
+ # Get seq_len dimension to slice the logits indices
611
+ tokens = next_tokens.size(0)
612
+ # Shuffle the next tokens to match the order of the batch's requests
613
+ indices = logits_indices[:tokens]
614
+ next_tokens = next_tokens[indices]
615
+ # Copy the next tokens and maybe their logprobs to the static output tensor
616
+ output_ids[0, :tokens].copy_(next_tokens)
617
+ if self.return_logprobs:
618
+ # Shuffle the logprobs the same way as the next tokens
619
+ logprobs = logprobs[indices]
620
+ # In order to match the dtype of output_ids, we cast the fp32 logprobs as int32 without changing the
621
+ # underlying data. It's just a trick to use the same storage for both tensors.
622
+ output_ids[1, :tokens].copy_(logprobs.view(dtype=torch.int32))
623
+
624
+ @torch.inference_mode()
625
+ def warmup(self, model: nn.Module) -> None:
626
+ """Pre-capture CUDA graphs (or trigger compile warmup) for varlen and decode paths. In async mode, both IO
627
+ pairs are warmed up since each has its own graph buffer and static tensors. The varlen path is warmed up at
628
+ the largest possible `(q, kv)` sizes so subsequent captures fit inside it without growing the pool."""
629
+
630
+ if not self._pad_inputs:
631
+ logger.info("CUDA graphs and compile are disabled, skipping warmup.")
632
+ return None
633
+
634
+ num_query_tokens = self.max_batch_tokens
635
+ num_pages = self.cache.num_blocks * self.cache.block_size
636
+ num_cache_tokens = num_pages - num_query_tokens
637
+ compute_stream = self.inputs_and_outputs.compute_stream
638
+
639
+ # In async mode, each IO pair has its own graph buffer and static tensors, so we warm up both
640
+ num_io_pairs = 2 if self.use_async_batching else 1
641
+
642
+ for pair_idx in range(num_io_pairs):
643
+ if self.use_async_batching:
644
+ self.inputs_and_outputs.current_pair = pair_idx
645
+ logger.info(f"Warming up IO pair {pair_idx + 1}/2...")
646
+
647
+ # --- Varlen path ---
648
+ padded_q, padded_kv = self.maybe_pad_inputs(
649
+ num_q_tokens=num_query_tokens,
650
+ max_kv_read=num_cache_tokens + num_query_tokens,
651
+ use_decode_fast_path=False,
652
+ )
653
+ logger.info(f"Warming up varlen path ({padded_q} Q tokens, {padded_kv} KV tokens)...")
654
+
655
+ future_states = create_warmup_future_states(
656
+ 1, RequestStatus.PREFILLING, num_query_tokens, num_cache_tokens, self.cache
657
+ )
658
+ try:
659
+ start = perf_counter()
660
+ self.inputs_and_outputs.prepare_batch_tensors(
661
+ future_states, self.logit_processor, False, padded_q, padded_kv - padded_q
662
+ )
663
+ batch_data = self.inputs_and_outputs.get_model_kwargs(use_padding=True)
664
+ carry_over_ids, prev_output_ids, output_ids = self.inputs_and_outputs.get_cb_kwargs()
665
+ forward_fn = self._compiled_varlen or self._forward_process_and_sample
666
+ forward_fn_args = (model, batch_data, carry_over_ids, prev_output_ids, output_ids)
667
+ if self.use_cuda_graph_varlen:
668
+ self.capture_graph(forward_fn, compute_stream, *forward_fn_args)
669
+ else:
670
+ with torch.cuda.stream(compute_stream):
671
+ forward_fn(*forward_fn_args)
672
+ logger.info(f"Varlen warmup completed in {perf_counter() - start:.2f}s")
673
+ except Exception as e:
674
+ logger.warning(f"Failed to warm up varlen path: {e}. Graph pool may fragment and OOM under load.")
675
+ finally:
676
+ for fs in future_states:
677
+ self.cache.free_blocks(fs.state.request_id)
678
+
679
+ # Exit here if the decode fast path is not available
680
+ if self.cache.max_blocks_per_request == 0:
681
+ continue
682
+
683
+ # --- Decode fast path ---
684
+ logger.info("Warming up decode fast path...")
685
+ decode_graphs = 0
686
+ start = perf_counter()
687
+
688
+ num_requests = 1
689
+ while True:
690
+ future_states = create_warmup_future_states(
691
+ num_requests, RequestStatus.DECODING, 1, self.cache.block_size, self.cache
692
+ )
693
+ if not future_states:
694
+ break
695
+ try:
696
+ padded_q, _ = self.maybe_pad_inputs(
697
+ num_q_tokens=num_requests, max_kv_read=0, use_decode_fast_path=True
698
+ )
699
+ self.inputs_and_outputs.prepare_batch_tensors(
700
+ future_states, self.logit_processor, True, padded_q, 0
701
+ )
702
+ batch_data = self.inputs_and_outputs.get_model_kwargs(use_padding=True)
703
+ carry_over_ids, prev_output_ids, output_ids = self.inputs_and_outputs.get_cb_kwargs()
704
+ forward_fn = self._compiled_decode or self._forward_process_and_sample
705
+ forward_fn_args = (model, batch_data, carry_over_ids, prev_output_ids, output_ids)
706
+ if self.use_cuda_graph_decode:
707
+ self.capture_graph(forward_fn, compute_stream, *forward_fn_args)
708
+ else:
709
+ with torch.cuda.stream(compute_stream):
710
+ forward_fn(*forward_fn_args)
711
+ decode_graphs += 1
712
+ except Exception as e:
713
+ logger.warning(f"Failed to warm up decode path for {num_requests} requests: {e}")
714
+ finally:
715
+ for fs in future_states:
716
+ self.cache.free_blocks(fs.state.request_id)
717
+ if num_requests >= self.max_batch_tokens:
718
+ break
719
+ num_requests = min(2 * num_requests, self.max_batch_tokens)
720
+ logger.info(f"Decode warmup completed ({decode_graphs} graphs) in {perf_counter() - start:.2f}s.")
721
+
722
+ # If using async batching, reset to pair 0 for the generation loop
723
+ if self.use_async_batching:
724
+ self.inputs_and_outputs.current_pair = 0
725
+
726
+
727
+ # Manager Class (User Interface)
728
+ @attach_tracer()
729
+ class ContinuousBatchingManager:
730
+ """Manager for handling continuous batching of generation requests. It provides a user interface for submitting
731
+ generation requests, retrieving results, and managing the background generation thread. This class should not be
732
+ created directly, but through one of the following entry points (all methods of the `ContinuousMixin` mixin):
733
+ - `init_continuous_batching`
734
+ - `continuous_batching_context_manager`
735
+ - `generate_batch`
736
+ """
737
+
738
+ def __init__(
739
+ self,
740
+ model: ProtoPretrainedModel,
741
+ generation_config: GenerationConfig,
742
+ continuous_batching_config: ContinuousBatchingConfig,
743
+ ) -> None:
744
+ """Initialize the continuous batching manager.
745
+
746
+ Args:
747
+ model: The language model for generation
748
+ generation_config: Configuration for generation parameters
749
+ continuous_batching_config: Configuration for continuous batching parameters
750
+ """
751
+ # Reload paged version of the attention implementation if necessary
752
+ if "paged|" not in model.config._attn_implementation:
753
+ model.set_attn_implementation(f"paged|{model.config._attn_implementation}")
754
+
755
+ # Internal arguments
756
+ self.model = model.eval()
757
+ self.generation_config = generation_config
758
+ self.continuous_batching_config = continuous_batching_config
759
+ self.warmed_up = False # Set to True after warmup is completed. Useful for persistent managers.
760
+ # This is an approximation until the cache is created: it will infer the correct value in cache.__init__
761
+ self._use_prefix_sharing = self.continuous_batching_config.allow_block_sharing
762
+
763
+ self.input_queue = queue.Queue(maxsize=self.continuous_batching_config.max_queue_size)
764
+ self._has_new_requests = threading.Event()
765
+ self.output_router = OutputRouter()
766
+ self.stop_event = threading.Event()
767
+ self.batch_processor: ContinuousBatchProcessor | None = None
768
+ self._generation_thread = None
769
+ self._request_counter = 0
770
+ self._request_lock = threading.Lock()
771
+ self.fatal_error: Exception | None = None
772
+
773
+ # Generation config related arguments
774
+ num_return_sequences = getattr(generation_config, "num_return_sequences", None)
775
+ self.num_return_sequences = num_return_sequences if num_return_sequences is not None else 1
776
+
777
+ self.logit_processor = ContinuousBatchingLogitsProcessorList(
778
+ logits_processor=self.model._get_logits_processor(generation_config),
779
+ per_request_processors=self.continuous_batching_config.per_request_processors,
780
+ drop_unsupported_processors=self.continuous_batching_config.drop_unsupported_processors,
781
+ )
782
+
783
+ # Cuda graph behavior is determined below using either user-specified arguments or heuristics
784
+ is_attn_mask_needed = attn_mask_is_needed(self.model.config)
785
+ self.continuous_batching_config.decide_use_cuda_graphs(
786
+ compile_config=getattr(generation_config, "compile_config", None),
787
+ is_attn_mask_needed=is_attn_mask_needed,
788
+ )
789
+ # Same for asynchronous batching behavior
790
+ self.use_async_batching = self.continuous_batching_config.decide_use_async_batching(is_attn_mask_needed)
791
+
792
+ # Resolve default parameters for Q and KV interval sizes, and max cached graphs. If one of those parameters is
793
+ # not specified (set to 0) then we use the default value and change its value in the config.
794
+ self.continuous_batching_config.resolve_sentinel_values()
795
+ self.q_padding_interval_size = self.continuous_batching_config.q_padding_interval_size
796
+ self.kv_padding_interval_size = self.continuous_batching_config.kv_padding_interval_size
797
+ self.max_cached_graphs = self.continuous_batching_config.max_cached_graphs
798
+
799
+ @traced
800
+ def start(self) -> None:
801
+ """Start the background generation thread."""
802
+ if self._generation_thread is not None and self._generation_thread.is_alive():
803
+ logger.warning("Manager thread is already running.")
804
+ return
805
+ self.stop_event.clear()
806
+ self.fatal_error = None
807
+ self._generation_thread = threading.Thread(target=self._run_generation_loop)
808
+ self._generation_thread.start()
809
+
810
+ def is_running(self) -> bool:
811
+ """Check if the background generation thread is running."""
812
+ return self._generation_thread is not None and self._generation_thread.is_alive()
813
+
814
+ def warmup(self) -> None:
815
+ """Pre-capture CUDA graphs for varlen and decode paths by running dummy batches. Initializes the batch
816
+ processor if not already done."""
817
+ if self.batch_processor is None:
818
+ self.batch_processor = self._create_batch_processor()
819
+ self.batch_processor.warmup(self.model)
820
+ self.warmed_up = True
821
+
822
+ # NOTE: don't forget to update `continuous_batching_context_manager` when changing this method's definition
823
+ def stop(self, block: bool = True, timeout: float | None = None, keep_for_next_session: bool = False) -> None:
824
+ """Signal the background thread to stop.
825
+
826
+ Args:
827
+ block: Whether to wait for the thread to stop
828
+ timeout: Maximum time to wait for the thread to stop
829
+ keep_for_next_session: Whether to cache this on the model for future use
830
+ """
831
+ if self.batch_processor is None:
832
+ logger.warning("\nBatch processor was not initialized.")
833
+ elif self.batch_processor.cache.use_prefix_sharing:
834
+ logger.info(
835
+ f"\nPrefix sharing was on. Total prefix length: {self.batch_processor.cache._total_prefix_length}"
836
+ )
837
+
838
+ if self._generation_thread is None:
839
+ suffix = " Hence the unstarted manager will not be kept for next session." if keep_for_next_session else ""
840
+ logger.warning("Manager not started." + suffix)
841
+ return
842
+
843
+ stop_trigger_time = perf_counter()
844
+ if not self.stop_event.is_set():
845
+ self.stop_event.set()
846
+ logger.info("Stopping continuous batching manager...")
847
+
848
+ if block:
849
+ self.join(stop_trigger_time, timeout)
850
+
851
+ # If the manager is not being kept for next session, we clear the batch processor
852
+ if not keep_for_next_session:
853
+ self.batch_processor = None
854
+ # Otherwise, we keep the batch processor and cache the manager as a model attribute
855
+ else:
856
+ logger.info("Continuous batching manager will be kept for next session.")
857
+ self.model._cached_continuous_batching_manager = self
858
+ # In all cases, a little cleanup is good
859
+ gc.collect()
860
+ if torch.cuda.is_available():
861
+ torch.cuda.empty_cache()
862
+
863
+ def join(self, stop_trigger_time: float, timeout: float | None = None) -> None:
864
+ """Wait for the background thread to finish.
865
+
866
+ Args:
867
+ timeout: Maximum time to wait for the thread to stop
868
+ """
869
+ if self._generation_thread is not None:
870
+ self._generation_thread.join(timeout=timeout)
871
+ if self._generation_thread.is_alive():
872
+ logger.warning(f"Generation thread did not exit after join timeout ({timeout}).")
873
+ else:
874
+ end = perf_counter()
875
+ logger.info(f"Continuous Batching Manager stopped after {end - stop_trigger_time:.2f}s.")
876
+ self._generation_thread = None
877
+
878
+ def add_request(
879
+ self,
880
+ input_ids: list[int],
881
+ request_id: str | None = None,
882
+ max_new_tokens: int | None = None,
883
+ streaming: bool = False,
884
+ record_timestamps: bool = False,
885
+ eos_token_id: int | list[int] | None = None,
886
+ **logit_processor_kwargs: Any,
887
+ ) -> str:
888
+ """Add a new generation request to the queue.
889
+
890
+ Args:
891
+ input_ids: Input token IDs to use as prompt
892
+ request_id: Optional custom request ID (auto-generated if None)
893
+ max_new_tokens: Maximum number of new tokens to generate
894
+ streaming: Whether to stream tokens as they're generated
895
+ record_timestamps: Whether to record timestamps for each generated token
896
+ eos_token_id: End-of-sequence token ID(s)
897
+ logit_processor_kwargs: Keyword arguments for the logits processor.
898
+
899
+ Returns:
900
+ str: The request ID
901
+ """
902
+ if request_id is None:
903
+ with self._request_lock:
904
+ request_id = f"req_{self._request_counter}"
905
+ self._request_counter += 1
906
+
907
+ max_new_tokens = self.generation_config.max_new_tokens if max_new_tokens is None else max_new_tokens
908
+ eos_token_id = self.generation_config.eos_token_id if eos_token_id is None else eos_token_id
909
+
910
+ # NOTE: do we want to handle a case when the user wants token ids returned instead of decoded text?
911
+ state = RequestState(
912
+ request_id=request_id,
913
+ initial_tokens=list(input_ids),
914
+ num_children=self.num_return_sequences - 1,
915
+ record_timestamps=record_timestamps,
916
+ max_new_tokens=max_new_tokens,
917
+ eos_token_id=eos_token_id,
918
+ streaming=streaming,
919
+ logit_processor_kwargs=logit_processor_kwargs,
920
+ )
921
+
922
+ # Use block=True with timeout to handle backpressure if queue is full
923
+ self.input_queue.put(state, block=True, timeout=10)
924
+ self._has_new_requests.set()
925
+ return request_id
926
+
927
+ def add_requests(
928
+ self,
929
+ inputs: list[list[int]],
930
+ max_new_tokens: int | None = None,
931
+ streaming: bool = False,
932
+ record_timestamps: bool = False,
933
+ **logit_processor_kwargs: Any,
934
+ ) -> None:
935
+ # Infer the request ids of all incoming requests
936
+ with self._request_lock:
937
+ request_ids = [f"req_{i}" for i in range(self._request_counter, self._request_counter + len(inputs))]
938
+ self._request_counter += len(inputs)
939
+ # If there is prefix sharing, we sort the inputs to maximize cache hits but keep the order of the requests
940
+ ids_and_inputs = list(zip(request_ids, inputs))
941
+ if self._use_prefix_sharing:
942
+ ids_and_inputs = sorted(ids_and_inputs, key=lambda x: x[1], reverse=True)
943
+ # Look for an EOS token ID in the generation config and then in the model config. If no EOS is found, we set it
944
+ # to -1 to avoid looking for it in each add_request call
945
+ eos_token_id = self.generation_config.eos_token_id
946
+ eos_token_id = self.model.config.eos_token_id if eos_token_id is None else eos_token_id
947
+ eos_token_id = -1 if eos_token_id is None else eos_token_id
948
+ # Add requests in order
949
+ for request_id, input_ids in ids_and_inputs:
950
+ self.add_request(
951
+ input_ids=input_ids,
952
+ request_id=request_id,
953
+ max_new_tokens=max_new_tokens,
954
+ streaming=streaming,
955
+ record_timestamps=record_timestamps,
956
+ eos_token_id=eos_token_id,
957
+ **logit_processor_kwargs,
958
+ )
959
+
960
+ def cancel_request(self, request_id: str) -> None:
961
+ """Cancel a request by its ID.
962
+
963
+ Args:
964
+ request_id: The ID of the request to cancel
965
+ """
966
+ if self.batch_processor is not None:
967
+ self.batch_processor.scheduler.set_request_cancellation(request_id)
968
+
969
+ # TODO:handle benchmarking properly when updating / fixing the requeue logic
970
+ def get_result(self, request_id: str | None = None, timeout: float | None = None) -> GenerationOutput | None:
971
+ """Retrieve one result from the output queue.
972
+
973
+ Args:
974
+ request_id: If set, only return results matching this ID (others are requeued).
975
+ timeout: Maximum time to wait for a result.
976
+
977
+ Returns:
978
+ Optional[GenerationOutput]: The result data or None if timeout.
979
+ """
980
+ if self._generation_thread is None and self.output_router.output_queue.empty():
981
+ return None
982
+ try:
983
+ result = self.output_router.output_queue.get(block=True, timeout=timeout)
984
+ if request_id is not None and result.request_id != request_id:
985
+ self.output_router.output_queue.put(result)
986
+ return None
987
+ return result
988
+ except queue.Empty:
989
+ return None
990
+
991
+ def __iter__(self):
992
+ """Iterate over results as they become available."""
993
+ while self._generation_thread is not None and self._generation_thread.is_alive():
994
+ result = self.get_result(timeout=0.1)
995
+ if result is not None:
996
+ yield result
997
+
998
+ def request_id_iter(self, request_id: str) -> Generator[GenerationOutput]:
999
+ """Iterate over results matching a specific request id (blocking).
1000
+
1001
+ Uses the shared output queue with requeue. For high-concurrency serving,
1002
+ use :meth:`register_result_handler` instead.
1003
+ """
1004
+ while self._generation_thread is not None and self._generation_thread.is_alive():
1005
+ result = self.get_result(request_id=request_id, timeout=0.1)
1006
+ if result is not None:
1007
+ yield result
1008
+ if result.is_finished():
1009
+ return
1010
+
1011
+ def register_result_handler(self, request_id: str, callback: Callable) -> None:
1012
+ """Register a callback for result delivery (streaming or non-streaming).
1013
+
1014
+ The callback is invoked on the event loop via ``call_soon_threadsafe``
1015
+ each time a result is produced for this request. For streaming requests,
1016
+ this happens on every token; for non-streaming, only on completion.
1017
+
1018
+ The handler is automatically cleaned up when the request finishes.
1019
+
1020
+ Args:
1021
+ request_id (`str`): The request ID to receive outputs for.
1022
+ callback (`callable`): Called with a ``GenerationOutput`` for each result.
1023
+ """
1024
+ loop = asyncio.get_running_loop()
1025
+
1026
+ def _auto_cleanup(result):
1027
+ callback(result)
1028
+ if result.is_finished():
1029
+ with self.output_router._lock:
1030
+ self.output_router.result_handlers.pop(request_id, None)
1031
+
1032
+ with self.output_router._lock:
1033
+ self.output_router.result_handlers[request_id] = (_auto_cleanup, loop)
1034
+
1035
+ @traced
1036
+ def _generation_step(self) -> None:
1037
+ """Perform a single generation step. This is mostly cuda graphed"""
1038
+ if self.batch_processor is None:
1039
+ raise RuntimeError("Tried to perform a generation step before the batch processor was initialized.")
1040
+ self.batch_processor._generation_step(self.model)
1041
+
1042
+ def _create_batch_processor(self) -> ContinuousBatchProcessor:
1043
+ # Resolve max_memory_percent now that we know whether any logit processors are active.
1044
+ self.continuous_batching_config.resolve_max_memory_percent(self.logit_processor.do_processing)
1045
+ # Create the PagedAttentionCache
1046
+ paged_attention_cache = PagedAttentionCache(
1047
+ self.model.config,
1048
+ self.continuous_batching_config,
1049
+ self.model.device,
1050
+ self.model.dtype,
1051
+ tp_size=getattr(self.model, "_tp_size", None), # Use model's actual TP setting
1052
+ )
1053
+ self._use_prefix_sharing = paged_attention_cache.use_prefix_sharing # update the approximation
1054
+
1055
+ # Create the scheduler
1056
+ scheduler_type = self.continuous_batching_config.scheduler_type
1057
+ scheduler = SCHEDULER_MAPPING.get(scheduler_type, None)
1058
+ if scheduler is None:
1059
+ logger.warning(f"Scheduler '{scheduler_type}' not found. Defaulting to FIFO.")
1060
+ scheduler = FIFOScheduler
1061
+
1062
+ # Create the batch processor
1063
+ batch_processor = ContinuousBatchProcessor(
1064
+ cache=paged_attention_cache,
1065
+ config=self.model.config,
1066
+ generation_config=self.generation_config,
1067
+ continuous_batching_config=self.continuous_batching_config,
1068
+ logit_processor=self.logit_processor,
1069
+ input_queue=self.input_queue,
1070
+ output_router=self.output_router,
1071
+ stop_event=self.stop_event,
1072
+ model_device=self.model.device,
1073
+ model_dtype=self.model.dtype,
1074
+ scheduler=scheduler(paged_attention_cache),
1075
+ )
1076
+ return batch_processor
1077
+
1078
+ @torch.inference_mode()
1079
+ def _run_generation_loop(self) -> None:
1080
+ """Main processing loop running in the background thread."""
1081
+ try:
1082
+ # Try to retrieve an already initialized batch processor
1083
+ batch_processor = getattr(self, "batch_processor", None)
1084
+ # If the batch processor already exists, we just reset it for a new generation loop
1085
+ if isinstance(batch_processor, ContinuousBatchProcessor):
1086
+ batch_processor.reset()
1087
+ # Otherwise, we create a new batch processor
1088
+ else:
1089
+ batch_processor = self._create_batch_processor()
1090
+
1091
+ # Start the generation loop
1092
+ self.batch_processor = batch_processor
1093
+ self.current_batch = 0
1094
+
1095
+ # If using the async API, we bootstrap the first batch w/out update
1096
+ if batch_processor.use_async_batching:
1097
+ if not batch_processor.prepare_next_batch():
1098
+ raise RuntimeError("Failed to bootstrap the first batch.")
1099
+ self._generation_step()
1100
+ self.current_batch += 1
1101
+
1102
+ while (not self.stop_event.is_set()) or batch_processor.has_pending_requests():
1103
+ self._inner_generation_loop(batch_processor)
1104
+ self.current_batch += 1
1105
+
1106
+ # In async mode, the last batch's results are still in flight - process them now
1107
+ # We need to switch back to the pair that has the last batch's D2H pending
1108
+ if isinstance(batch_processor.inputs_and_outputs, ContinuousBatchingAsyncIOs):
1109
+ batch_processor.inputs_and_outputs.current_pair = 1 - batch_processor.inputs_and_outputs.current_pair
1110
+ batch_processor.update_batch()
1111
+
1112
+ except Exception as e:
1113
+ logger.error(f"Error in generation loop: {e}", exc_info=True)
1114
+ self._handle_critical_error(e, batch_processor)
1115
+ finally:
1116
+ logger.info("Generation loop finished.")
1117
+
1118
+ @traced(span_name="generation_loop")
1119
+ def _inner_generation_loop(self, batch_processor: ContinuousBatchProcessor) -> None:
1120
+ # Loop body ends if there is no requests in the batch
1121
+ if not batch_processor.prepare_next_batch():
1122
+ # Wait for new requests instead of busy-spinning.
1123
+ self._has_new_requests.wait(timeout=0.1)
1124
+ self._has_new_requests.clear()
1125
+ return
1126
+ self._generation_step()
1127
+ batch_processor.update_batch()
1128
+
1129
+ @traced
1130
+ def _handle_critical_error(self, error: Exception, batch_processor: ContinuousBatchProcessor | None) -> None:
1131
+ """Handle critical errors that terminate the generation loop."""
1132
+ # Record so callers (e.g. the serving layer) can fail fast on subsequent requests
1133
+ # instead of enqueuing into a worker that will never drain.
1134
+ self.fatal_error = error
1135
+ # Signal stop
1136
+ self.stop_event.set()
1137
+
1138
+ # Fail pending requests in input queue
1139
+ try:
1140
+ while True:
1141
+ req_data = self.input_queue.get_nowait()
1142
+ if batch_processor is not None:
1143
+ batch_processor._handle_request_error(error, req_data)
1144
+ except queue.Empty:
1145
+ pass
1146
+
1147
+ # Fail active requests
1148
+ if batch_processor is not None:
1149
+ batch_processor.fail_all_requests(error)
1150
+
1151
+
1152
+ class ContinuousMixin:
1153
+ """Mixin class for models to add continuous batching capabilities. Continuous batching has three entry points:
1154
+ - `init_continuous_batching`, which is the actual entry point for continuous batching
1155
+ - `continuous_batching_context_manager`, which itself is a wrapper around `init_continuous_batching`
1156
+ - `generate_batch`, which is really a wrapper around `continuous_batching_context_manager`
1157
+
1158
+ They are defined in this order. Any change made to any of those three entry points should be reflected in the other
1159
+ two.
1160
+ """
1161
+
1162
+ generation_config: GenerationConfig
1163
+
1164
+ @torch.inference_mode()
1165
+ def init_continuous_batching(
1166
+ self,
1167
+ generation_config: GenerationConfig | None = None,
1168
+ continuous_batching_config: ContinuousBatchingConfig | None = None,
1169
+ workload_hints: WorkloadHints | None = None,
1170
+ **deprecated_kwargs,
1171
+ ) -> ContinuousBatchingManager:
1172
+ """Initialize a manager for continuous batching inference.
1173
+
1174
+ Args:
1175
+ generation_config: An optional generation configuration, which may contain a CompileConfig object
1176
+ continuous_batching_config: An optional continuous batching configuration
1177
+ workload_hints: Optional WorkloadHints to help the continuous batching manager make better decisions for
1178
+ default values
1179
+ **deprecated_kwargs: Deprecated arguments that are now passed in the continuous_batching_config. Those are:
1180
+ max_queue_size, q_padding_interval_size, kv_padding_interval_size, allow_block_sharing,
1181
+ use_async_batching, max_cached_graphs
1182
+ Returns:
1183
+ `ContinuousBatchingManager`: The manager instance to add requests and retrieve results.
1184
+ """
1185
+ # Mandatory attributes
1186
+ if not hasattr(self, "config") or not hasattr(self, "device") or not hasattr(self, "dtype"):
1187
+ raise AttributeError("Model must have 'config', 'device', and 'dtype' attributes.")
1188
+
1189
+ # If a persistent manager is found we return it
1190
+ cached_manager = getattr(self, "_cached_continuous_batching_manager", None)
1191
+ if isinstance(cached_manager, ContinuousBatchingManager):
1192
+ logger.info(
1193
+ "Cached continuous batching manager found: it will be re-used instead of creating a new one. If you"
1194
+ " want to create a new manager, you should call `destroy_cached_continuous_batching_manager` first."
1195
+ )
1196
+ return cached_manager
1197
+
1198
+ # Retrieve generation config
1199
+ gen_config = generation_config if generation_config is not None else self.generation_config
1200
+ if gen_config is None:
1201
+ raise ValueError("A GenerationConfig must be provided or set in the model.")
1202
+ # Warn about EOS
1203
+ if gen_config.eos_token_id is None:
1204
+ logger.warning("`eos_token_id` not set in GenerationConfig. Setting to -1 (disabled).")
1205
+ gen_config.eos_token_id = -1
1206
+
1207
+ # Retrieve continuous batching config, or create it if none is provided
1208
+ if continuous_batching_config is None:
1209
+ if isinstance(getattr(gen_config, "continuous_batching_config", None), ContinuousBatchingConfig):
1210
+ continuous_batching_config = gen_config.continuous_batching_config
1211
+ else:
1212
+ continuous_batching_config = ContinuousBatchingConfig()
1213
+ continuous_batching_config.account_for_cb_deprecated_arguments(**deprecated_kwargs)
1214
+ if workload_hints is not None:
1215
+ workload_hints.resolve_using_hints(continuous_batching_config)
1216
+
1217
+ # Create and return the manager
1218
+ return ContinuousBatchingManager(
1219
+ model=self, generation_config=gen_config, continuous_batching_config=continuous_batching_config
1220
+ )
1221
+
1222
+ def destroy_cached_continuous_batching_manager(self) -> None:
1223
+ """Destroy the cached continuous batching manager and free GPU resources."""
1224
+ cached_manager = getattr(self, "_cached_continuous_batching_manager", None)
1225
+ if isinstance(cached_manager, ContinuousBatchingManager):
1226
+ cached_manager.stop(block=True, timeout=None, keep_for_next_session=False)
1227
+ delattr(self, "_cached_continuous_batching_manager")
1228
+
1229
+ @contextmanager
1230
+ @torch.inference_mode()
1231
+ def continuous_batching_context_manager(
1232
+ self,
1233
+ generation_config: GenerationConfig | None = None,
1234
+ block: bool = True,
1235
+ timeout: float | None = None,
1236
+ continuous_batching_config: ContinuousBatchingConfig | None = None,
1237
+ persistent_manager: bool = False,
1238
+ warmup: bool = True,
1239
+ workload_hints: WorkloadHints | None = None,
1240
+ **deprecated_kwargs,
1241
+ ) -> Generator[ContinuousBatchingManager]:
1242
+ """A context manager to safely use the continuous batching manager. Arguments are similar to the ones of
1243
+ `init_continuous_batching`, except for:
1244
+ - block: whether to block the thread when stopping the manager. Default is True.
1245
+ - timeout: maximum time to wait for the thread to stop. Default is None (no timeout).
1246
+ - warmup: whether to pre-capture CUDA graphs at the largest sizes before running. Default is True.
1247
+ """
1248
+ manager = self.init_continuous_batching(
1249
+ generation_config=generation_config,
1250
+ continuous_batching_config=continuous_batching_config,
1251
+ workload_hints=workload_hints,
1252
+ **deprecated_kwargs,
1253
+ )
1254
+ if warmup and not manager.warmed_up:
1255
+ # Warmup is long (~30 sec): best to signal the user it's happening than let them think the manager is stuck
1256
+ logger.warning("Warming up for continuous batching...")
1257
+ start = perf_counter()
1258
+ manager.warmup()
1259
+ logger.warning(f"Warming up completed in {perf_counter() - start:.2f}s.")
1260
+ manager.start()
1261
+ try:
1262
+ yield manager
1263
+ finally:
1264
+ # This is a dummy log needed for the logs of stop to show. It won't show.
1265
+ logger.debug("Continuous batching loop finished")
1266
+ manager.stop(block=block, timeout=timeout, keep_for_next_session=persistent_manager)
1267
+
1268
+ # TODO: support streaming
1269
+ @traced
1270
+ @torch.inference_mode()
1271
+ def generate_batch(
1272
+ self,
1273
+ inputs: list[list[int]],
1274
+ generation_config: GenerationConfig | None = None,
1275
+ continuous_batching_config: ContinuousBatchingConfig | None = None,
1276
+ record_timestamps: bool = False,
1277
+ progress_bar: bool = True,
1278
+ persistent_manager: bool = False,
1279
+ warmup: bool = True,
1280
+ **kwargs,
1281
+ ) -> dict[str, GenerationOutput]:
1282
+ """Generate sequences for a batch of prompts using continuous batching.
1283
+
1284
+ Args:
1285
+ inputs: List of input token sequences (prompts)
1286
+ generation_config: Optional generation configuration
1287
+ continuous_batching_config: Optional continuous batching configuration
1288
+ record_timestamps: If set to true, the requests will have a timestamp for each token generated
1289
+ progress_bar: If set to true, a progress bar will be displayed
1290
+ persistent_manager: whether to persist the manager after the generation is finished. Default is False.
1291
+ warmup: whether to pre-capture CUDA graphs before processing requests. Default is True.
1292
+ **kwargs: Additional generation parameters. Only max_new_tokens is used, but other deprecated arguments
1293
+ are extracted and passed to the continuous_batching_config object.
1294
+ Returns:
1295
+ `dict[str, GenerationOutput]`: a dictionary of request ids to GenerationOutput objects
1296
+ """
1297
+ # If no input are provided, return an empty dictionary
1298
+ if not inputs:
1299
+ return {}
1300
+
1301
+ # If the logger level is less than DEBUG, disable the progress bar
1302
+ if logger.getEffectiveLevel() <= logging.DEBUG:
1303
+ logger.warning("Progress bar is disabled when logger level is less than DEBUG")
1304
+ progress_bar = False
1305
+
1306
+ # Extract deprecated arguments from regular kwargs (deprecated in v5.3). These args are now expected in the
1307
+ # continuous_batching_config object.
1308
+ deprecated_kwargs = {}
1309
+ deprecated_keys = [
1310
+ "q_padding_interval_size",
1311
+ "kv_padding_interval_size",
1312
+ "allow_block_sharing",
1313
+ "use_async_batching",
1314
+ "max_cached_graphs",
1315
+ "max_queue_size",
1316
+ ]
1317
+ for depr_key in deprecated_keys:
1318
+ if depr_key in kwargs:
1319
+ deprecated_kwargs[depr_key] = kwargs.pop(depr_key)
1320
+
1321
+ # Compute the total number of requests
1322
+ gen_cfg = self.generation_config if generation_config is None else generation_config
1323
+ num_return_sequences = gen_cfg.num_return_sequences if gen_cfg.num_return_sequences is not None else 1
1324
+ num_requests = len(inputs) * num_return_sequences
1325
+
1326
+ # Extract max_new_tokens from kwargs because it's the only expected kwarg
1327
+ max_new_tokens = kwargs.pop("max_new_tokens", None)
1328
+ max_new_tokens = gen_cfg.max_new_tokens if max_new_tokens is None else max_new_tokens
1329
+
1330
+ # Compute workload hints
1331
+ workload_hints = WorkloadHints(
1332
+ max_prompt_length=max(len(input_ids) for input_ids in inputs),
1333
+ max_generated_length=max_new_tokens if max_new_tokens is not None else 0,
1334
+ )
1335
+
1336
+ # Prepare context managers for the main loop
1337
+ manager_cm = self.continuous_batching_context_manager(
1338
+ generation_config=generation_config,
1339
+ continuous_batching_config=continuous_batching_config,
1340
+ block=True,
1341
+ timeout=5,
1342
+ persistent_manager=persistent_manager,
1343
+ warmup=warmup,
1344
+ workload_hints=workload_hints,
1345
+ **deprecated_kwargs,
1346
+ )
1347
+ logging_cm = logging_redirect_tqdm([logger])
1348
+ pbar_cm = tqdm(
1349
+ total=num_requests,
1350
+ disable=(not progress_bar),
1351
+ desc=f"Solving {num_requests} requests",
1352
+ unit="request",
1353
+ )
1354
+
1355
+ # Main loop
1356
+ results = {}
1357
+ finished_count = 0
1358
+ with manager_cm as manager, logging_cm, pbar_cm as pbar:
1359
+ try:
1360
+ manager.add_requests(inputs=inputs, max_new_tokens=max_new_tokens, record_timestamps=record_timestamps)
1361
+ while finished_count < num_requests:
1362
+ result = manager.get_result(timeout=1)
1363
+ if result:
1364
+ req_id = result.request_id
1365
+ if result.is_finished():
1366
+ results[req_id] = result
1367
+ finished_count += 1
1368
+ pbar.update(1)
1369
+ elif not manager.is_running():
1370
+ logger.error("Generation thread terminated unexpectedly.")
1371
+ # This helps get some information in stdout
1372
+ print("Returning results of generate_batch despite unexpected termination.")
1373
+ break
1374
+
1375
+ except Exception as e:
1376
+ logger.error(f"Error during batch generation: {e}", exc_info=True)
1377
+
1378
+ # Re-order requests to match the order of the inputs
1379
+ reordered_results = {}
1380
+ for i in range(len(inputs)):
1381
+ # We cannot guarantee generation success for all requests, so check if the request is in the results
1382
+ result = results.get(f"req_{i}")
1383
+ if result is not None:
1384
+ reordered_results[f"req_{i}"] = result
1385
+ else:
1386
+ logger.error(f"Request req_{i} not found in results.")
1387
+ return reordered_results
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/input_outputs.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Inc. team
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from contextlib import nullcontext
15
+ from dataclasses import dataclass
16
+ from functools import partial
17
+ from typing import Any
18
+
19
+ import torch
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+
23
+ from ...utils import get_available_devices
24
+ from ...utils.metrics import traced
25
+ from .cache import PagedAttentionCache
26
+ from .cb_logits_processors import ContinuousBatchingLogitsProcessorList
27
+ from .requests import TMP_TOKEN_ID, FutureRequestState, logger
28
+ from .utils import CudaGraphBuffer, aligned_divide, attn_mask_is_needed, build_attention_mask, pad_to_pow2
29
+
30
+
31
+ @dataclass
32
+ class PagedAttentionArgs:
33
+ """Dataclass containing the keyword arguments for a forward pass using paged attention.
34
+
35
+ Attributes:
36
+ input_ids: Input token IDs tensor of shape `(1, total_query_tokens)`.
37
+ attention_mask: Attention mask tensor or dictionary mapping layer types to masks. Can be `None` if the
38
+ attention implementation doesn't require explicit masks.
39
+ position_ids: Position IDs tensor of shape `(1, total_query_tokens)`.
40
+ cu_seq_lens_q: Cumulative sequence lengths for queries, used for variable-length batching.
41
+ cu_seq_lens_k: Cumulative sequence lengths for keys/values. Can be a tensor or dictionary mapping layer
42
+ types (e.g., "full_attention", "sliding_attention") to tensors for hybrid models.
43
+ max_seqlen_q: Maximum query sequence length in the batch.
44
+ max_seqlen_k: Maximum key/value sequence length. Can be an int or dictionary for hybrid models.
45
+ write_index: List of tensors indicating where to write new KV states in the cache, one per attention group.
46
+ read_index: List of tensors indicating which cache positions to read from, one per attention group.
47
+ logits_indices: Tensor indicating which positions in the output should be used for next-token prediction.
48
+ cache: The [`PagedAttentionCache`] instance managing the KV cache.
49
+ block_table: Block table for paged KV cache. If provided, uses `flash_attn_with_kvcache` for fused attention +
50
+ cache update. More information in src/transformers/integrations/flash_paged.py
51
+ logits_processor_args: List of tensors containing the arguments for the logits processors, one per request.
52
+ use_cache: Whether to use caching (always `False` in continuous batching as the cache is managed externally).
53
+ """
54
+
55
+ input_ids: torch.Tensor
56
+ attention_mask: torch.Tensor | dict[str, torch.Tensor] | None
57
+ position_ids: torch.Tensor
58
+ cu_seq_lens_q: torch.Tensor
59
+ cu_seq_lens_k: torch.Tensor | dict[str, torch.Tensor]
60
+ max_seqlen_q: int
61
+ max_seqlen_k: int | dict[str, int]
62
+ write_index: list[torch.Tensor]
63
+ read_index: list[torch.Tensor]
64
+ logits_indices: torch.Tensor
65
+ cache: PagedAttentionCache
66
+ block_table: torch.Tensor | None
67
+ logits_processor_args: torch.Tensor
68
+ use_cache: bool = False
69
+
70
+ def asdict(self) -> dict[str, Any]:
71
+ return {
72
+ "input_ids": self.input_ids,
73
+ "attention_mask": self.attention_mask,
74
+ "position_ids": self.position_ids,
75
+ "cu_seq_lens_q": self.cu_seq_lens_q,
76
+ "cu_seq_lens_k": self.cu_seq_lens_k,
77
+ "max_seqlen_q": self.max_seqlen_q,
78
+ "max_seqlen_k": self.max_seqlen_k,
79
+ "write_index": self.write_index,
80
+ "read_index": self.read_index,
81
+ "logits_indices": self.logits_indices,
82
+ "cache": self.cache,
83
+ "block_table": self.block_table,
84
+ "logits_processor_args": self.logits_processor_args,
85
+ "use_cache": self.use_cache,
86
+ }
87
+
88
+
89
+ class ContinuousBatchingIOs:
90
+ """A class to hold inputs and outputs for a continuous batching forward pass, using static tensors as storage. The
91
+ class is meant to be self-contained, so once a set of inputs have been created, the class can be used to update the
92
+ batch alone.
93
+ """
94
+
95
+ static_inputs: int = 7 # Number of static inputs always present in the bulk tensor
96
+
97
+ def __init__(
98
+ self,
99
+ cache: PagedAttentionCache,
100
+ config: PretrainedConfig,
101
+ device: torch.device,
102
+ model_dtype: torch.dtype,
103
+ max_graphs: int,
104
+ return_logprobs: bool,
105
+ logit_processor: ContinuousBatchingLogitsProcessorList,
106
+ use_cuda_graph_varlen: bool = False,
107
+ ) -> None:
108
+ """Initialize the continuous batching I/O manager. Args:
109
+ - cache: The [`PagedAttentionCache`] instance managing the KV cache. Meant to be unique.
110
+ - config: The model's pretrained configuration.
111
+ - device: The device to allocate tensors on. If the device is CPU, then the memory is pinned.
112
+ - model_dtype: The data type for model computations.
113
+ - max_graphs: Maximum number of CUDA graphs to cache. Uses LRU eviction when full.
114
+ - return_logprobs: Whether to return log probabilities along with the token IDs.
115
+ - logit_processor: The [`ContinuousBatchingLogitsProcessorList`] object used to process the logits.
116
+ - use_cuda_graph_varlen: Whether CUDA graphs are enabled for the varlen (prefill) path.
117
+ """
118
+ # Memoize attributes
119
+ self.cache = cache
120
+ self.device = device
121
+ self.config = config
122
+ self.model_dtype = model_dtype
123
+ self.use_cuda_graph_varlen = use_cuda_graph_varlen
124
+ self.sliding_window = 1 if getattr(config, "sliding_window", None) is None else config.sliding_window
125
+ self.return_logprobs = return_logprobs
126
+ # Setup input-related accumulators
127
+ self.num_q_tokens = 0 # number of query tokens in the batch. Can be padded.
128
+ self.max_kv_read = 0 # number of KV tokens read from cache (maxed across all groups). Can be padded.
129
+ self.true_batch_size = 0
130
+ self.true_read_sizes = [0 for _ in range(cache.num_groups)]
131
+ self.true_write_sizes = [0 for _ in range(cache.num_groups)]
132
+ self.use_block_table = False # True if all requests in batch have query_length == 1
133
+ # Setup other accumulators
134
+ self.requests_in_batch: list[FutureRequestState] = []
135
+ self.req_id_to_new_token_position: dict[str, int] = {} # only used for async API
136
+ self.graphs: CudaGraphBuffer = CudaGraphBuffer(max_graphs)
137
+ self._trash_index = cache.trash_index
138
+ # Setup static tensors and compute stream
139
+ self._setup_static_tensors(logit_processor=logit_processor)
140
+ self._reset_static_tensors(full_reset=True)
141
+ self.compute_stream = torch.cuda.Stream(device=self.device) if device.type == "cuda" else None
142
+
143
+ @traced(standalone=True)
144
+ def _setup_static_tensors(self, logit_processor: ContinuousBatchingLogitsProcessorList) -> None:
145
+ """Allocates static tensors for generation inputs and outputs. This is called only once at init time, to avoid
146
+ repeated allocations and enable CUDA graphs. All tensors are allocated with maximum possible sizes.
147
+ The allocated tensors are:
148
+
149
+ - `_bulk_input_tensor`: Storage for all the small inputs: `input_ids`, `position_ids`, `cumulative_seqlens_q`,
150
+ `logits_indices`, `cumulative_seqlens_k`, `carry_over_ids`.
151
+ - `attention_mask`: Optional attention masks (only for eager/SDPA implementations)
152
+ - `write_index` and `read_index` storage: Cache indexing tensors for each attention group
153
+ - `output_ids`: Storage for generated token IDs and maybe log probabilities if return_logprobs is True
154
+ """
155
+ num_groups = self.cache.num_groups
156
+ max_batch_tokens = self.cache.max_batch_tokens
157
+ num_pages = self.cache.num_blocks * self.cache.block_size
158
+ # Pin memory on CPU only when an accelerator is available, to speed up H2D transfers
159
+ pin_memory = self.device.type == "cpu" and len(get_available_devices()) > 1
160
+
161
+ # Small inputs are allocated as slices in a larget tensor aligned to 128 bytes (32 * 4b). This reduces the
162
+ # reduces fragmentation, so it lowers the number of D2H transfers and speeds up transfers.
163
+ bulk_lines = self.static_inputs + logit_processor.tensors_required
164
+ bulk_columns = aligned_divide(max_batch_tokens + 1, 1, 32)
165
+ self._bulk_input_tensor = torch.empty(
166
+ (bulk_lines, bulk_columns), dtype=torch.int32, device=self.device, pin_memory=pin_memory
167
+ )
168
+ # Prepare a tensor to hold the default values for the logits processors
169
+ self.logits_processors_defaults = torch.empty(
170
+ (logit_processor.tensors_required, 1), dtype=torch.int32, device=self.device
171
+ )
172
+ logit_processor.fill_defaults(self.logits_processors_defaults)
173
+
174
+ self.input_ids = self._bulk_input_tensor[0, :max_batch_tokens]
175
+ self.position_ids = self._bulk_input_tensor[1, :max_batch_tokens]
176
+ self.cumulative_seqlens_q = self._bulk_input_tensor[2, : max_batch_tokens + 1]
177
+ self.logits_indices = self._bulk_input_tensor[3, :max_batch_tokens]
178
+ full_attention_cumulative_seqlens_k = self._bulk_input_tensor[4, : max_batch_tokens + 1]
179
+ sliding_attention_cumulative_seqlens_k = self._bulk_input_tensor[5, : max_batch_tokens + 1]
180
+ self.carry_over_ids = self._bulk_input_tensor[6, :max_batch_tokens] # only used for async API
181
+
182
+ # For sequence length of KV, the entries in the dict depend on the model
183
+ self.cumulative_seqlens_k: dict[str, torch.Tensor] = {}
184
+ if self.cache.num_full_attention_groups:
185
+ self.cumulative_seqlens_k["full_attention"] = full_attention_cumulative_seqlens_k
186
+ if self.cache.num_sliding_attention_groups:
187
+ self.cumulative_seqlens_k["sliding_attention"] = sliding_attention_cumulative_seqlens_k
188
+
189
+ # Output tensor and scalars
190
+ num_output_rows = 2 if self.return_logprobs else 1
191
+ self.output_ids = torch.empty(
192
+ (num_output_rows, max_batch_tokens + 1), dtype=torch.int32, device=self.device, pin_memory=pin_memory
193
+ )
194
+ # Last output token is never changed and set to 0 for async carry on purpose
195
+ self.output_ids.zero_()
196
+ self.total_seqlen_q = 0
197
+ self.max_seqlen_q = 0
198
+ self.max_seqlen_k = dict.fromkeys(self.cumulative_seqlens_k.keys(), 0)
199
+
200
+ # If the attention mask is needed, it is allocated separately
201
+ if attn_mask_is_needed(self.config):
202
+ self.attention_mask = {}
203
+ for layer_type in self.cumulative_seqlens_k.keys():
204
+ self.attention_mask[layer_type] = torch.empty(
205
+ size=(1, 1, max_batch_tokens, num_pages + max_batch_tokens),
206
+ dtype=self.model_dtype,
207
+ device=self.device,
208
+ pin_memory=pin_memory,
209
+ )
210
+ else:
211
+ self.attention_mask = None
212
+
213
+ # No block table == No elements in the block table tensor
214
+ n = num_groups if self.cache.max_blocks_per_request > 0 else 0
215
+ self.block_table = torch.empty(
216
+ (n, max_batch_tokens, self.cache.max_blocks_per_request),
217
+ dtype=torch.int32,
218
+ device=self.device,
219
+ pin_memory=pin_memory,
220
+ )
221
+
222
+ # For other kwargs, we need a list of tensors with as many tensors as there are groups
223
+ self.write_index_storage = torch.empty(
224
+ (num_groups, max_batch_tokens), dtype=torch.int64, device=self.device, pin_memory=pin_memory
225
+ )
226
+ self.read_index_storage = torch.empty(
227
+ (num_groups, num_pages + max_batch_tokens), dtype=torch.int64, device=self.device, pin_memory=pin_memory
228
+ )
229
+ # For read index, the +T is because there are sentinel indices for seqlen_q when model uses a sliding window
230
+
231
+ def _transfer_inputs(
232
+ self, other: "ContinuousBatchingIOs", stream: torch.cuda.Stream, non_blocking: bool = False
233
+ ) -> None:
234
+ # Transfer accumulators
235
+ other.num_q_tokens = self.num_q_tokens
236
+ other.max_kv_read = self.max_kv_read
237
+ other.true_batch_size = self.true_batch_size
238
+ other.true_read_sizes = self.true_read_sizes[:]
239
+ other.true_write_sizes = self.true_write_sizes[:]
240
+ other.use_block_table = self.use_block_table
241
+ # Transfer scalar attributes
242
+ other.total_seqlen_q = self.total_seqlen_q
243
+ other.max_seqlen_q = self.max_seqlen_q
244
+ other.max_seqlen_k = dict(self.max_seqlen_k.items())
245
+ # Transfer static tensors
246
+ maybe_stream = torch.cuda.stream(stream) if stream is not None else nullcontext()
247
+ with maybe_stream:
248
+ other._bulk_input_tensor.copy_(self._bulk_input_tensor, non_blocking=non_blocking) # fast bulk transfer
249
+ # Only transfer block_table for decode-only batches (when it's actually used)
250
+ if self.use_block_table:
251
+ other.block_table.copy_(self.block_table, non_blocking=non_blocking)
252
+ # Otherwise, we transfer the write indices (and read indices if the batch uses any cache reads)
253
+ else:
254
+ other.write_index_storage.copy_(self.write_index_storage, non_blocking=non_blocking)
255
+ if self.max_kv_read > 0:
256
+ other.read_index_storage.copy_(self.read_index_storage, non_blocking=non_blocking)
257
+ # Transfer the attention masks if needed
258
+ if self.attention_mask is not None and other.attention_mask is not None:
259
+ for layer_type in self.attention_mask.keys():
260
+ other.attention_mask[layer_type].copy_(self.attention_mask[layer_type], non_blocking=non_blocking)
261
+
262
+ @traced
263
+ @torch.no_grad()
264
+ def _reset_static_tensors(self, full_reset: bool = False) -> None:
265
+ """Reset static tensors for the next batch. For efficiency, this only resets the portions of tensors that were
266
+ actually used in the previous batch, using the attributes num_q_tokens and max_kv_read. If a (full_reset)
267
+ is requested, the entire tensor storage is reset.
268
+ """
269
+ # Compute the slice to reset
270
+ q_len = self.write_index_storage.size(-1) if full_reset else self.num_q_tokens
271
+ kv_len = self.read_index_storage.size(-1) if full_reset else self.max_kv_read
272
+
273
+ # Reset the attributes part of the bulk input tensor in one kernel
274
+ self._bulk_input_tensor[: self.static_inputs, : q_len + 1].zero_()
275
+ if full_reset:
276
+ self._bulk_input_tensor[self.static_inputs :] = self.logits_processors_defaults
277
+ self.max_seqlen_q = 0
278
+
279
+ # Reset the logits indices and output ids
280
+ self.logits_indices[:q_len].zero_()
281
+ self.output_ids[:, :q_len].zero_()
282
+
283
+ # Reset the attributes that are either tensors or dict of tensors
284
+ for layer_type in self.cumulative_seqlens_k:
285
+ self.max_seqlen_k[layer_type] = 0
286
+ if self.attention_mask is not None:
287
+ self.attention_mask[layer_type][:, :, :q_len, : q_len + kv_len].fill_(
288
+ torch.finfo(self.model_dtype).min
289
+ )
290
+
291
+ # If this is a full reset, we reset every tensors
292
+ if full_reset:
293
+ self.block_table[:, :q_len].fill_(-1)
294
+ self.write_index_storage[:, :q_len].fill_(self._trash_index)
295
+ self.read_index_storage[:, : q_len + kv_len].fill_(self._trash_index)
296
+ # If this is not a full reset, and we are going to use the block table, we only reset it
297
+ elif self.use_block_table:
298
+ self.block_table[:, :q_len].fill_(-1)
299
+ # Otherwise, the read and write indices are the ones used, so we reset them
300
+ else:
301
+ self.write_index_storage[:, :q_len].fill_(self._trash_index)
302
+ self.read_index_storage[:, : q_len + kv_len].fill_(self._trash_index)
303
+
304
+ def reset(self) -> None:
305
+ """Reset all relevant states for a new generation loop."""
306
+ self._reset_static_tensors(full_reset=True)
307
+ self.requests_in_batch = []
308
+ self.req_id_to_new_token_position = {}
309
+ if self.compute_stream is not None:
310
+ self.compute_stream.synchronize()
311
+
312
+ # These getter function help create a common interface for the sync and async IOs
313
+ def get_cumulative_seqlens(self) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
314
+ """Get the cumulative sequence lengths for the current batch."""
315
+ return self.cumulative_seqlens_q, self.cumulative_seqlens_k
316
+
317
+ def carry_over_tokens(
318
+ self, input_ids: torch.Tensor, carry_over_ids: torch.Tensor, prev_output_ids: torch.Tensor
319
+ ) -> None:
320
+ pass
321
+
322
+ def retrieve_device_outputs(self) -> None:
323
+ if self.compute_stream is not None:
324
+ self.compute_stream.synchronize()
325
+
326
+ def prepare_batch_update(self) -> tuple[list[FutureRequestState], list[int], list[float] | None]:
327
+ requests_in_batch = self.requests_in_batch
328
+ new_tokens = self.output_ids[0, : len(self.requests_in_batch)].tolist()
329
+ # If logprobs are generated, we retrieve them from the output tensor and cast them to the right dtype
330
+ if self.return_logprobs:
331
+ logprobs = self.output_ids[1, : len(self.requests_in_batch)].view(dtype=torch.float32).tolist()
332
+ # Otherwise, we can return an empty list because they wont be used
333
+ else:
334
+ logprobs = None
335
+ return requests_in_batch, new_tokens, logprobs
336
+
337
+ @traced
338
+ def prepare_batch_tensors(
339
+ self,
340
+ requests_in_batch: list[FutureRequestState],
341
+ logits_processors: ContinuousBatchingLogitsProcessorList,
342
+ use_decode_fast_path: bool,
343
+ num_q_tokens: int,
344
+ max_kv_read: int,
345
+ ) -> None:
346
+ """Prepare tensors and metadata for the next model forward pass, using the given requests as data. This method:
347
+
348
+ 1. Resets the static tensors from the previous batch
349
+ 2. Iterates through requests to accumulate input_ids, position_ids, and sequence lengths
350
+ 3. Extends read/write indices for cache management
351
+ 4. Builds attention masks if needed (for eager/SDPA implementations)
352
+ 5. Converts accumulated lists to tensors and copies them to static storage
353
+
354
+ This method also modifies the `position_offset` attribute of each request to track progress and adds a
355
+ temporary token at the end of the requests for which there will a new token.
356
+ """
357
+ # Keep track of this requests in the batch, which will be useful to update the batch later
358
+ if not requests_in_batch:
359
+ raise ValueError("No requests in batch")
360
+
361
+ # Determine if the block table is used before we start to prepare the batch, to avoid useless preparation
362
+ self.use_block_table = use_decode_fast_path and self.block_table.numel() > 0
363
+ # Memoize the length of Q and KV
364
+ self.num_q_tokens = num_q_tokens
365
+ self.max_kv_read = 0 if self.use_block_table else max_kv_read # No need to track KV read for decode-fast-path
366
+ self.true_batch_size = len(requests_in_batch)
367
+ # Reset the static storage that is going to be used for the next batch
368
+ self._reset_static_tensors()
369
+
370
+ # Reset accumulators
371
+ self.true_read_sizes = [0 for _ in range(self.cache.num_groups)]
372
+ self.true_write_sizes = [0 for _ in range(self.cache.num_groups)]
373
+ self.requests_in_batch = []
374
+ self.req_id_to_new_token_position = {}
375
+
376
+ # Prepare accumulators. For batches with no past cache to read, we leave read_index empty: the cache.update
377
+ # will detect the 0-size indices and skip the read.
378
+ input_ids = []
379
+ position_ids = []
380
+ cumulative_seqlens_q = [0]
381
+ logits_indices = []
382
+ cumulative_seqlens_k = {layer_type: [0] for layer_type in self.cumulative_seqlens_k.keys()}
383
+ write_index = [[] for _ in range(self.cache.num_groups)]
384
+ read_index = None if self.max_kv_read == 0 else [[] for _ in range(self.cache.num_groups)]
385
+
386
+ # Go through all the requests in the batch
387
+ for i, future_state in enumerate(requests_in_batch):
388
+ # First we retrieve the lengths related to the request
389
+ state = future_state.state
390
+ past_length = state.position_offset
391
+ query_length = future_state.query_length
392
+ seqlens_k = self.cache.get_seqlens_k(past_length, query_length)
393
+
394
+ # Update the internal state of the request
395
+ state.position_offset += query_length
396
+
397
+ # Then we accumulate for the object used in the kwargs
398
+ input_ids.extend(state.tokens_to_process)
399
+ position_ids.extend(range(past_length, past_length + query_length))
400
+ cumulative_seqlens_q.append(cumulative_seqlens_q[-1] + query_length)
401
+ self.max_seqlen_q = max(self.max_seqlen_q, query_length)
402
+
403
+ # Accumulate the key sequence lengths for the current request
404
+ for layer_type, layer_type_seqlen_k in seqlens_k.items():
405
+ cumulative_seqlens_k[layer_type].append(cumulative_seqlens_k[layer_type][-1] + layer_type_seqlen_k)
406
+ self.max_seqlen_k[layer_type] = max(self.max_seqlen_k[layer_type], layer_type_seqlen_k)
407
+
408
+ # We extend the read and write indices for the cache, or fill the block table for decode-only batches
409
+ if self.use_block_table:
410
+ self.cache.fill_block_table(state.request_id, past_length, query_length, self.block_table[:, i])
411
+ else:
412
+ self.cache.extend_read_and_write_indices(
413
+ state.request_id, past_length, query_length, read_index, write_index
414
+ )
415
+
416
+ # If the request has no remaining prefill tokens, it means the next token prediction is relevant
417
+ if future_state.has_new_token:
418
+ logits_indices.append(cumulative_seqlens_q[-1] - 1)
419
+ state.tokens_to_process = [TMP_TOKEN_ID]
420
+ self.req_id_to_new_token_position[state.request_id] = logits_indices[-1]
421
+
422
+ self.requests_in_batch.append(future_state)
423
+
424
+ # Also prepare the tensor arguments for the logits processors
425
+ logits_processors.prepare_tensor_args(
426
+ requests_in_batch=requests_in_batch,
427
+ arg_storage=self._bulk_input_tensor[self.static_inputs :],
428
+ )
429
+
430
+ # When looping over request is done, we can build the actual tensors. This is faster than modifying the static
431
+ # tensors inside the loop.
432
+ to_tensor = partial(torch.tensor, dtype=torch.int32, device=self.device)
433
+
434
+ # Those kwargs always have the same type regardless of the model
435
+ self.input_ids[: len(input_ids)] = to_tensor(input_ids)
436
+ self.position_ids[: len(position_ids)] = to_tensor(position_ids)
437
+ self.cumulative_seqlens_q[: len(cumulative_seqlens_q)] = to_tensor(cumulative_seqlens_q)
438
+ self.logits_indices[: len(logits_indices)] = to_tensor(logits_indices)
439
+ self.total_seqlen_q = cumulative_seqlens_q[-1]
440
+
441
+ # Those kwargs are either dict of tensors or tensors, so we need to handle both cases
442
+ for layer_type, layer_type_seqlens_k in cumulative_seqlens_k.items():
443
+ self.cumulative_seqlens_k[layer_type][: len(layer_type_seqlens_k)] = to_tensor(layer_type_seqlens_k)
444
+ if self.attention_mask is not None:
445
+ build_attention_mask(
446
+ attention_mask=self.attention_mask[layer_type],
447
+ cumulative_seqlens_q=cumulative_seqlens_q,
448
+ cumulative_seqlens_k=layer_type_seqlens_k,
449
+ sliding_window=self.sliding_window if layer_type == "sliding_attention" else 1,
450
+ )
451
+
452
+ # If we are not using the block table, we populate the write indices (and maybe the read indices)
453
+ if not self.use_block_table:
454
+ to_index_tensor = partial(torch.tensor, dtype=torch.int64, device=self.device)
455
+ for i, group_write_indices in enumerate(write_index):
456
+ self.write_index_storage[i, : len(group_write_indices)] = to_index_tensor(group_write_indices)
457
+ self.true_write_sizes[i] = len(group_write_indices)
458
+ if read_index is not None:
459
+ for i, group_read_indices in enumerate(read_index):
460
+ self.read_index_storage[i, : len(group_read_indices)] = to_index_tensor(group_read_indices)
461
+ self.true_read_sizes[i] = len(group_read_indices)
462
+
463
+ def get_model_kwargs(self, use_padding: bool = False) -> dict[str, Any]:
464
+ """Get model keyword arguments for the current batch, eventually padding the query dimension and KV dimensions
465
+ if use_padding is True. The padding is only useful if we want static shapes, like when using cuda graphs."""
466
+ q_size = self.num_q_tokens
467
+ kv_size = self.max_kv_read + self.num_q_tokens
468
+ batch_size = self.num_q_tokens if use_padding else self.true_batch_size
469
+
470
+ # Prepare the kwargs, the attributes that are either tensors or dict of tensors are initialized to empty dicts.
471
+ kwargs = PagedAttentionArgs(
472
+ input_ids=self.input_ids[:q_size].unsqueeze(0),
473
+ position_ids=self.position_ids[:q_size].unsqueeze(0),
474
+ cu_seq_lens_q=self.cumulative_seqlens_q[: batch_size + 1],
475
+ max_seqlen_q=self.max_seqlen_q,
476
+ logits_indices=self.logits_indices[:q_size],
477
+ logits_processor_args=self._bulk_input_tensor[self.static_inputs :, :q_size],
478
+ cu_seq_lens_k={},
479
+ max_seqlen_k={},
480
+ attention_mask=None if self.attention_mask is None else {},
481
+ read_index=[],
482
+ write_index=[],
483
+ cache=self.cache,
484
+ block_table=self.block_table[:, :batch_size] if self.use_block_table else None,
485
+ use_cache=False,
486
+ )
487
+
488
+ # If there is padding, make sure the padding sequences have length 0 (ie. cumulative lengths plateau)
489
+ if use_padding:
490
+ kwargs.cu_seq_lens_q[self.true_batch_size + 1 :] = self.total_seqlen_q
491
+ # Additionally, if there are CUDA graphs, we need to pad max_seqlen so graph capture will work regardless of
492
+ # the future Q / KV lengths of the next batches
493
+ if not self.use_block_table and self.use_cuda_graph_varlen:
494
+ self.max_seqlen_q = q_size
495
+ self.max_seqlen_k = {
496
+ layer_type: pad_to_pow2(self.max_seqlen_k[layer_type], self.cache.num_pages, 1024)
497
+ for layer_type in self.max_seqlen_k.keys()
498
+ }
499
+
500
+ # When using block table, max_seqlen_q and max_seqlen_k are not used by flash_attn_with_kvcache, so we set them
501
+ # to constant `1` to avoid dynamo guards on these changing integer values. This applies throughout this method.
502
+ kwargs.max_seqlen_q = 1 if self.use_block_table else self.max_seqlen_q
503
+
504
+ # For the attributes that are lists of tensors, we construct list of tensor references
505
+ for i in range(self.cache.num_groups):
506
+ write_index_size = q_size if use_padding else self.true_write_sizes[i]
507
+ kwargs.write_index.append(self.write_index_storage[i, :write_index_size])
508
+ # If there is no cache to read, pass a list of empty tensors so `cache.update` uses the write-only fast path
509
+ if self.max_kv_read == 0:
510
+ read_index_size = 0
511
+ else:
512
+ read_index_size = kv_size if use_padding else self.true_read_sizes[i]
513
+ kwargs.read_index.append(self.read_index_storage[i, :read_index_size])
514
+
515
+ # For the attributes that are dict of tensors, we first fill the dict with the actual values
516
+ for layer_type, seqlens_k in self.cumulative_seqlens_k.items():
517
+ kwargs.cu_seq_lens_k[layer_type] = seqlens_k[: batch_size + 1]
518
+ if use_padding:
519
+ kwargs.cu_seq_lens_k[layer_type][self.true_batch_size + 1 :] = seqlens_k[self.true_batch_size]
520
+ kwargs.max_seqlen_k[layer_type] = 1 if self.use_block_table else self.max_seqlen_k[layer_type]
521
+ if self.attention_mask is not None:
522
+ k_len = kv_size if use_padding else seqlens_k[batch_size]
523
+ kwargs.attention_mask[layer_type] = self.attention_mask[layer_type][..., :q_size, :k_len]
524
+
525
+ # If there is only one layer type, we remove the dicts around some attributes to avoid unnecessary overhead
526
+ if len(self.cumulative_seqlens_k.keys()) == 1:
527
+ kwargs.cu_seq_lens_k = kwargs.cu_seq_lens_k.popitem()[1] # type: ignore
528
+ kwargs.max_seqlen_k = kwargs.max_seqlen_k.popitem()[1] # type: ignore
529
+ if self.attention_mask is not None:
530
+ kwargs.attention_mask = kwargs.attention_mask.popitem()[1] # type: ignore
531
+
532
+ return kwargs.asdict() # TODO: this is imperfect, check if there is no better way to juggle dict / dataclass
533
+
534
+ def get_cb_kwargs(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
535
+ """Returns the tensors used inside the generation step that are not inputs to the model forward pass. In
536
+ synchronous batching, there is no carry over, so the only tensor that will be used is output_ids, but we still
537
+ return 3 tensors to have the same interface as when using async batching."""
538
+ return self.carry_over_ids, self.output_ids, self.output_ids
539
+
540
+ def _get_graph_key(self) -> tuple[int, ...]:
541
+ # Keys for decode fast path
542
+ if self.use_block_table:
543
+ return (self.num_q_tokens,)
544
+ # Keys for varlen path
545
+ return (self.num_q_tokens, self.max_kv_read, *self.max_seqlen_k.values())
546
+
547
+ def get_graph(self) -> torch.cuda.CUDAGraph | None:
548
+ key = self._get_graph_key()
549
+ graph = self.graphs.get_graph(key)
550
+ # If this point is reached, it means the next step will be a new graph capture
551
+ if graph is None:
552
+ self.graphs.plan_for_new_graph()
553
+ logger.info(f"Creating graph for {key = }")
554
+ return graph
555
+
556
+ def set_graph(self, graph: torch.cuda.CUDAGraph) -> None:
557
+ key = self._get_graph_key()
558
+ self.graphs.set_graph(key, graph)
559
+ logger.info(f"Setting graph for {key = }")
560
+
561
+
562
+ class HostDeviceIOPair:
563
+ def __init__(
564
+ self,
565
+ cache: PagedAttentionCache,
566
+ config: PretrainedConfig,
567
+ device: torch.device,
568
+ model_dtype: torch.dtype,
569
+ max_graphs: int,
570
+ return_logprobs: bool,
571
+ logit_processor: ContinuousBatchingLogitsProcessorList,
572
+ use_cuda_graph_varlen: bool = False,
573
+ ) -> None:
574
+ # The host IO has automatic pinned memory because it is created on the CPU
575
+ self.host_io = ContinuousBatchingIOs(
576
+ cache,
577
+ config,
578
+ torch.device("cpu"),
579
+ model_dtype,
580
+ max_graphs,
581
+ return_logprobs,
582
+ logit_processor,
583
+ use_cuda_graph_varlen,
584
+ )
585
+ self.device_io = ContinuousBatchingIOs(
586
+ cache,
587
+ config,
588
+ device,
589
+ model_dtype,
590
+ max_graphs,
591
+ return_logprobs,
592
+ logit_processor,
593
+ use_cuda_graph_varlen,
594
+ )
595
+ # Create events only on CUDA devices
596
+ self.h2d_over = torch.cuda.Event() if torch.cuda.is_available() else None
597
+ self.compute_over = torch.cuda.Event() if torch.cuda.is_available() else None
598
+ self.d2h_over = torch.cuda.Event() if torch.cuda.is_available() else None
599
+
600
+ def reset(self) -> None:
601
+ self.host_io.reset()
602
+ self.device_io.reset()
603
+ for event in [self.h2d_over, self.compute_over, self.d2h_over]:
604
+ if event is not None:
605
+ event.synchronize()
606
+
607
+ def transfer_inputs_h2d(self, stream: torch.cuda.Stream) -> None:
608
+ self.host_io._transfer_inputs(self.device_io, stream=stream, non_blocking=True)
609
+
610
+ def transfer_outputs_d2h(self, stream: torch.cuda.Stream | None) -> None:
611
+ maybe_stream = torch.cuda.stream(stream) if stream is not None else nullcontext()
612
+ with maybe_stream:
613
+ self.host_io.output_ids.copy_(self.device_io.output_ids, non_blocking=True)
614
+
615
+
616
+ class ContinuousBatchingAsyncIOs:
617
+ """A class to handle the inputs and outputs for the asynchronous API. It uses two IO pairs to avoid race conditions
618
+ between the two batches, which means twice as more VRAM is used for static input tensors and CUDA graph. If your GPU
619
+ is large enough or you want to generate long sequences, this is a good trade-off to make.
620
+
621
+ Asynchronous batching works by creating two pairs of host - device inputs and ouputs:
622
+
623
+ inputs
624
+ ┌──────────┐ ────────► ┌────────────┐
625
+ IO pair object: │ Host IOs │ │ Device IOs │ (for a CUDA sytem, Host = CPU and Device = GPU)
626
+ └──────────┘ ◄──────── └────────────┘
627
+ outputs
628
+
629
+ Each pair is separate from the other. This means that each pairs has its own CUDA graphs set, because CUDA graphs
630
+ need to have static adresses for input tensors. To have a unique set of CUDA graph, we would need to copy the input
631
+ tensors to a third device-side buffer. This could limit the memory cost of CUDA graphs but would slow down the
632
+ forward pass.
633
+ But the CUDA streams orchestrating the transfer from host to device (H2D) and device to host (D2H) are the same for
634
+ both pairs. Same for the compute stream.
635
+ The order of steps in async batching looks like this (for 3 batches of compute):
636
+
637
+ │ ┌────┬────┐ ┌────┬────┐ ┌────┬────┐ ┌────┐ ┌────┐
638
+ CPU │ │PR 0│PR 1│ │UP 0│PR 2│ │UP 1│PR 3│ │UP 2│ │UP 3│
639
+ │ └────┼───┬┴──┐ └────┴────┼───┐ └────┴────┼───┐ └────┘ └────┘
640
+ H2D │ │0->│1->│ ¦ │2->│ ¦ │3->│ ¦ ¦
641
+ │ └───┼───┴───────────┬─────────────┴─┬─┼───────────┴───┼───────────────┐ ¦
642
+ GPU │ │ COMPUTE 0 │ COMPUTE 1 │█│ COMPUTE 2 │ COMPUTE 3 │ ¦
643
+ │ └─────────────���─┼───┬───────────┼─┴─┬─────────────┼───┬───────────┼───┤
644
+ D2H │ │0<-│ │1<-│ │2<-│ │3<-│
645
+ │ └───┘ └───┘ └───┘ └───┘
646
+
647
+ with: - CPU: actions happening on the CPU (host-side)
648
+ - GPU: actions happening on the GPU (device-side)
649
+ - H2D: host to device transfer
650
+ - D2H: device to host transfer
651
+ and:
652
+ - PR N: preparation of batch N
653
+ - ->N: host to device transfer of batch N
654
+ - COMPUTE N: compute step for batch N
655
+ - <-N: device to host transfer of batch N
656
+ - UP N: update of batch N
657
+
658
+ You can see that the GPU is almost always busy, except where the █ is.
659
+ Proper ordering of steps is ensured through the use of CUDA events and streams.
660
+ """
661
+
662
+ def __init__(
663
+ self,
664
+ cache: PagedAttentionCache,
665
+ config: PretrainedConfig,
666
+ device: torch.device,
667
+ model_dtype: torch.dtype,
668
+ max_graphs: int,
669
+ return_logprobs: bool,
670
+ logit_processor: ContinuousBatchingLogitsProcessorList,
671
+ use_cuda_graph_varlen: bool = False,
672
+ ) -> None:
673
+ # Async batching needs streams to function, so check is CUDA is available
674
+ if not torch.cuda.is_available():
675
+ raise RuntimeError(f"Async batching requires CUDA, but {torch.cuda.is_available() = }")
676
+ # IO pairs used to avoid race conditions
677
+ self.current_pair = 0
678
+ self.io_pairs = [
679
+ HostDeviceIOPair(
680
+ cache,
681
+ config,
682
+ device,
683
+ model_dtype,
684
+ max_graphs,
685
+ return_logprobs,
686
+ logit_processor,
687
+ use_cuda_graph_varlen,
688
+ )
689
+ for _ in range(2)
690
+ ]
691
+ # CUDA streams
692
+ self.h2d_stream = torch.cuda.Stream(device=device)
693
+ self.d2h_stream = torch.cuda.Stream(device=device)
694
+ self.compute_stream = torch.cuda.Stream(device=device)
695
+ # Set all unused compute streams to None
696
+ self.io_pairs[0].host_io.compute_stream = None
697
+ self.io_pairs[0].device_io.compute_stream = None
698
+ self.io_pairs[1].host_io.compute_stream = None
699
+ self.io_pairs[1].device_io.compute_stream = None
700
+ # Used in carry over ids computation
701
+ self.max_batch_tokens = cache.max_batch_tokens
702
+
703
+ # These methods are simple wrapper dispatching to the current IO pair
704
+ def get_cumulative_seqlens(self) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
705
+ return self.io_pairs[self.current_pair].host_io.get_cumulative_seqlens()
706
+
707
+ # The prepare_batch_tensor method also has to prepare the carry over ids
708
+ def prepare_batch_tensors(
709
+ self,
710
+ requests_in_batch: list[FutureRequestState],
711
+ logits_processors: ContinuousBatchingLogitsProcessorList,
712
+ use_decode_fast_path: bool,
713
+ num_q_tokens: int,
714
+ max_kv_read: int,
715
+ ) -> None:
716
+ io_pair = self.io_pairs[self.current_pair]
717
+ io_pair.host_io.prepare_batch_tensors(
718
+ requests_in_batch, logits_processors, use_decode_fast_path, num_q_tokens, max_kv_read
719
+ )
720
+ io_pair.host_io.carry_over_ids.copy_(self.infer_carry_over_ids())
721
+
722
+ def infer_carry_over_ids(self) -> torch.Tensor:
723
+ """Infers the ids of the tokens to carry over from batch N to batch N+1. In asynchronous batching mode, we can
724
+ schedule a request for batch N+1 without knowing the token predicted for that request in batch N. For that
725
+ reason, we might need to carry over tokens just predicted in batch N before launching the forwar pass of batch
726
+ N+1. This method computes the ids of the tokens to carry over."""
727
+ next_req_id_to_new_token_position = self.io_pairs[self.current_pair].host_io.req_id_to_new_token_position
728
+ prev_req_id_to_new_token_position = self.io_pairs[1 - self.current_pair].host_io.req_id_to_new_token_position
729
+ carry_over_ids = [-1 for _ in range(self.max_batch_tokens)]
730
+ # Carry over happens after the raw predictions have been indexed with logits_indices. So output_ids contains the
731
+ # a sequence of contiguous new tokens in the order the request were added to the batch. Eg:
732
+ # output_ids = [new_tok_req3, new_tok_req1, new_tok_req2]
733
+ # Since it's also the order of req_id_to_new_token_position, we just iterate over the old positions and look for
734
+ # a request_id match: if there is one, we carry the predicted token over to its new position.
735
+ for i, req_id in enumerate(prev_req_id_to_new_token_position.keys()):
736
+ new_token_position = next_req_id_to_new_token_position.get(req_id)
737
+ if new_token_position is not None:
738
+ carry_over_ids[new_token_position] = i
739
+ return torch.tensor(carry_over_ids, dtype=torch.int32)
740
+
741
+ # The get_model_kwargs method is where the H2D transfer happens
742
+ def get_model_kwargs(self, use_padding: bool = False) -> dict[str, Any]:
743
+ io_pair = self.io_pairs[self.current_pair]
744
+ io_pair.transfer_inputs_h2d(self.h2d_stream)
745
+ self.h2d_stream.record_event(io_pair.h2d_over)
746
+ self.compute_stream.wait_event(io_pair.h2d_over)
747
+ return io_pair.device_io.get_model_kwargs(use_padding=use_padding)
748
+
749
+ def get_cb_kwargs(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
750
+ """Returns the tensors used inside the generation step that are not inputs to the model forward pass. Those
751
+ tensors could be retrieved using this object, but it would trigger a recompile if using torch.compile. They are:
752
+ - output_ids: the output ids of the current batch
753
+ - prev_output_ids: the output ids of the previous batch, required to carry over outputs tokens of the previous
754
+ batch to the input tokens of the next batch.
755
+ - carry_over_ids: a mask representing how to carry over tokens.
756
+ """
757
+ current_pair = self.io_pairs[self.current_pair]
758
+ previous_pair = self.io_pairs[1 - self.current_pair]
759
+ return (
760
+ current_pair.device_io.carry_over_ids,
761
+ previous_pair.device_io.output_ids,
762
+ current_pair.device_io.output_ids,
763
+ )
764
+
765
+ def carry_over_tokens(
766
+ self, input_ids: torch.Tensor, carry_over_ids: torch.Tensor, prev_output_ids: torch.Tensor
767
+ ) -> None:
768
+ """As explained in the infer_carry_over_ids method, we might need to carry over tokens just predicted in batch N
769
+ before launching the forwar pass of batch N+1. This method performs the carry over, and is recorded in CUDA
770
+ graphs if they are enabled."""
771
+ # Compute tokens to carry over and the corresponding mask
772
+ carried_over_ids = prev_output_ids[0, carry_over_ids]
773
+ carried_over_mask = (carry_over_ids != -1).int()
774
+ # Truncate everything to the right size
775
+ carried_over_ids = carried_over_ids[: input_ids.size(1)]
776
+ carried_over_mask = carried_over_mask[: input_ids.size(1)]
777
+ # Perform the carry over
778
+ input_ids[0] = carried_over_ids * carried_over_mask + input_ids[0] * (1 - carried_over_mask)
779
+
780
+ # This is called during compute, so we always pick the device IO in the IO pair
781
+ @property
782
+ def output_ids(self) -> torch.Tensor:
783
+ # The output ids are used to copy_ the infered tokens: they need to be on the device
784
+ return self.io_pairs[self.current_pair].device_io.output_ids
785
+
786
+ def get_graph(self) -> torch.cuda.CUDAGraph | None:
787
+ return self.io_pairs[self.current_pair].device_io.get_graph()
788
+
789
+ def set_graph(self, graph: torch.cuda.CUDAGraph) -> None:
790
+ self.io_pairs[self.current_pair].device_io.set_graph(graph)
791
+
792
+ @property
793
+ def use_block_table(self) -> bool:
794
+ return self.io_pairs[self.current_pair].host_io.use_block_table
795
+
796
+ # The retrieve_device_outputs method is where the D2H transfer happens AND where we switch IO pair
797
+ def retrieve_device_outputs(self) -> None:
798
+ io_pair = self.io_pairs[self.current_pair]
799
+ # Wait for compute to finish before starting D2H transfer
800
+ self.compute_stream.record_event(io_pair.compute_over)
801
+ self.d2h_stream.wait_event(io_pair.compute_over)
802
+ # Transfer the outputs to the host
803
+ io_pair.transfer_outputs_d2h(self.d2h_stream)
804
+ self.d2h_stream.record_event(io_pair.d2h_over)
805
+ # Switch IO pair
806
+ self.current_pair = 1 - self.current_pair
807
+
808
+ # This method is called after the switch and not during the first batch
809
+ def prepare_batch_update(self) -> tuple[list[FutureRequestState], list[int], list[float] | None]:
810
+ io_pair = self.io_pairs[self.current_pair]
811
+ io_pair.d2h_over.synchronize() # ty:ignore[unresolved-attribute] <- this is always a CUDA event
812
+ return io_pair.host_io.prepare_batch_update()
813
+
814
+ def reset(self) -> None:
815
+ """Reset all state for a new generation session. Used in persistent mode between sessions."""
816
+ self.current_pair = 0
817
+ for io_pair in self.io_pairs:
818
+ io_pair.reset()
819
+ self.h2d_stream.synchronize()
820
+ self.d2h_stream.synchronize()
821
+ self.compute_stream.synchronize()
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/offloading_manager.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Inc. team
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Centralized offloading logic for continuous batching.
15
+
16
+ Handles two offloading strategies when the GPU KV cache is full:
17
+ 1. CPU offloading: copy the KV cache to a pre-allocated pinned CPU buffer, preserving exact request state.
18
+ 2. Soft reset: discard the KV cache and re-prefill from scratch when the request is re-scheduled. This incurs no data
19
+ transfer overhead, but we need to re-run prefill over all intial + generated tokens (so more compute overhead).
20
+
21
+ The CPU swap pool is a static set of pinned tensors allocated once at init (like vLLM/SGLang). Blocks are tracked
22
+ with a simple free set — no dynamic allocation or deallocation of tensors ever happens at runtime.
23
+ """
24
+
25
+ from collections import deque
26
+ from contextlib import nullcontext
27
+
28
+ import torch
29
+
30
+ from ...utils import is_psutil_available
31
+ from .cache import PagedAttentionCache
32
+ from .requests import FutureRequestState, RequestState, RequestStatus, logger
33
+ from .scheduler import Scheduler
34
+
35
+
36
+ class OffloadingManager:
37
+ """Manages request offloading and restoration for continuous batching.
38
+
39
+ Owns a static CPU swap pool (pre-allocated pinned tensors mirroring the GPU cache layout), performs GPU↔CPU block
40
+ copies, decides between CPU offloading and soft reset, and ensures cleanup on cancellation/failure/reset.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ cache: PagedAttentionCache,
46
+ scheduler: Scheduler,
47
+ cpu_offload_space_gib: float | None,
48
+ safety_threshold: float,
49
+ compute_stream: torch.cuda.Stream | None,
50
+ ) -> None:
51
+ self.cache = cache
52
+ self.scheduler = scheduler
53
+ # All offloading transfers run on the compute stream (stream-ordered, like the fork copy path)
54
+ self._compute_stream = compute_stream
55
+
56
+ # Bookkeeping defaults, valid whether or not the pool is allocated
57
+ self._cpu_key_cache: list[torch.Tensor] = []
58
+ self._cpu_value_cache: list[torch.Tensor] = []
59
+ self._gpu_key_views: list[torch.Tensor] = []
60
+ self._gpu_value_views: list[torch.Tensor] = []
61
+ self._free_cpu_blocks: deque[int] = deque()
62
+ self._request_id_to_cpu_blocks: dict[str, list[int]] = {}
63
+ self._request_id_to_group_block_counts: dict[str, list[int]] = {}
64
+
65
+ # Compute the size of the CPU swap pool in blocks
66
+ self._num_cpu_blocks = self._compute_num_cpu_blocks(cpu_offload_space_gib, safety_threshold)
67
+ offloading_enabled = cpu_offload_space_gib is not None and cpu_offload_space_gib > 0
68
+ if self._num_cpu_blocks == 0:
69
+ if offloading_enabled:
70
+ logger.warning(
71
+ f"cpu_offload_space={cpu_offload_space_gib:.1f} GiB is too small for even one block. "
72
+ "No CPU offloading."
73
+ )
74
+ return None
75
+
76
+ # Allocate the CPU swap pool
77
+ cpu_cache_shape = (self._num_cpu_blocks, cache.block_size, cache.num_key_value_heads, cache.head_dim)
78
+ for _ in cache.key_cache:
79
+ self._cpu_key_cache.append(torch.empty(cpu_cache_shape, dtype=cache.dtype, pin_memory=True))
80
+ self._cpu_value_cache.append(torch.empty(cpu_cache_shape, dtype=cache.dtype, pin_memory=True))
81
+
82
+ # Pre-view the GPU cache tensors as block-shaped so the hot copy paths avoid per-op .view() calls
83
+ block_shape = (-1, cache.block_size, cache.num_key_value_heads, cache.head_dim)
84
+ for k_cache, v_cache in zip(cache.key_cache, cache.value_cache):
85
+ self._gpu_key_views.append(k_cache.view(*block_shape))
86
+ self._gpu_value_views.append(v_cache.view(*block_shape))
87
+
88
+ # FIFO order favors contiguity when blocks are returned in bulk
89
+ self._free_cpu_blocks = deque(range(self._num_cpu_blocks))
90
+
91
+ # Reusable int32 scratch for cpu_ids / gpu_ids (bounded by _num_cpu_blocks on both paths)
92
+ self._cpu_ids_scratch = torch.empty(self._num_cpu_blocks, dtype=torch.int32, pin_memory=True)
93
+ self._gpu_ids_scratch = torch.empty(self._num_cpu_blocks, dtype=torch.int32, device=cache.device)
94
+
95
+ # Log the size of the CPU swap pool
96
+ cache_tensor = self._cpu_key_cache[0]
97
+ size_in_bytes = 2 * cache_tensor.numel() * cache_tensor.element_size() * len(cache.key_cache)
98
+ logger.info(
99
+ f"CPU swap pool initialized: {self._num_cpu_blocks} blocks ({size_in_bytes / (1024**3):.2f} GiB pinned)"
100
+ )
101
+
102
+ def _compute_num_cpu_blocks(self, cpu_offload_space_gib: float | None, safety_threshold: float) -> int:
103
+ """Returns the number of blocks that can fit in the CPU swap pool."""
104
+ # Compute the CPU pool size in bytes
105
+ offload_bytes = int(cpu_offload_space_gib * (1024**3)) if cpu_offload_space_gib is not None else None
106
+
107
+ # Determine the maximum number of bytes that can be offloaded based on the safety threshold
108
+ if is_psutil_available():
109
+ import psutil
110
+
111
+ total_ram = psutil.virtual_memory().available
112
+ max_bytes = int(total_ram * safety_threshold)
113
+ else:
114
+ max_bytes = None
115
+
116
+ # If both the request number of bytes and its limit are not None, we just clamp one to the other
117
+ if offload_bytes is not None and max_bytes is not None:
118
+ if offload_bytes > max_bytes:
119
+ clamped_gib = max_bytes / (1024**3)
120
+ logger.warning(
121
+ f"cpu_offload_space={cpu_offload_space_gib:.1f} GiB exceeds {safety_threshold:.0%} of total RAM "
122
+ f"({total_ram / (1024**3):.1f} GiB). Clamping to {clamped_gib:.1f} GiB."
123
+ )
124
+ offload_bytes = max_bytes
125
+ # Else if the max is None, throw a warning and accept the requested number of bytes as is
126
+ elif offload_bytes is not None:
127
+ logger.warning(
128
+ "psutil is not available — cpu_offload_space_safety_threshold cannot be enforced. "
129
+ "Install psutil to enable the safety cap."
130
+ )
131
+ # Else if the requested number of bytes is None, we use the max number of bytes as the requested number of bytes
132
+ elif max_bytes is not None:
133
+ offload_bytes = max_bytes
134
+ logger.warning(f"Auto-sizing CPU swap pool from safety threshold: {max_bytes / (1024**3):.2f} GiB.")
135
+ # Otherwise, it means the pool was supposed to be sized using psutil but it is not available
136
+ else:
137
+ raise ImportError(
138
+ "cpu_offload_space=None requires psutil to auto-size the CPU swap pool. Install psutil or pass an "
139
+ "explicit GiB value."
140
+ )
141
+
142
+ # Compute how many blocks fit in CPU pool
143
+ bytes_per_block = (
144
+ 2 # one for key, one for value
145
+ * len(self.cache.key_cache) # number of layers in a layer group
146
+ * self.cache.block_size # block size
147
+ * self.cache.num_key_value_heads # number of key value heads
148
+ * self.cache.head_dim # head dimension
149
+ * self.cache.dtype.itemsize # data type size in bytes
150
+ ) # fmt: skip
151
+ if bytes_per_block == 0:
152
+ raise ValueError("The number of bytes per block is 0. This is not possible.")
153
+ return offload_bytes // bytes_per_block
154
+
155
+ def _stream_ctx(self):
156
+ """Returns a context manager that runs enclosed ops on the compute stream, or a no-op when none is set."""
157
+ return torch.cuda.stream(self._compute_stream) if self._compute_stream is not None else nullcontext()
158
+
159
+ def offload_one_request(self) -> None:
160
+ """Offload one active request to make room in the GPU cache. Tries CPU offloading first; if the pool is full,
161
+ falls back to the legacy soft reset."""
162
+ scheduler = self.scheduler
163
+ request_id, state = scheduler.pop_request_to_evict()
164
+ logger.info(
165
+ f"Offloading request {request_id} with {len(state.initial_tokens)} initial tokens and "
166
+ f"{len(state.generated_tokens)} generated tokens."
167
+ )
168
+
169
+ # Try CPU offloading first, if it fails, we soft reset the request
170
+ offloaded_to_cpu = self._offload_to_cpu(request_id, state)
171
+ if offloaded_to_cpu:
172
+ # We set the allocated blocks to 0 so the scheduler re-allocates all blocks using position_offset.
173
+ state.allocated_blocks = 0
174
+ # DECODING requests have empty remaining_prefill_tokens, so we use tokens_to_process as a placeholder
175
+ # so the scheduler has at least 1 token to schedule and enters the allocation path.
176
+ if state._status == RequestStatus.DECODING:
177
+ state.remaining_prefill_tokens = state.tokens_to_process[:]
178
+ # Here, the new state is the same as the old one, but with the status set to PENDING. We bypass the setter
179
+ # to avoid the lifespan bookeeping and the associated warning
180
+ state._status = RequestStatus.PENDING
181
+ new_state = state
182
+ logger.debug(f"Offloaded request {request_id} to CPU: {len(self._free_cpu_blocks)} free blocks remaining.")
183
+ else:
184
+ new_state = state.create_equivalent_initial_request()
185
+ state._status = RequestStatus.FINISHED
186
+ logger.debug(f"Soft reset request {request_id}.")
187
+
188
+ scheduler.finish_request(request_id)
189
+ scheduler.add_waiting_request(new_state)
190
+ scheduler.block_new_requests = True
191
+
192
+ def restore_scheduled_requests(self, requests_in_batch: list[FutureRequestState]) -> None:
193
+ """Restore KV caches from CPU for any CPU-offloaded requests in the scheduled batch. Indices are accumulated
194
+ per group across all requests, then copied in one batched operation per layer."""
195
+ cache = self.cache
196
+ all_cpu_indices: list[int] = []
197
+ all_gpu_indices: list[int] = []
198
+
199
+ for future_state in requests_in_batch:
200
+ # Skip state that are not CPU-offloaded
201
+ state = future_state.state
202
+ if not state.is_cpu_offloaded:
203
+ continue
204
+ # TODO: if the H2D copy below raises, already-popped entries leak (never returned to _free_cpu_blocks)
205
+ # Accumulate CPU indices for this request
206
+ cpu_indices = self._request_id_to_cpu_blocks.pop(state.request_id)
207
+ group_counts = self._request_id_to_group_block_counts.pop(state.request_id)
208
+ all_cpu_indices.extend(cpu_indices)
209
+ # Accumulate GPU indices for this request, but since there may be extra block due to re-allocation, slice to
210
+ # match the number of blocks offloaded.
211
+ max_allocated_blocks = 0
212
+ for group_idx, n in enumerate(group_counts):
213
+ gpu_blocks = cache.group_cache_managers[group_idx].block_table.get(state.request_id, [])
214
+ all_gpu_indices.extend(gpu_blocks[:n])
215
+ max_allocated_blocks = max(max_allocated_blocks, n)
216
+ # Restore the state to non-offloaded state
217
+ state.is_cpu_offloaded = False
218
+ state.allocated_blocks = max_allocated_blocks # ensures re-allocation is accounted for
219
+ # Prefix sharing: restored blocks will be re-hashed during the next update
220
+ if cache.allow_block_sharing:
221
+ future_state.complete_blocks += state.position_offset // cache.block_size
222
+ logger.debug(
223
+ f"Restored CPU-offloaded request {state.request_id} with {len(state.initial_tokens)} prefill tokens "
224
+ f"and {len(state.generated_tokens)} generated tokens."
225
+ )
226
+
227
+ # Early return if there are no copy to perform
228
+ if not all_cpu_indices:
229
+ return None
230
+
231
+ # Single batched copy for all requests (still, one copy per layer)
232
+ cpu_ids = self._cpu_ids_scratch[: len(all_cpu_indices)]
233
+ gpu_ids = self._gpu_ids_scratch[: len(all_cpu_indices)]
234
+ cpu_ids.copy_(torch.as_tensor(all_cpu_indices, dtype=torch.int32)) # cpu op, not in the stream
235
+ with self._stream_ctx():
236
+ gpu_ids.copy_(torch.as_tensor(all_gpu_indices, dtype=torch.int32))
237
+ for cpu_k, gpu_k in zip(self._cpu_key_cache, self._gpu_key_views):
238
+ gpu_k[gpu_ids].copy_(cpu_k[cpu_ids])
239
+ for cpu_v, gpu_v in zip(self._cpu_value_cache, self._gpu_value_views):
240
+ gpu_v[gpu_ids].copy_(cpu_v[cpu_ids])
241
+ self._free_cpu_blocks.extend(all_cpu_indices)
242
+
243
+ def free_request_cpu_cache(self, state: RequestState) -> None:
244
+ """Free CPU blocks for a single request (e.g., on cancellation)."""
245
+ if state.is_cpu_offloaded:
246
+ self._return_cpu_blocks(state.request_id)
247
+ state.is_cpu_offloaded = False
248
+
249
+ def free_all_waiting_cpu_caches(self) -> None:
250
+ """Free all CPU-offloaded caches in the waiting queue (e.g., on fail_all or reset)."""
251
+ for state in self.scheduler.waiting_requests.values():
252
+ self.free_request_cpu_cache(state)
253
+
254
+ def reset(self) -> None:
255
+ """Reset CPU offloading state for a new generation session."""
256
+ self.free_all_waiting_cpu_caches()
257
+ self._request_id_to_cpu_blocks.clear()
258
+ self._request_id_to_group_block_counts.clear()
259
+ self._free_cpu_blocks = deque(range(self._num_cpu_blocks))
260
+
261
+ def _offload_to_cpu(self, request_id: str, state: RequestState) -> bool:
262
+ """Copy a request's KV cache blocks from GPU to the static CPU swap pool. Returns True on success, False if
263
+ the pool is full."""
264
+
265
+ # Get the indices to offload from
266
+ gpu_indices = []
267
+ group_block_counts = []
268
+ for cm in self.cache.group_cache_managers:
269
+ blocks = cm.block_table.get(request_id, [])
270
+ gpu_indices.extend(blocks)
271
+ group_block_counts.append(len(blocks))
272
+
273
+ # No CPU offloading if there are no blocks to offload or not enough free blocks in the CPU swap pool
274
+ total_gpu_blocks = len(gpu_indices)
275
+ if total_gpu_blocks == 0 or len(self._free_cpu_blocks) < total_gpu_blocks:
276
+ return False
277
+
278
+ # Reserve CPU blocks from the free pool
279
+ cpu_indices = [self._free_cpu_blocks.popleft() for _ in range(total_gpu_blocks)]
280
+
281
+ # Offload using the compute stream so it does not interfere with current generation
282
+ cpu_ids = self._cpu_ids_scratch[:total_gpu_blocks]
283
+ gpu_ids = self._gpu_ids_scratch[:total_gpu_blocks]
284
+ cpu_ids.copy_(torch.as_tensor(cpu_indices, dtype=torch.int32)) # cpu op, not in the stream
285
+ with self._stream_ctx():
286
+ gpu_ids.copy_(torch.as_tensor(gpu_indices, dtype=torch.int32))
287
+ # Keys
288
+ for cpu_key_cache, gpu_key_view in zip(self._cpu_key_cache, self._gpu_key_views):
289
+ cpu_key_cache[cpu_ids].copy_(gpu_key_view[gpu_ids])
290
+ # Values
291
+ for cpu_value_cache, gpu_value_view in zip(self._cpu_value_cache, self._gpu_value_views):
292
+ cpu_value_cache[cpu_ids].copy_(gpu_value_view[gpu_ids])
293
+ # TODO: add asynchronous version of this
294
+ # TODO: can we get rid of this for loop? eg. by consolidating the cache.
295
+
296
+ # No explicit sync needed: finish_request is logical, and the next forward pass serializes on the same stream.
297
+ self._request_id_to_cpu_blocks[request_id] = cpu_indices
298
+ self._request_id_to_group_block_counts[request_id] = group_block_counts
299
+ state.is_cpu_offloaded = True
300
+ return True
301
+
302
+ def _return_cpu_blocks(self, request_id: str) -> tuple[list[int], list[int]]:
303
+ """Return CPU blocks to the free pool without copying anything."""
304
+ cpu_ids = self._request_id_to_cpu_blocks.pop(request_id)
305
+ group_counts = self._request_id_to_group_block_counts.pop(request_id)
306
+ self._free_cpu_blocks.extend(cpu_ids)
307
+ return cpu_ids, group_counts
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/requests.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import time
15
+ from copy import deepcopy
16
+ from dataclasses import dataclass, field
17
+ from enum import IntEnum
18
+
19
+ import torch
20
+
21
+ from ...utils import is_psutil_available, is_torch_xpu_available
22
+ from ...utils.logging import logging
23
+ from ...utils.metrics import traced
24
+
25
+
26
+ if is_psutil_available():
27
+ import psutil
28
+
29
+ # This is a temporary token ID used to represent a token that is not yet generated
30
+ # TODO: update this to 0 and check it breaks nothing + simplify carry over and time new logic
31
+ TMP_TOKEN_ID = -1
32
+
33
+
34
+ # We centralize the logger here to coordinate between logging and progress bar
35
+ logger = logging.getLogger("ContinuousBatchingLogger")
36
+ # Add a handler to the logger to print the logs to the console. Only happens once thanks to setting propagate to False.
37
+ if logger.propagate:
38
+ handler = logging.StreamHandler()
39
+ handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
40
+ logger.addHandler(handler)
41
+ logger.propagate = False
42
+
43
+
44
+ def get_device_and_memory_breakdown() -> tuple[torch.device, int, int, int]:
45
+ if torch.cuda.is_available():
46
+ device = torch.device("cuda")
47
+ torch.cuda.empty_cache()
48
+ torch.cuda.synchronize()
49
+ # Use mem_get_info to get actual free memory: device_properties().total_memory returns the physical device
50
+ # total which ignores CUDA context and driver overhead (~0.5 GiB), leading to overcommit.
51
+ free_memory, total_memory = torch.cuda.mem_get_info(device)
52
+ reserved_memory = torch.cuda.memory_reserved(device)
53
+ allocated_memory = total_memory - free_memory
54
+ elif is_torch_xpu_available():
55
+ device = torch.device("xpu")
56
+ torch.xpu.empty_cache()
57
+ torch.xpu.synchronize()
58
+ total_memory = torch.xpu.get_device_properties(device).total_memory
59
+ reserved_memory = torch.xpu.memory_reserved(device)
60
+ allocated_memory = torch.xpu.memory_allocated(device)
61
+ elif torch.backends.mps.is_available() and torch.backends.mps.is_built():
62
+ device = torch.device("mps")
63
+ # MPS memory reporting (PyTorch 2.0+)
64
+ total_memory = torch.mps.driver_allocated_memory()
65
+ allocated_memory = total_memory - getattr(torch.mps, "recommended_max_memory")()
66
+ reserved_memory = 0 # MPS does not track reserved separately
67
+ else:
68
+ device = torch.device("cpu")
69
+ if is_psutil_available():
70
+ total_memory = psutil.virtual_memory().total
71
+ allocated_memory = psutil.Process().memory_info().rss
72
+ reserved_memory = allocated_memory
73
+ else:
74
+ logger.error(
75
+ "Cannot get memory breakdown on CPU without psutil: returning 0 for all memory values. Please install "
76
+ "psutil to get an actual memory breakdown."
77
+ )
78
+ total_memory = 0
79
+ reserved_memory = 0
80
+ allocated_memory = 0
81
+
82
+ return device, total_memory, reserved_memory, allocated_memory
83
+
84
+
85
+ class RequestStatus(IntEnum):
86
+ """Status of a generation request through its lifecycle."""
87
+
88
+ PENDING = 0
89
+ PREFILLING = 1
90
+ DECODING = 2
91
+ FINISHED = 3
92
+ FAILED = 4
93
+
94
+
95
+ @dataclass
96
+ class GenerationOutput:
97
+ """Tracks the output of a generation request.
98
+
99
+ Attributes:
100
+ request_id (str): The ID of the generation request.
101
+ prompt_ids (list[int]): The IDs of the prompt tokens.
102
+ generated_tokens (list[int]): The generated tokens.
103
+ logprobs (list[float]): The log probabilities of the generated tokens.
104
+ error (Optional[str]): Any error message associated with the request. When None, the request was successful.
105
+ status (RequestStatus): The status of the request.
106
+ created_time (float): The time the request was created.
107
+ lifespan (tuple[float, float]): The time the request was no longer pending and the time the request finished.
108
+ """
109
+
110
+ request_id: str
111
+ prompt_ids: list[int] = field(default_factory=list)
112
+ generated_tokens: list[int] = field(default_factory=list)
113
+ logprobs: list[float] = field(default_factory=list)
114
+ error: str | None = None
115
+ status: RequestStatus = RequestStatus.PENDING
116
+ created_time: float = field(default_factory=time.perf_counter)
117
+ lifespan: tuple[float, float] = (-1, -1) # (time request was no longer pending, time request finished)
118
+ timestamps: list[float] | None = None # Timestamps of the generated tokens
119
+
120
+ def is_finished(self) -> bool:
121
+ return self.status == RequestStatus.FINISHED
122
+
123
+
124
+ @dataclass
125
+ class RequestState:
126
+ """Tracks the state of a generation request through its lifecycle.
127
+
128
+ Attributes:
129
+ request_id (str): The ID of the generation request.
130
+ initial_tokens (list[int]): The initial prompt tokens.
131
+ num_children (int): The number of children requests
132
+ full_prompt_ids (list[int] | None): The tokens IDs of the full prompt.
133
+ prompt_ids (list[int] | None): The tokens IDs currently being processed.
134
+ remaining_prompt_ids (list[int]): The initial tokens IDs remaining to be processed.
135
+ static_outputs (list[int]): The generated tokens.
136
+ allocated_blocks (int): The number of blocks allocated to the request.
137
+ position_offset (int): The current position in the sequence for position_ids.
138
+ status (RequestStatus): The status of the request: can be one of PENDING, PREFILLING, PREFILLING_SPLIT,
139
+ SPLIT_PENDING_REMAINDER, DECODING, FINISHED, FAILED
140
+ max_new_tokens (int | None): The maximum number of new tokens to generate.
141
+ eos_token_id (None | int | list[int]): The ID(s) of the end-of-sequence tokens. Only used in post-init.
142
+ _eos_token_ids (set[int]): The IDs of the end-of-sequence tokens, formatted as a set.
143
+ streaming (bool): Whether to stream tokens as they're generated
144
+ created_time (float): The time the request was created.
145
+ error (Optional[str]): Any error message associated with the request. When None, has had no error yet.
146
+ """
147
+
148
+ # Required fields
149
+ request_id: str
150
+ initial_tokens: list[int] # Initial prompt tokens # TODO: rename this as prefill tokens
151
+
152
+ # Optional fields (CB parameters)
153
+ streaming: bool = False # Whether to stream tokens as they're generated
154
+ record_timestamps: bool = False # Whether to record timestamps for the generated tokens
155
+
156
+ # Optional fields (generation parameters)
157
+ max_new_tokens: int | None = 20 # Maximum number of new tokens to generate. None means no limit. Default to 20.
158
+ eos_token_id: int | list[int] | None = None # ID(s) of the end-of-sequence tokens. Only used in post-init.
159
+ num_children: int = 0 # Number of children requests
160
+ logit_processor_kwargs: dict = field(default_factory=dict) # Keyword arguments for the logits processor.
161
+
162
+ # Internal fields (for scheduling)
163
+ tokens_to_process: list[int] = field(default_factory=list) # Tokens IDs currently being processed
164
+ generated_tokens: list[int] = field(default_factory=list) # Generated tokens
165
+ logprobs: list[float] = field(default_factory=list) # Log probabilities of the generated tokens
166
+ position_offset: int = 0 # Current position in the sequence for position_ids
167
+ allocated_blocks: int = 0 # Number of blocks allocated to the request
168
+
169
+ _status: RequestStatus = RequestStatus.PENDING # Status of the request, hidden behind a property
170
+ _eos_token_ids: set[int] = field(default_factory=set) # IDs of the end-of-sequence tokens, formatted as a set
171
+
172
+ # Internal fields (for tracking)
173
+ created_time: float = field(default_factory=time.perf_counter) # Time the request was created
174
+ error: str | None = None # Error message if the request failed
175
+ lifespan: tuple[float, float] = (-1, -1) # (time request was no longer pending, time request finished)
176
+ _timestamps: list[float] = field(default_factory=list) # Timestamps of the generated tokens
177
+ _true_initial_tokens: int = 0 # The true number of initial tokens, useful when soft resetting requests
178
+ # TODO: remove the attribute above to _num_initial_tokens once initial_tokens is renamed
179
+
180
+ # Fields overwritten in __post_init__
181
+ _new_tokens_limit: int = 2147483647 # An int to check the max number of new tokens w/out always comparing w/ None
182
+ remaining_prefill_tokens: list[int] = field(default_factory=list) # Initial tokens left to process
183
+ is_cpu_offloaded: bool = False # True when the request's KV cache is in the CPU swap pool
184
+
185
+ def __post_init__(self):
186
+ # If no max length is set, we set an absurdly high value which will never be reached
187
+ self._new_tokens_limit = 2147483647 if self.max_new_tokens is None else self.max_new_tokens
188
+ # Keep a copy of the initial tokens to process
189
+ self.remaining_prefill_tokens = self.initial_tokens[:]
190
+ # Format the EOS token ID(s) as a set of ints. If there is no EOS token ID, it's an empty set
191
+ if self.eos_token_id is None:
192
+ pass
193
+ # If there is a single EOS token ID, add it to the set only if the ID is valid, ie. non-negative
194
+ elif isinstance(self.eos_token_id, int):
195
+ if self.eos_token_id >= 0:
196
+ self._eos_token_ids.add(self.eos_token_id)
197
+ # If there are multiple EOS token IDs, add them to the set only if they are valid, ie. non-negative
198
+ else:
199
+ for token_id in self.eos_token_id:
200
+ if token_id >= 0:
201
+ self._eos_token_ids.add(token_id)
202
+
203
+ @property
204
+ def status(self) -> RequestStatus:
205
+ return self._status
206
+
207
+ @status.setter
208
+ def status(self, value: RequestStatus):
209
+ if self._status == RequestStatus.PENDING:
210
+ self.lifespan = (time.perf_counter(), -1)
211
+ elif value == RequestStatus.FINISHED:
212
+ self.lifespan = (self.lifespan[0], time.perf_counter())
213
+ self.log_end_of_request()
214
+ self._status = value
215
+
216
+ @property
217
+ def timestamps(self) -> list[float] | None:
218
+ return self._timestamps if self.record_timestamps else None
219
+
220
+ def log_end_of_request(self):
221
+ prefill_len = len(self.initial_tokens)
222
+ decode_len = self.generated_len()
223
+ start_time = self.lifespan[0] - self.created_time
224
+ end_time = self.lifespan[1] - self.created_time
225
+ logger.info(
226
+ f"Request {self.request_id} finished: {prefill_len = } {decode_len = } {start_time = } {end_time = }"
227
+ )
228
+
229
+ def current_len(self) -> int:
230
+ """Get the current length of the sequence (prompt + generated tokens)."""
231
+ return self.position_offset
232
+
233
+ def generated_len(self) -> int:
234
+ """Get the number of tokens generated so far."""
235
+ return len(self.generated_tokens)
236
+
237
+ # TODO: this logic seems one token off, check it out
238
+ @traced
239
+ def update_and_check_completion(self, token_id: int, logprob: float | None) -> bool:
240
+ """Update the request with a newly generated token (and optional log probability of the token) and check for
241
+ completion. Returns True if the request is now complete, False otherwise."""
242
+ # Only update if we're in decoding state # TODO: seems useless (always true) -- remove this
243
+ if self.status != RequestStatus.DECODING:
244
+ return False
245
+
246
+ # If we're recording timestamps, add timestamp to the list
247
+ if self.record_timestamps:
248
+ self._timestamps.append(time.perf_counter())
249
+
250
+ # Stop if we reached an EOS token
251
+ is_eos = token_id in self._eos_token_ids
252
+ current_len = self.generated_len()
253
+
254
+ # Replace the temporary token if we're not finishing due to max length
255
+ # (EOS tokens should still be added to the output)
256
+ if is_eos or (current_len < self._new_tokens_limit):
257
+ self.generated_tokens.append(token_id)
258
+ self.tokens_to_process = [token_id] # this works for 2 levels of pipelines, but not sure for more
259
+ current_len += 1
260
+ if logprob is not None:
261
+ self.logprobs.append(logprob)
262
+ else:
263
+ logger.warning(f"Request {self.request_id} generated a useless token: {token_id}")
264
+
265
+ if is_eos or current_len >= self._new_tokens_limit:
266
+ self.status = RequestStatus.FINISHED
267
+ return True
268
+ return False # We still need to process more tokens
269
+
270
+ def __repr__(self):
271
+ msg = [
272
+ f"request_id={self.request_id}",
273
+ f"status={self._status}",
274
+ f"out_tokens={self.generated_len()}",
275
+ f"query_length={len(self.tokens_to_process)}",
276
+ f"remaining_tokens={len(self.remaining_prefill_tokens)}",
277
+ f"kv_length={self.position_offset}",
278
+ f"full_prompt_length={len(self.initial_tokens)}",
279
+ f"allocated_blocks={self.allocated_blocks}",
280
+ f"generated_tokens={self.generated_tokens}",
281
+ f"logit_processor_kwargs={self.logit_processor_kwargs}",
282
+ ]
283
+ return "RequestState(\n\t" + ",\n\t".join(msg) + "\n)"
284
+
285
+ def to_generation_output(self):
286
+ """Convert the request state to a GenerationOutput object."""
287
+ if self._true_initial_tokens:
288
+ self.generated_tokens = self.initial_tokens[self._true_initial_tokens :] + self.generated_tokens
289
+ self.initial_tokens = self.initial_tokens[: self._true_initial_tokens]
290
+ return GenerationOutput(
291
+ request_id=self.request_id,
292
+ prompt_ids=self.initial_tokens,
293
+ generated_tokens=self.generated_tokens,
294
+ logprobs=self.logprobs,
295
+ error=self.error,
296
+ status=self.status,
297
+ created_time=self.created_time,
298
+ lifespan=self.lifespan,
299
+ timestamps=self.timestamps,
300
+ )
301
+
302
+ def fork(self, new_request_id: str) -> "RequestState":
303
+ """Fork the request into a new request with the same state except for request_id, created_time and lifespan."""
304
+ new_request = deepcopy(self)
305
+ # Update tracking fields
306
+ new_request.request_id = new_request_id
307
+ new_request.created_time = time.perf_counter()
308
+ new_request.lifespan = (new_request.created_time, -1)
309
+ new_request._timestamps = []
310
+ # Update fields overwritten in __post_init__
311
+ new_request.remaining_prefill_tokens = self.remaining_prefill_tokens[:]
312
+ return new_request
313
+
314
+ def get_request_config(self) -> dict:
315
+ """Get all the fields necessary to create a request that would have the same configuration."""
316
+ return {
317
+ "streaming": self.streaming,
318
+ "record_timestamps": self.record_timestamps,
319
+ "max_new_tokens": self.max_new_tokens,
320
+ "eos_token_id": self.eos_token_id,
321
+ "num_children": self.num_children,
322
+ "logit_processor_kwargs": deepcopy(self.logit_processor_kwargs),
323
+ }
324
+
325
+ def create_equivalent_initial_request(self) -> "RequestState":
326
+ """Creates an equivalent new request by removing the generated tokens and adding them to the initial prompt. The
327
+ created request has THE SAME request_id. Notably, we can retrieve the original request from the created one with
328
+ the _true_initial_tokens attribute. The logprobs of the generated tokens are kept in the new request."""
329
+
330
+ request_config = self.get_request_config()
331
+ # If there is a number of max new tokens, we update it to account for the already generated tokens
332
+ if self.max_new_tokens is not None:
333
+ request_config["max_new_tokens"] = self.max_new_tokens - len(self.generated_tokens)
334
+ # Create new request state
335
+ new_state = RequestState(
336
+ request_id=self.request_id,
337
+ initial_tokens=self.initial_tokens + self.generated_tokens,
338
+ logprobs=self.logprobs[:],
339
+ _true_initial_tokens=self._true_initial_tokens + len(self.initial_tokens),
340
+ **request_config,
341
+ )
342
+ # If the request has been soft reset once already, this stays the same
343
+ if self._true_initial_tokens:
344
+ new_state._true_initial_tokens = self._true_initial_tokens
345
+ # Otherwise, we set the true initial tokens to the number of initial tokens
346
+ else:
347
+ new_state._true_initial_tokens = len(self.initial_tokens)
348
+ return new_state
349
+
350
+
351
+ class FutureRequestState:
352
+ """Tracks the current state of a request and the relevant information to update it."""
353
+
354
+ # This makes instantiating this class faster
355
+ __slots__ = ("state", "has_new_token", "complete_blocks", "query_length")
356
+
357
+ def __init__(self, state: RequestState, has_new_token: bool, complete_blocks: int, query_length: int) -> None:
358
+ self.state = state
359
+ self.has_new_token = has_new_token
360
+ self.complete_blocks = complete_blocks
361
+ self.query_length = query_length
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/scheduler.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Inc. team
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import threading
15
+ from abc import ABC, abstractmethod
16
+ from collections import deque
17
+
18
+ from ...utils.metrics import attach_tracer, traced
19
+ from .cache import PagedAttentionCache
20
+ from .requests import FutureRequestState, RequestState, RequestStatus, logger
21
+
22
+
23
+ class Scheduler(ABC):
24
+ """
25
+ Abstract base class for scheduling requests in the continuous batch processor. Schedulers manage the lifecycle of
26
+ requests from when they are added to the waiting queue to when they are scheduled for processing. Different
27
+ schedulers implement different strategies for prioritizing and batching requests.
28
+ """
29
+
30
+ def __init__(self, cache: PagedAttentionCache):
31
+ self.cache = cache
32
+ self._cancellation_lock = threading.Lock()
33
+ # This is to compute the read cache used by a new request being scheduled
34
+ self.read_cache_limit = None if self.cache.num_full_attention_groups else self.cache.config.sliding_window
35
+ self.max_decode_fast_path_length = self.cache.max_blocks_per_request * self.cache.block_size
36
+ # Initialize mutable states via reset()
37
+ self.reset()
38
+
39
+ def reset(self) -> None:
40
+ """Reset scheduler state for a new generation loop."""
41
+ self.active_requests: dict[str, RequestState] = {}
42
+ self.waiting_requests: dict[str, RequestState] = {}
43
+ self.waiting_requests_order: deque[str] = deque()
44
+ self._requests_to_cancel: set[str] = set()
45
+ self._requests_to_fork: list[RequestState] = []
46
+ self.block_new_requests = False
47
+
48
+ @traced
49
+ def add_waiting_request(self, state: RequestState):
50
+ """Adds a request to the waiting list."""
51
+ self.waiting_requests[state.request_id] = state
52
+ self.waiting_requests_order.append(state.request_id)
53
+
54
+ @abstractmethod
55
+ def schedule_batch(
56
+ self, token_budget: int, cache_budget: int
57
+ ) -> tuple[list[FutureRequestState] | None, bool, int, int]:
58
+ """Schedules requests for the next batch based on available token and cache budgets. This method selects which
59
+ requests should be processed in the current batch, considering the budgets and the scheduler's prioritization
60
+ rules. The token_budget is the maximum number of tokens that can be processed in a batch, and the cache_budget
61
+ is the maximum number of KV cache entries that can be read in a batch.
62
+ Returns the list of scheduled requests in their "FutureRequestState" form, a boolean indicating if the decode
63
+ fast path can be used, the total number of query tokens and the maximum number of kv tokens read."""
64
+
65
+ @traced
66
+ def has_pending_requests(self) -> bool:
67
+ """Checks if there are requests ready to be processed."""
68
+ return bool(len(self.active_requests) or len(self.waiting_requests))
69
+
70
+ @traced
71
+ def finish_request(self, request_id: str) -> None:
72
+ """Completes processing of a request and frees its allocated cache blocks. This method is called
73
+ when a request has finished generation or encountered an error.
74
+ """
75
+ self.cache.free_blocks(request_id)
76
+ self.active_requests.pop(request_id, None)
77
+
78
+ def pop_request_to_evict(self) -> tuple[str, RequestState]:
79
+ """Remove and return an active request chosen as the eviction victim for cache-pressure offload or soft reset.
80
+ Picks the newest active request when `block_new_requests` is set, else the oldest."""
81
+ if self.block_new_requests:
82
+ return self.active_requests.popitem()
83
+ request_id = next(iter(self.active_requests))
84
+ return request_id, self.active_requests.pop(request_id)
85
+
86
+ @traced
87
+ def get_active_request_static_outputs(self, request_id: str) -> list[int]:
88
+ """Gets generated tokens for an active request."""
89
+ if request_id in self.active_requests:
90
+ return self.active_requests[request_id].generated_tokens
91
+ return []
92
+
93
+ @traced
94
+ def set_request_cancellation(self, request_id: str):
95
+ """Marks a request for cancellation."""
96
+ with self._cancellation_lock:
97
+ self._requests_to_cancel.add(request_id)
98
+
99
+ @traced
100
+ def clear_cancelled_requests(self) -> list[RequestState]:
101
+ """Remove all cancelled requests from active and waiting queues."""
102
+ cancelled_states = []
103
+ with self._cancellation_lock:
104
+ for request_id in self._requests_to_cancel:
105
+ state_a = self.active_requests.pop(request_id, None)
106
+ state_w = self.waiting_requests.pop(request_id, None)
107
+ # Invariant: a request is never in both queues; state_a or state_w picks the one it was in
108
+ state = state_a or state_w
109
+ if state is not None:
110
+ cancelled_states.append(state)
111
+ if request_id in self.waiting_requests_order:
112
+ self.waiting_requests_order.remove(request_id)
113
+ self.cache.free_blocks(request_id)
114
+ self._requests_to_cancel = set()
115
+ return cancelled_states
116
+
117
+ @traced
118
+ def request_is_cancelled(self, request_id: str) -> bool:
119
+ """Checks if a request has been cancelled or removed."""
120
+ return request_id in self._requests_to_cancel or (
121
+ request_id not in self.active_requests and request_id not in self.waiting_requests
122
+ )
123
+
124
+ @traced
125
+ def _allocate_blocks_if_needed(self, state: RequestState, len_next_tokens: int) -> bool:
126
+ """Allocate additional cache blocks for a request if the currently allocated blocks are insufficient to
127
+ accommodate the next tokens. It calculates how many blocks are needed based on the request's current
128
+ cache occupancy and the number of tokens to be processed. The allocation itself is done by the CacheAllocator
129
+ objects. Returns a boolean indicating if the allocation was successful or not.
130
+ """
131
+ # First we check that the occupancy is less than the requested length, then we allocate enough blocks to cover
132
+ # the requested length. This is done using `current_len` so it also works for offloaded requests.
133
+ current_len = state.current_len()
134
+ occupancy = state.allocated_blocks * self.cache.block_size - current_len
135
+ if occupancy < len_next_tokens or state.allocated_blocks == 0:
136
+ blocks_needed = ((len_next_tokens - occupancy + 1) // self.cache.block_size) + 1
137
+ allocated = self.cache.allocate_blocks(blocks_needed, state.request_id, state.allocated_blocks)
138
+ if allocated is None:
139
+ return False
140
+ state.allocated_blocks += allocated
141
+ return True
142
+
143
+ def _infer_request_tokens(self, state: RequestState, request_ids_to_remove_from_waiting: set[str]) -> list[int]:
144
+ """Prepares a request for processing in the current batch. If prefix sharing is enabled, and the request was
145
+ pending, this is where we look for a prefix match and split the request if found."""
146
+ # If prefix sharing is enabled, we look for a prefix match and split the request if found
147
+ if self.cache.use_prefix_sharing and state.status == RequestStatus.PENDING and not state.is_cpu_offloaded:
148
+ prefill_length = self.cache.search_prefix_match(state.request_id, state.remaining_prefill_tokens)
149
+ if prefill_length > 0:
150
+ self.active_requests[state.request_id] = state
151
+ request_ids_to_remove_from_waiting.add(state.request_id)
152
+ state.status = RequestStatus.PREFILLING
153
+ # We keep track of the number of allocated blocks to avoid double allocation
154
+ state.allocated_blocks += prefill_length // self.cache.block_size
155
+ # Even if we match the whole request, we keep at least 1 token to start decoding
156
+ prefill_length = min(prefill_length, len(state.remaining_prefill_tokens) - 1)
157
+ state.remaining_prefill_tokens = state.remaining_prefill_tokens[prefill_length:]
158
+ state.position_offset += prefill_length
159
+
160
+ # If the request is decoding, the tokens to process are already set
161
+ if state.status == RequestStatus.DECODING:
162
+ request_tokens = state.tokens_to_process
163
+ # Otherwise, the tokens to process are the remaining prefill tokens
164
+ else:
165
+ request_tokens = state.remaining_prefill_tokens
166
+ return request_tokens
167
+
168
+ def _schedule_request(
169
+ self,
170
+ state: RequestState,
171
+ request_tokens: list[int],
172
+ token_budget: int,
173
+ request_ids_to_remove_from_waiting: set[str],
174
+ ) -> None:
175
+ """Schedules a request for the current batch, updating the request's status according to the token budget left.
176
+ After a request is scheduled, it is part of the next batch unless there is an error.
177
+ If the request has children (for parallel decoding), it ensures at least one token remains before the request is
178
+ forked."""
179
+ # If the request has one or more children we make sure not to prefill it entirely
180
+ # This does not check the request state, but DECODING request already have children set to 0.
181
+ if state.num_children > 0 and token_budget >= len(request_tokens) - 1:
182
+ token_budget = len(request_tokens) - 1
183
+ self._requests_to_fork.append(state)
184
+
185
+ # Case: we can process the entire prompt/remainder
186
+ if len(request_tokens) <= token_budget:
187
+ if state.status == RequestStatus.PENDING:
188
+ self.active_requests[state.request_id] = state
189
+ request_ids_to_remove_from_waiting.add(state.request_id)
190
+ if state.status <= RequestStatus.PREFILLING:
191
+ state.tokens_to_process = state.remaining_prefill_tokens
192
+ state.remaining_prefill_tokens = []
193
+ # Although prefill will only be done after the batch being scheduled now, we set the status to DECODING
194
+ # to stay coherent when using asynchronous batching
195
+ state.status = RequestStatus.DECODING
196
+
197
+ # Otherwise: we need to split the request
198
+ else:
199
+ if state.status == RequestStatus.PENDING:
200
+ self.active_requests[state.request_id] = state
201
+ state.status = RequestStatus.PREFILLING
202
+ request_ids_to_remove_from_waiting.add(state.request_id)
203
+ state.remaining_prefill_tokens = request_tokens[token_budget:]
204
+ state.tokens_to_process = request_tokens[:token_budget]
205
+
206
+ def _process_candidates(
207
+ self,
208
+ candidates: list[RequestState],
209
+ token_budget: int,
210
+ cache_budget: int,
211
+ request_ids_to_remove_from_waiting: set[str],
212
+ safety_margin: float = 0.0,
213
+ ) -> tuple[list[FutureRequestState], bool, bool, int, int]:
214
+ """Schedules candidate requests for the current batch.
215
+
216
+ This method contains the common logic shared by all schedulers: it checks token and cache budgets, allocates
217
+ cache blocks if needed, updates request states, and tracks which waiting requests should be removed from the
218
+ waiting queue.
219
+ """
220
+ scheduled_requests = []
221
+ one_allocation_failed = False
222
+ decode_fast_path = self.cache.max_blocks_per_request > 0 # best way to check if decode fast path availability
223
+ safety_margins = safety_margin * self.cache.num_blocks
224
+ original_token_budget, original_cache_budget = token_budget, cache_budget
225
+
226
+ for state in candidates:
227
+ num_free_blocks = self.cache.get_num_free_blocks()
228
+ # If we are out the safety margin, we only accept decoding requests or the first prefill request
229
+ outside_safety_margin = num_free_blocks < safety_margins
230
+ if outside_safety_margin and scheduled_requests and state.status != RequestStatus.DECODING:
231
+ logger.info(
232
+ f"Outside safety margin, breaking out of scheduling loop. {num_free_blocks = } {safety_margins = }"
233
+ )
234
+ break
235
+
236
+ # Infer the tokens that will be present in the batch if token budget is enough
237
+ request_tokens = self._infer_request_tokens(state, request_ids_to_remove_from_waiting)
238
+ # Account for token budget
239
+ request_len = min(len(request_tokens), token_budget)
240
+
241
+ # This block checks cache budget: decode batches have infinite budget, but varlen batches don't, because KV
242
+ # cache is read through a fixed-sized index tensor. We keep track of the current budget in case the batch
243
+ # goes from decode to varlen
244
+ is_decode_eligible = request_len == 1 and state.position_offset < self.max_decode_fast_path_length
245
+ read_cache_needed = state.current_len()
246
+ if self.read_cache_limit is not None:
247
+ read_cache_needed = min(read_cache_needed, self.read_cache_limit)
248
+ # A request that would change the batch from decode to varlen is rejected if the cache budget is too low
249
+ if not (decode_fast_path and is_decode_eligible) and cache_budget < read_cache_needed:
250
+ continue
251
+
252
+ # Check there will be enough cache for the new tokens
253
+ allocation_successful = self._allocate_blocks_if_needed(state, request_len)
254
+
255
+ # If the allocation would not be successful, we move on to the next request
256
+ if not allocation_successful:
257
+ one_allocation_failed = True
258
+ # If we reached a waiting request and the cache is full, all subsequent waiting requests will need
259
+ # allocation as well, so we can safely break out of the scheduling loop.
260
+ if num_free_blocks == 0 and state.request_id in self.waiting_requests:
261
+ logger.info(f"Breaking mid-loop for request {state.request_id} because the cache is full")
262
+ break
263
+ continue
264
+
265
+ # If this point is reached, it means we can safely schedule the request
266
+ self._schedule_request(state, request_tokens, token_budget, request_ids_to_remove_from_waiting)
267
+ request_len = len(state.tokens_to_process) # it may change after scheduling
268
+
269
+ # The decode fast path is only used if the request is a single token and its length is less than the max blocks per request
270
+ decode_fast_path &= request_len == 1 and state.position_offset < self.max_decode_fast_path_length
271
+
272
+ # Update the token and cache budgets
273
+ token_budget -= request_len
274
+ cache_budget -= read_cache_needed
275
+
276
+ # If using prefix sharing, we make note of the blocks that will be computed in the forward pass
277
+ if self.cache.allow_block_sharing:
278
+ tokens_in_current_block = state.current_len() % self.cache.block_size
279
+ tokens_after_forward = tokens_in_current_block + request_len
280
+ complete_blocks = tokens_after_forward // self.cache.block_size
281
+ else:
282
+ complete_blocks = 0
283
+
284
+ # Store the future request state
285
+ has_new_token = not state.remaining_prefill_tokens
286
+ scheduled_requests.append(FutureRequestState(state, has_new_token, complete_blocks, request_len))
287
+
288
+ # Remove the request from the waiting queue and mark it as removed
289
+ req_id = state.request_id
290
+ was_waiting = self.waiting_requests.pop(req_id, None) is not None
291
+ if was_waiting:
292
+ request_ids_to_remove_from_waiting.add(req_id)
293
+
294
+ # Early exit of the loop if we have no budget left
295
+ if token_budget == 0 or (cache_budget <= 0 and not decode_fast_path):
296
+ break
297
+
298
+ num_q_tokens = original_token_budget - token_budget
299
+ max_kv_read = original_cache_budget - cache_budget
300
+ return scheduled_requests, one_allocation_failed, decode_fast_path, num_q_tokens, max_kv_read
301
+
302
+ def _get_waiting_candidates(self) -> list[RequestState]:
303
+ """Returns waiting requests in priority order. Since CPU-offloaded requests are cheaper to restore than fresh
304
+ requests, they get priority, but we interleave them with fresh request to not saturate new batches with only
305
+ offloaded requests."""
306
+ offloaded: deque[RequestState] = deque()
307
+ fresh: deque[RequestState] = deque()
308
+ for req_id in self.waiting_requests_order:
309
+ state = self.waiting_requests[req_id]
310
+ (offloaded if state.is_cpu_offloaded else fresh).append(state)
311
+ ordered: list[RequestState] = []
312
+ while offloaded or fresh:
313
+ if offloaded:
314
+ ordered.append(offloaded.popleft())
315
+ if fresh:
316
+ ordered.append(fresh.popleft())
317
+ return ordered
318
+
319
+ def _cleanup_waiting_queue(self, request_ids_to_remove_from_waiting: set[str]) -> None:
320
+ """Removes processed requests from the waiting queue order."""
321
+ self.waiting_requests_order = deque(
322
+ [req_id for req_id in self.waiting_requests_order if req_id not in request_ids_to_remove_from_waiting]
323
+ )
324
+
325
+
326
+ # TODO: further common-ize the two classes
327
+ @attach_tracer()
328
+ class FIFOScheduler(Scheduler):
329
+ """This scheduler processes requests in the order they arrive, meaning decoding requests has priority over
330
+ prefilling requests. Additionally, it includes a safety margin mechanism to prevent cache exhaustion. By default,
331
+ when 80% of the cache is full, new requests will not be scheduled to prioritize decoding active requests."""
332
+
333
+ def __init__(self, cache: PagedAttentionCache, safety_margin: float = 0.2):
334
+ """Initializes the FIFO scheduler. The safety margin is the percentage of free blocks under which we stop
335
+ scheduling new prefill requests, so safety_margin = 0.1 means that when there is less than 10% of free blocks,
336
+ or equivalently when more than 90% of blocks are already allocated, we stop scheduling new prefill requests.
337
+ """
338
+ super().__init__(cache)
339
+ self.safety_margin = safety_margin
340
+
341
+ @traced
342
+ def schedule_batch(
343
+ self, token_budget: int, cache_budget: int
344
+ ) -> tuple[list[FutureRequestState] | None, bool, int, int]:
345
+ priority_states: list[RequestState] = []
346
+ second_priority_states: list[RequestState] = []
347
+
348
+ for state in self.active_requests.values():
349
+ if state.status == RequestStatus.DECODING:
350
+ priority_states.append(state)
351
+ elif state.status == RequestStatus.PREFILLING:
352
+ second_priority_states.append(state)
353
+
354
+ # Add waiting requests to second priority, with CPU-offloaded requests first
355
+ if not self.block_new_requests:
356
+ second_priority_states.extend(self._get_waiting_candidates())
357
+
358
+ candidates = priority_states + second_priority_states
359
+ request_ids_to_remove_from_waiting = set()
360
+ scheduled_requests, one_allocation_failed, decode_fast_path, num_q_tokens, max_kv_read = (
361
+ self._process_candidates(
362
+ candidates,
363
+ token_budget,
364
+ cache_budget,
365
+ request_ids_to_remove_from_waiting,
366
+ safety_margin=self.safety_margin,
367
+ )
368
+ )
369
+
370
+ # We remove waiting requests before checking requests were scheduled, because there might have been prefill matches
371
+ self._cleanup_waiting_queue(request_ids_to_remove_from_waiting)
372
+
373
+ # If no requests were scheduled and the cache is full, we signal it by returning None
374
+ if not scheduled_requests and one_allocation_failed:
375
+ return None, decode_fast_path, 0, 0
376
+
377
+ return scheduled_requests, decode_fast_path, num_q_tokens, max_kv_read
378
+
379
+
380
+ # FIXME: prioritize adding from waiting reqs before scheduling `RequestStatus.DECODING` when cache space allows it
381
+ # TODO: further consolidate the code by making more of it common. The reference Scheduler is FIFO, not this one.
382
+ @attach_tracer()
383
+ class PrefillFirstScheduler(Scheduler):
384
+ """Scheduler that prioritizes split prefill requests over decoding requests. This scheduler ensures that split
385
+ prefill requests (which are continuations of partially processed prompts) are completed before processing new
386
+ decoding requests."""
387
+
388
+ @traced
389
+ def schedule_batch(
390
+ self, token_budget: int, cache_budget: int
391
+ ) -> tuple[list[FutureRequestState] | None, bool, int, int]:
392
+ priority_states: list[RequestState] = []
393
+ second_priority_states: list[RequestState] = []
394
+
395
+ for state in self.active_requests.values():
396
+ # XXX: when cache is full, state can stay on `PREFILLING_SPLIT` so we need to take those into account
397
+ if state.status == RequestStatus.PREFILLING:
398
+ priority_states.append(state)
399
+ elif state.status == RequestStatus.DECODING:
400
+ second_priority_states.append(state)
401
+
402
+ # Add waiting requests to second priority, with CPU-offloaded requests first
403
+ if not self.block_new_requests:
404
+ second_priority_states.extend(self._get_waiting_candidates())
405
+
406
+ candidates = priority_states + second_priority_states
407
+ request_ids_to_remove_from_waiting = set()
408
+ scheduled_requests, one_allocation_failed, decode_fast_path, num_q_tokens, max_kv_read = (
409
+ self._process_candidates(
410
+ candidates,
411
+ token_budget,
412
+ cache_budget,
413
+ request_ids_to_remove_from_waiting,
414
+ safety_margin=0.0,
415
+ )
416
+ )
417
+
418
+ # We remove waiting requests before checking requests were scheduled, because there might have been prefill matches
419
+ self._cleanup_waiting_queue(request_ids_to_remove_from_waiting)
420
+
421
+ # If no requests were scheduled and the cache is full, we signal it by returning None
422
+ if not scheduled_requests and one_allocation_failed:
423
+ return None, decode_fast_path, 0, 0
424
+
425
+ return scheduled_requests, decode_fast_path, num_q_tokens, max_kv_read
426
+
427
+
428
+ SCHEDULER_MAPPING = {
429
+ "fifo": FIFOScheduler,
430
+ "prefill_first": PrefillFirstScheduler,
431
+ }
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/generation/continuous_batching/utils.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Inc. team
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from collections import OrderedDict
15
+ from dataclasses import dataclass
16
+ from math import ceil, log2
17
+ from typing import Any
18
+
19
+ import torch
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.generation.configuration_utils import ContinuousBatchingConfig
23
+
24
+ from .requests import FutureRequestState, RequestState, RequestStatus, logger
25
+
26
+
27
+ class CudaGraphBuffer:
28
+ """A fixed-size dict for CUDA graphs with LRU eviction when full."""
29
+
30
+ def __init__(self, max_size: int) -> None:
31
+ if max_size <= 0:
32
+ raise ValueError(f"max_size must be positive, but got {max_size}")
33
+ self.max_size = max_size
34
+ self._storage: OrderedDict[tuple[int, ...], torch.cuda.CUDAGraph] = OrderedDict()
35
+
36
+ def __del__(self) -> None:
37
+ original_max_size = self.max_size
38
+ self.max_size = 1 # 0 would cause an infinite loop, 1 is enough to clear all graphs
39
+ self.plan_for_new_graph(silent=True)
40
+ self.max_size = original_max_size
41
+
42
+ def get_graph(self, key: tuple[int, ...]) -> torch.cuda.CUDAGraph | None:
43
+ graph = self._storage.get(key)
44
+ if graph is not None:
45
+ self._storage.move_to_end(key)
46
+ return graph
47
+
48
+ def plan_for_new_graph(self, silent: bool = False) -> None:
49
+ while len(self._storage) >= self.max_size:
50
+ evicted_key, evicted_graph = self._storage.popitem(last=False)
51
+ if not silent:
52
+ logger.info(f"Evicting graph for {evicted_key = }")
53
+ evicted_graph.reset()
54
+
55
+ def set_graph(self, key: tuple[int, ...], graph: torch.cuda.CUDAGraph) -> None:
56
+ # In our use case, this should not have any effect because we plan for a new graph before it is captured
57
+ self.plan_for_new_graph()
58
+ self._storage[key] = graph
59
+
60
+
61
+ @dataclass
62
+ class WorkloadHints:
63
+ """A tiny dataclass containing hints to help choose good continuous batching defaults"""
64
+
65
+ max_prompt_length: int = 0
66
+ max_generated_length: int = 0
67
+
68
+ # TODO: can this be fused with other resolve methods?
69
+ def resolve_using_hints(self, cb_config: "ContinuousBatchingConfig") -> None:
70
+ """Resolves the config using the given hints."""
71
+ # The max number of block per request is an even number large enough to hold the max request length
72
+ if self.max_prompt_length and self.max_generated_length:
73
+ if cb_config.max_blocks_per_request is None:
74
+ max_sequence_length = self.max_prompt_length + self.max_generated_length
75
+ blocks_per_request = int(ceil(max_sequence_length / cb_config.block_size)) + 1
76
+ cb_config.max_blocks_per_request = blocks_per_request + (blocks_per_request % 2)
77
+
78
+
79
+ def attn_mask_is_needed(config: PretrainedConfig) -> bool:
80
+ """Checks if attention mask is needed for the given (config)."""
81
+ return config._attn_implementation in ["paged|eager", "paged|sdpa"]
82
+
83
+
84
+ def pad_to_interval(size: int, interval_size: int, max_value: int) -> int:
85
+ """Return the smallest multiple of (interval_size) >= (size), capped at (max_value)."""
86
+ if interval_size <= 0:
87
+ return max_value
88
+ padded = ceil(size / interval_size) * interval_size if size > 0 else interval_size
89
+ return min(padded, max_value)
90
+
91
+
92
+ def pad_to_pow2(value: int, max_value: int, min_value: int = 0) -> int:
93
+ """Return the smallest power of 2 >= (value), capped at (max_value). If a minimum value is provided, the value is at
94
+ least padded to that value."""
95
+ value = max(value, max(1, min_value))
96
+ padded = 2 ** int(ceil(log2(value)))
97
+ return min(padded, max_value)
98
+
99
+
100
+ def aligned_divide(x: int, divide_by: int, align_to: int) -> int:
101
+ x = int(ceil(x / divide_by))
102
+ if x % align_to:
103
+ x += align_to - (x % align_to)
104
+ return x
105
+
106
+
107
+ def build_attention_mask(
108
+ attention_mask: torch.Tensor,
109
+ cumulative_seqlens_q: list[int],
110
+ cumulative_seqlens_k: list[int],
111
+ sliding_window: int = 1,
112
+ ) -> None:
113
+ """Builds an attention mask inplace using the cumulative seqlens of the query and key. If given a sliding window, it
114
+ will also apply a sliding window mask on top. The attention mask is not boolean, it uses zeroes and -inf (or its
115
+ equivalent) so it's more of an attention score bias tensor.
116
+ The attention mask is a block-diagonal matrix, with each block an attention mask for a single query-key pair.
117
+ Each of those block is built from a causal mask and, if there is a sliding window, a sliding window mask.
118
+
119
+ An example is represented below, with seqlen_k = 8, seqlen_q = 4 and sliding_window = 6:
120
+
121
+ CAUSAL MASK:
122
+
123
+ █ █ █ █ █ ░ ░ ░
124
+ █ █ █ █ █ █ ░ ░
125
+ █ █ █ █ █ █ █ ░
126
+ █ █ █ █ █ █ █ █
127
+
128
+ SLIDING WINDOW MASK:
129
+ ┌──────────────────────── seqlen_k - seqlen_q - sliding_window = 8 - 4 - 6 = -2 offset to the left
130
+ <─┴─>
131
+ ░ █ | █ █ █ █ █ █ █ █
132
+ ░ ░ | █ █ █ █ █ █ █ █
133
+ ░ ░ | ░ █ █ █ █ █ █ █
134
+ ░ ░ | ░ ░ █ █ █ █ █ █
135
+
136
+ ATTENTION MASK (sum of causal and sliding window masks):
137
+
138
+ █ █ █ █ █ ░ ░ ░
139
+ █ █ █ █ █ █ ░ ░
140
+ ░ █ █ █ █ █ █ ░
141
+ ░ ░ █ █ █ █ █ █
142
+
143
+ Another example with seqlen_k = 5, seqlen_q = 3 and sliding_window = 2:
144
+
145
+ CAUSAL MASK:
146
+
147
+ █ █ █ ░ ░
148
+ █ █ █ █ ░
149
+ █ █ █ █ █
150
+
151
+ SLIDING WINDOW MASK:
152
+ ┌──────────────────────── seqlen_k - seqlen_q - sliding_window = 5 - 3 - 2 = 0 offset to the left
153
+ <┴>
154
+ | ░ █ █ █ █
155
+ | ░ ░ █ █ █
156
+ | ░ ░ ░ █ █
157
+
158
+ ATTENTION MASK (sum of causal and sliding window masks):
159
+
160
+ ░ █ █ ░ ░
161
+ ░ ░ █ █ ░
162
+ ░ ░ ░ █ █
163
+
164
+ """
165
+ min_value = torch.finfo(attention_mask.dtype).min
166
+ for i in range(len(cumulative_seqlens_q) - 1):
167
+ seqlen_q = cumulative_seqlens_q[i + 1] - cumulative_seqlens_q[i]
168
+ seqlen_k = cumulative_seqlens_k[i + 1] - cumulative_seqlens_k[i]
169
+ if seqlen_q < seqlen_k and seqlen_q >= 1:
170
+ causal_diagonal = seqlen_k - seqlen_q + 1
171
+ else:
172
+ causal_diagonal = 1
173
+ query_range = slice(cumulative_seqlens_q[i], cumulative_seqlens_q[i + 1])
174
+ key_range = slice(cumulative_seqlens_k[i], cumulative_seqlens_k[i + 1])
175
+ # Apply causal mask
176
+ minus_inf = torch.full(
177
+ attention_mask[..., query_range, key_range].shape,
178
+ min_value,
179
+ dtype=attention_mask.dtype,
180
+ device=attention_mask.device,
181
+ )
182
+ masked = torch.triu(minus_inf, diagonal=causal_diagonal)
183
+ # Apply sliding window mask if needed
184
+ if sliding_window > 1:
185
+ sliding_diagonal = seqlen_k - seqlen_q - sliding_window
186
+ masked += torch.tril(minus_inf, diagonal=sliding_diagonal)
187
+ # Replace in attention mask
188
+ attention_mask[..., query_range, key_range] = masked
189
+
190
+
191
+ def create_warmup_future_states(
192
+ num: int,
193
+ status: RequestStatus,
194
+ num_query_tokens: int,
195
+ num_cache_tokens: int,
196
+ cache: Any, # not annotated to avoid circular import
197
+ ) -> list[FutureRequestState]:
198
+ """An utility function to create a list of FutureRequestStates for the warmup of CB."""
199
+ # Setup
200
+ request_ids = [f"__warmup_{status.name}_{i}__" for i in range(num)]
201
+ total_tokens = num_query_tokens + num_cache_tokens
202
+ blocks_needed = ceil(total_tokens / cache.block_size)
203
+ # Main loop
204
+ future_states = []
205
+ for req_id in request_ids:
206
+ state = RequestState(request_id=req_id, initial_tokens=[0] * total_tokens, max_new_tokens=1)
207
+ state._status = status # bypass the property setter to avoid the lifecycle side effects
208
+ state.tokens_to_process = [0] * num_query_tokens
209
+ state.position_offset = num_cache_tokens
210
+ # Stop if allocation fails for any request
211
+ allocated = cache.allocate_blocks(blocks_needed, state.request_id, 0)
212
+ if allocated is None:
213
+ return future_states
214
+ future_states.append(
215
+ FutureRequestState(state, has_new_token=True, complete_blocks=0, query_length=num_query_tokens)
216
+ )
217
+ return future_states
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (8.16 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/accelerate.cpython-311.pyc ADDED
Binary file (46 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/aqlm.cpython-311.pyc ADDED
Binary file (3.02 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/awq.cpython-311.pyc ADDED
Binary file (4.89 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/bitnet.cpython-311.pyc ADDED
Binary file (19.6 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/bitsandbytes.cpython-311.pyc ADDED
Binary file (17.7 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/deepspeed.cpython-311.pyc ADDED
Binary file (34.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/eager_paged.cpython-311.pyc ADDED
Binary file (4.13 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/eetq.cpython-311.pyc ADDED
Binary file (7.38 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/executorch.cpython-311.pyc ADDED
Binary file (53.9 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fbgemm_fp8.cpython-311.pyc ADDED
Binary file (17 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/finegrained_fp8.cpython-311.pyc ADDED
Binary file (50.6 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/flash_attention.cpython-311.pyc ADDED
Binary file (4.3 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/flash_paged.cpython-311.pyc ADDED
Binary file (7.3 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/flex_attention.cpython-311.pyc ADDED
Binary file (14.4 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fouroversix.cpython-311.pyc ADDED
Binary file (4.09 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fp_quant.cpython-311.pyc ADDED
Binary file (6.71 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/fsdp.cpython-311.pyc ADDED
Binary file (3.93 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/ggml.cpython-311.pyc ADDED
Binary file (30.4 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/higgs.cpython-311.pyc ADDED
Binary file (29.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/hqq.cpython-311.pyc ADDED
Binary file (5.37 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/hub_kernels.cpython-311.pyc ADDED
Binary file (18.9 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/liger.cpython-311.pyc ADDED
Binary file (1.99 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/metal_quantization.cpython-311.pyc ADDED
Binary file (14.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/mistral.cpython-311.pyc ADDED
Binary file (8 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/moe.cpython-311.pyc ADDED
Binary file (23.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/mxfp4.cpython-311.pyc ADDED
Binary file (35.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/neftune.cpython-311.pyc ADDED
Binary file (4.59 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/npu_flash_attention.cpython-311.pyc ADDED
Binary file (4.74 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/peft.cpython-311.pyc ADDED
Binary file (56.7 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/integrations/__pycache__/quanto.cpython-311.pyc ADDED
Binary file (5.74 kB). View file