forked from NVIDIA/Megatron-LM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_dynamic_context.py
More file actions
1586 lines (1389 loc) · 65.4 KB
/
test_dynamic_context.py
File metadata and controls
1586 lines (1389 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
import contextlib
import math
import pytest
import torch
from megatron.core import parallel_state
from megatron.core.inference.config import InferenceConfig, MambaInferenceStateConfig
from megatron.core.inference.contexts.dynamic_context import (
DynamicInferenceContext,
RequestOverflowError,
TokenOverflowError,
)
from megatron.core.inference.inference_request import DynamicInferenceRequest
from megatron.core.inference.sampling_params import SamplingParams
from megatron.core.ssm.mamba_hybrid_layer_allocation import Symbols
from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
from megatron.core.transformer.transformer_config import TransformerConfig
from tests.unit_tests.test_utilities import Utils
@contextlib.contextmanager
def rounder_override(n):
original_token_rounder = DynamicInferenceContext.TOKEN_ROUNDER
original_request_rounder = DynamicInferenceContext.REQUEST_ROUNDER
try:
DynamicInferenceContext.TOKEN_ROUNDER = n
DynamicInferenceContext.REQUEST_ROUNDER = n
yield
finally:
DynamicInferenceContext.TOKEN_ROUNDER = original_token_rounder
DynamicInferenceContext.REQUEST_ROUNDER = original_request_rounder
class TestDynamicContext:
def _setup_model_parallel_group(self, tensor_parallel_size, pipeline_parallel_size):
self.pp_size = pipeline_parallel_size
Utils.initialize_model_parallel(
tensor_model_parallel_size=tensor_parallel_size,
pipeline_model_parallel_size=pipeline_parallel_size,
)
model_parallel_cuda_manual_seed(123)
def _get_dynamic_context(
self,
params_dtype,
num_layers,
kv_channels,
num_attention_heads,
max_sequence_length,
buffer_size_gb,
block_size_tokens,
max_tokens,
is_hybrid_model=False,
layer_type_list=None,
paused_buffer_size_gb=None,
num_cuda_graphs=None,
):
if is_hybrid_model:
if layer_type_list is None:
layer_type_list = [Symbols.MAMBA, Symbols.MLP, Symbols.ATTENTION, Symbols.MLP]
mamba_conv_states_shape = (544, 4)
mamba_ssm_states_shape = (8, 64, 16)
mamba_inference_state_config = MambaInferenceStateConfig(
layer_type_list,
mamba_conv_states_shape,
mamba_ssm_states_shape,
params_dtype,
params_dtype,
)
else:
mamba_inference_state_config = None
dynamic_context = DynamicInferenceContext(
model_config=TransformerConfig(
params_dtype=params_dtype,
num_layers=num_layers,
kv_channels=kv_channels,
num_attention_heads=num_attention_heads,
),
inference_config=InferenceConfig(
max_sequence_length=max_sequence_length,
num_cuda_graphs=num_cuda_graphs,
use_cuda_graphs_for_non_decode_steps=True,
buffer_size_gb=buffer_size_gb,
paused_buffer_size_gb=(
0.2 * buffer_size_gb if paused_buffer_size_gb is None else paused_buffer_size_gb
),
block_size_tokens=block_size_tokens,
max_tokens=max_tokens,
mamba_inference_state_config=mamba_inference_state_config,
use_flashinfer_fused_rope=None, # default to using flash-infer if available
# this is for compatibility with the LTS environment
unified_memory_level=0, # unit tests currently broken with UVM
),
)
return dynamic_context
def teardown_method(self, method):
Utils.destroy_model_parallel()
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_initialize_dynamic_context(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
if not is_hybrid_model:
assert dynamic_context.block_allocator.total_count == 491
assert dynamic_context.block_allocator.active_count == 392
# We make max_requests divisible by the REQUEST_ROUNDER.
assert dynamic_context.max_requests == 448
assert dynamic_context.max_tokens == 16384
assert dynamic_context.num_mamba_layers == 0
assert dynamic_context.mamba_metadata is None
else:
assert dynamic_context.block_allocator.total_count == 556
assert dynamic_context.block_allocator.active_count == 444
assert dynamic_context.max_requests == 512
assert dynamic_context.max_tokens == 16384
assert dynamic_context.num_mamba_layers == 1
assert dynamic_context.mamba_metadata is not None
# Check initializations to -1
assert torch.all(dynamic_context.request_ids == -1)
@pytest.mark.internal
def test_is_static_batching(self):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=64,
num_attention_heads=8,
max_sequence_length=512,
buffer_size_gb=1.0,
block_size_tokens=128,
max_tokens=None,
)
assert not dynamic_context.is_static_batching()
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_is_memory_available(self, is_hybrid_model):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=64,
num_attention_heads=8,
max_sequence_length=512,
buffer_size_gb=1.0,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
dynamic_context.block_allocator.total_avail = 10
assert dynamic_context.block_allocator.is_memory_available(10)
assert not dynamic_context.block_allocator.is_memory_available(11)
assert dynamic_context.block_allocator.is_memory_available(1)
dynamic_context.block_allocator.total_avail = 0
assert not dynamic_context.block_allocator.is_memory_available(1)
@pytest.mark.internal
@rounder_override(1)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_request_overflow(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=64,
num_attention_heads=8,
max_sequence_length=128,
buffer_size_gb=0.01,
block_size_tokens=32,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
dynamic_context.max_requests //= 2
with pytest.raises(RequestOverflowError):
for i in range(dynamic_context.max_requests + 1):
dynamic_context.add_request(
DynamicInferenceRequest(
request_id=i,
prompt_tokens=torch.zeros(10, device='cuda'),
sampling_params=SamplingParams(
num_tokens_to_generate=dynamic_context.max_tokens - 10
),
)
) # Adding more than allowed requests
@pytest.mark.internal
@rounder_override(1)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_token_overflow_error(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=64,
num_attention_heads=8,
max_sequence_length=512,
buffer_size_gb=0.1,
block_size_tokens=128,
max_tokens=200, # setting low, but >= context.max_requests.
is_hybrid_model=is_hybrid_model,
)
with pytest.raises(TokenOverflowError):
dynamic_context.add_request(
DynamicInferenceRequest(
request_id=1,
prompt_tokens=torch.arange(0, 225, device='cuda'),
sampling_params=SamplingParams(
num_tokens_to_generate=dynamic_context.max_tokens - 25
),
)
) # Exceeding max token count
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_reset(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=64,
num_attention_heads=8,
max_sequence_length=128,
buffer_size_gb=1.0,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
# Initialize all variables
dynamic_context.total_request_count = 10
dynamic_context.active_token_count = 10
dynamic_context.paused_request_count = 5
dynamic_context.padded_active_token_count = 10
dynamic_context.padded_active_request_count = 5
dynamic_context.paused_tokens = torch.tensor([1, 2, 3], device='cuda')
dynamic_context.request_ids.fill_(1)
dynamic_context.request_query_lengths.fill_(1)
dynamic_context.request_kv_length_offsets.fill_(1)
dynamic_context.request_kv_block_counts.fill_(1)
dynamic_context.request_last_kv_block_id.fill_(1)
dynamic_context.request_last_kv_block_offset.fill_(1)
dynamic_context.token_to_input_ids.fill_(1)
dynamic_context.token_to_pos_ids.fill_(1)
dynamic_context.token_to_request_idx.fill_(1)
dynamic_context.token_to_position_in_request.fill_(1)
dynamic_context.token_to_block_idx.fill_(1)
dynamic_context.token_to_local_position_within_kv_block.fill_(1)
dynamic_context.memory_buffer.fill_(1)
dynamic_context.request_to_kv_block_ids.fill_(1)
if is_hybrid_model:
dynamic_context.mamba_conv_states.fill_(1)
dynamic_context.mamba_ssm_states.fill_(1)
# Call reset
dynamic_context.reset()
# Assert all variables are reset to zero or their default values
assert dynamic_context.total_request_count == 0
assert dynamic_context.active_token_count == 0
assert dynamic_context.paused_request_count == 0
assert dynamic_context.padded_active_token_count == 0
assert dynamic_context.padded_active_request_count == 0
assert dynamic_context.paused_tokens is None
assert torch.all(dynamic_context.request_ids == -1)
assert torch.all(dynamic_context.request_query_lengths == 0)
assert torch.all(dynamic_context.request_kv_length_offsets == 0)
assert torch.all(dynamic_context.request_kv_block_counts == 0)
assert torch.all(dynamic_context.request_last_kv_block_id == -1)
assert torch.all(dynamic_context.request_last_kv_block_offset == 0)
assert torch.all(dynamic_context.token_to_input_ids == 0)
assert torch.all(dynamic_context.token_to_pos_ids == 0)
assert torch.all(dynamic_context.token_to_request_idx == -1)
assert torch.all(dynamic_context.token_to_position_in_request == 0)
assert torch.all(dynamic_context.token_to_block_idx == -1)
assert torch.all(dynamic_context.token_to_local_position_within_kv_block == 0)
if not is_hybrid_model:
assert dynamic_context.block_allocator.active_count == 819
assert dynamic_context.block_allocator.total_count == 1024
else:
assert dynamic_context.block_allocator.active_count == 1517
assert dynamic_context.block_allocator.total_count == 1897
assert torch.all(dynamic_context.request_to_kv_block_ids == -1)
if is_hybrid_model:
assert torch.all(dynamic_context.mamba_metadata.request_to_mamba_state_idx == -1)
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_allocate_and_release_memory_blocks(self, is_hybrid_model):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
if is_hybrid_model:
expected_memory_blocks = [551, 552, 553, 554]
else:
expected_memory_blocks = [486, 487, 488, 489]
expected_block_count_avail = expected_memory_blocks[0]
assert (
dynamic_context.block_allocator.allocate_memory_blocks(4)
.cpu()
.detach()
.numpy()
.tolist()
== expected_memory_blocks
)
assert dynamic_context.block_allocator.total_avail == expected_block_count_avail
dynamic_context.block_allocator.release_memory_blocks(
torch.tensor(expected_memory_blocks[-2:], device='cuda')
)
assert dynamic_context.block_allocator.total_avail == expected_block_count_avail + 2
assert (
dynamic_context.block_allocator.allocate_memory_blocks(1).item()
== expected_memory_blocks[-1]
)
assert dynamic_context.block_allocator.total_avail == expected_block_count_avail + 1
# Should return None since we allocate more blocks than what we have.
assert (
dynamic_context.block_allocator.allocate_memory_blocks(
dynamic_context.block_allocator.total_avail + 100
)
== None
)
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_add_request(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
assert dynamic_context.block_size_tokens == 128
context_length = 144
dynamic_context.add_request(
DynamicInferenceRequest(
request_id=0,
prompt_tokens=torch.arange(0, context_length, dtype=torch.long, device='cuda'),
sampling_params=SamplingParams(
num_tokens_to_generate=dynamic_context.max_tokens - context_length
),
)
)
assert dynamic_context.total_request_count == 1
assert dynamic_context.active_token_count == context_length
assert dynamic_context.request_ids[0] == 0
assert torch.all(dynamic_context.request_ids[1:] == -1)
assert dynamic_context.request_query_lengths[0] == context_length
assert dynamic_context.request_kv_length_offsets[0] == 0
assert dynamic_context.request_kv_block_counts[0] == 2
assert dynamic_context.request_last_kv_block_id[0].item() == (
554 if is_hybrid_model else 489
)
assert dynamic_context.request_last_kv_block_offset[0].item() == 15
assert torch.all(
dynamic_context.token_to_pos_ids[0:context_length]
== torch.arange(0, context_length, dtype=torch.long, device='cuda')
)
assert torch.all(
dynamic_context.token_to_input_ids[0:context_length]
== torch.arange(0, context_length, dtype=torch.long, device='cuda')
)
assert torch.all(
dynamic_context.token_to_position_in_request[0:context_length]
== torch.arange(0, context_length, dtype=torch.long, device='cuda')
)
# Verify token_to_block_idx and token_to_local_position_within_kv_block based on assigned blocks
first_block_id = dynamic_context.request_to_kv_block_ids[0, 0]
second_block_id = dynamic_context.request_to_kv_block_ids[0, 1]
assert torch.all(
dynamic_context.token_to_block_idx[0:context_length][
0 : dynamic_context.block_size_tokens
]
== first_block_id
)
assert torch.all(
dynamic_context.token_to_block_idx[0:context_length][
dynamic_context.block_size_tokens : context_length
]
== second_block_id
)
assert torch.all(
dynamic_context.token_to_local_position_within_kv_block[0:context_length]
== torch.arange(0, context_length, dtype=torch.long, device='cuda')
% dynamic_context.block_size_tokens
)
@pytest.mark.internal
@rounder_override(64)
def test_add_dummy_requests_parallel_populates_state(self):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=16,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.01,
block_size_tokens=4,
max_tokens=None,
)
requests = [
DynamicInferenceRequest(
request_id=100,
prompt_tokens=torch.arange(0, 3, device='cuda'),
sampling_params=SamplingParams(num_tokens_to_generate=2, termination_id=7),
),
DynamicInferenceRequest(
request_id=101,
prompt_tokens=torch.arange(3, 9, device='cuda'),
sampling_params=SamplingParams(num_tokens_to_generate=1, termination_id=8),
),
]
lengths = [req.remaining_prompt_length for req in requests]
total_tokens = sum(lengths)
block_avail_before = dynamic_context.block_allocator.total_avail
dynamic_context.add_dummy_requests_parallel(requests, count_as_prefill=False)
assert dynamic_context.active_token_count == total_tokens
assert dynamic_context.total_request_count == len(requests)
assert dynamic_context.num_prefill_requests == 0
assert dynamic_context.block_allocator.total_avail == block_avail_before
expected_tokens = torch.cat(
[torch.arange(0, 3, device='cuda'), torch.arange(3, 9, device='cuda')]
)
assert torch.equal(dynamic_context.token_to_input_ids[:total_tokens], expected_tokens)
expected_positions = torch.tensor(
[0, 1, 2, 0, 1, 2, 3, 4, 5], device='cuda', dtype=torch.long
)
assert torch.equal(
dynamic_context.token_to_position_in_request[:total_tokens], expected_positions
)
assert torch.equal(dynamic_context.token_to_pos_ids[:total_tokens], expected_positions)
expected_request_indices = torch.tensor(
[0, 0, 0, 1, 1, 1, 1, 1, 1], device='cuda', dtype=torch.long
)
assert torch.equal(
dynamic_context.token_to_request_idx[:total_tokens], expected_request_indices
)
expected_local = expected_positions % dynamic_context.block_size_tokens
assert torch.equal(
dynamic_context.token_to_local_position_within_kv_block[:total_tokens], expected_local
)
dummy_block_idx = dynamic_context.block_allocator.dummy_block_idx
assert torch.all(dynamic_context.token_to_block_idx[:total_tokens] == dummy_block_idx)
assert torch.equal(
dynamic_context.request_query_lengths[: len(requests)],
torch.tensor(lengths, device='cuda', dtype=torch.int32),
)
assert torch.equal(
dynamic_context.request_output_lengths[: len(requests)],
torch.tensor([5, 7], device='cuda', dtype=torch.int32),
)
assert torch.equal(
dynamic_context.request_kv_block_counts[: len(requests)],
torch.tensor([1, 2], device='cuda', dtype=torch.int32),
)
assert torch.all(
dynamic_context.request_to_kv_block_ids[0, :1] == dummy_block_idx
), "first request should use dummy block"
assert torch.all(
dynamic_context.request_to_kv_block_ids[1, :2] == dummy_block_idx
), "second request should use dummy blocks"
assert torch.all(dynamic_context.request_to_kv_block_ids[:2, 2:] == -1)
assert torch.all(dynamic_context.request_last_kv_block_id[:2] == dummy_block_idx)
assert torch.equal(
dynamic_context.request_last_kv_block_offset[:2],
torch.tensor([2, 1], device='cuda', dtype=torch.int32),
)
assert torch.equal(
dynamic_context.request_metadata["termination_id"][:2],
torch.tensor([7.0, 8.0], device='cuda'),
)
@pytest.mark.internal
@rounder_override(64)
def test_add_dummy_requests_parallel_hybrid_allocates_mamba(self):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=8,
max_tokens=None,
is_hybrid_model=True,
layer_type_list=[Symbols.MAMBA, Symbols.ATTENTION, Symbols.MLP, Symbols.ATTENTION],
)
request = DynamicInferenceRequest(
request_id=55,
prompt_tokens=torch.arange(0, 5, device='cuda'),
sampling_params=SamplingParams(num_tokens_to_generate=4, termination_id=9),
)
dynamic_context.add_dummy_requests_parallel([request])
mamba_idx = dynamic_context.mamba_metadata.request_to_mamba_state_idx[0].item()
assert mamba_idx >= 0
assert torch.all(dynamic_context.mamba_conv_states[:, mamba_idx] == 0)
assert torch.all(dynamic_context.mamba_ssm_states[:, mamba_idx] == 0)
@pytest.mark.internal
@rounder_override(64)
def test_add_dummy_requests_parallel_decode_does_not_count_as_prefill(self):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=2,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=256,
buffer_size_gb=0.02,
block_size_tokens=4,
max_tokens=1_000_000,
)
request = DynamicInferenceRequest(
request_id=5,
prompt_tokens=torch.arange(0, 1, device='cuda'),
sampling_params=SamplingParams(num_tokens_to_generate=1, termination_id=2),
)
dynamic_context.num_prefill_requests = 0
dynamic_context.add_dummy_requests_parallel([request], count_as_prefill=False)
assert dynamic_context.num_prefill_requests == 0
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_update_request(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
# This case should just reset and return since all requests are finished
active_requests_mask = torch.Tensor([0, 0, 0])
dynamic_context.paused_request_count = 0
dynamic_context.total_request_count = 3
dynamic_context.request_kv_block_counts[0:3] = 1
new_block_ids = dynamic_context.block_allocator.allocate_memory_blocks(3)
dynamic_context.request_to_kv_block_ids[0:3, 0] = new_block_ids
if is_hybrid_model:
# Also initialize Mamba states for the dummy requests
dynamic_context.mamba_conv_states[:, 0:3, :, :].fill_(1.0)
dynamic_context.mamba_ssm_states[:, 0:3, :, :, :].fill_(1.0)
dynamic_context.update_requests(
active_requests_mask=active_requests_mask, new_tokens=torch.tensor([0, 1, 2])
)
assert dynamic_context.total_request_count == 0
# This case would cover all cases
# 1. Already there will be 2 paused requests
# 2. Active request mask will have active and finished requests.
# 3. The active requests will also have some requests that have to be paused because of reaching max token limit within block
# 4. Some of these requests will be resumed.
# Setup is as follows :
# Request ids 0, 1 are paused
# Request ids 2, 4, 9 are active requests
# Request ids 3 7 8 have completed
# Request ids 5 and 6 will require on more block later on because they finished their current block
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
active_requests_mask = torch.Tensor([1, 0, 1, 1, 1, 0, 0, 1]).cuda().int()
next_tokens = torch.arange(2, 10, device='cuda').int()
dynamic_context.paused_request_count = 2
dynamic_context.paused_tokens = torch.Tensor([0, 1]).cuda().int()
dynamic_context.total_request_count = 5
# Total req count should be equal to paused + num elements in active request mask.
# So here it will raise an assertion error
with pytest.raises(AssertionError) as error:
dynamic_context.update_requests(
active_requests_mask=active_requests_mask, new_tokens=next_tokens
)
total_request_count = 10
dynamic_context.block_allocator.total_avail -= 11 # We align 11 blocks to the 10 requests we have. 3rd request alone we setup like it requires 2 blocks
dynamic_context.total_request_count = total_request_count
dynamic_context.request_to_kv_block_ids[0:total_request_count, 0] = torch.arange(
dynamic_context.block_allocator.total_avail,
dynamic_context.block_allocator.total_avail + 10,
)
dynamic_context.request_to_kv_block_ids[3][
1
] = dynamic_context.block_allocator.total_avail # Assign one extra block to request 3.
dynamic_context.request_kv_length_offsets[0:total_request_count] = 10
# For 0, 1, 5, 6, the total number of tokens in last block is block size -1, so that they will all need extra blocks
dynamic_context.request_kv_length_offsets[0:2] = dynamic_context.block_size_tokens - 1
dynamic_context.request_kv_length_offsets[5:7] = dynamic_context.block_size_tokens - 1
# For the 3rd request, its completed and required 2 blocks. So we add more tokens than block size
dynamic_context.request_kv_length_offsets[3] = dynamic_context.block_size_bytes + 10
dynamic_context.request_query_lengths[0:total_request_count] = (
1 # Everything is in decode phase
)
dynamic_context.request_ids[0:total_request_count] = torch.arange(0, total_request_count)
dynamic_context.request_kv_block_counts[0:total_request_count] = 1
dynamic_context.request_kv_block_counts[3] = 2 # 3rd block alone requies 2 blocks
dynamic_context.request_last_kv_block_id[0:total_request_count] = torch.arange(
0, total_request_count
)
dynamic_context.request_last_kv_block_id[3] = 11
dynamic_context.request_last_kv_block_offset[0:total_request_count] = 10
# For the 3rd request, its completed and required 2 blocks. So we add more tokens than block size
dynamic_context.request_last_kv_block_offset[0:2] = dynamic_context.block_size_tokens - 1
dynamic_context.request_last_kv_block_offset[5:7] = dynamic_context.block_size_tokens - 1
if is_hybrid_model:
# Dummy fill for states to be non-zero before update
for i in range(total_request_count):
dynamic_context.mamba_metadata.request_to_mamba_state_idx[i] = i
dynamic_context.mamba_metadata.mamba_state_free_slot_count -= total_request_count
dynamic_context.mamba_conv_states[:, 0:total_request_count, :, :] = 1.0
dynamic_context.mamba_ssm_states[:, 0:total_request_count, :, :, :] = 1.0
dynamic_context.update_requests(
active_requests_mask=active_requests_mask, new_tokens=next_tokens
)
# Then set up the test data
dynamic_context.request_ids[0:10] = torch.tensor(
[0, 1, 5, 6, 4, 2, 9, 7, 8, 9], device=torch.cuda.current_device()
)
# Now verify the values
assert dynamic_context.request_ids[0:10].cpu().numpy().tolist() == [
0,
1,
5,
6,
4,
2,
9,
7,
8,
9,
]
assert dynamic_context.paused_request_count == 0
assert dynamic_context.total_request_count == 7
assert dynamic_context.active_token_count == 7
# The first four are zero because they have all obtained a new block
assert dynamic_context.request_last_kv_block_offset[0:10].cpu().numpy().tolist() == [
0,
0,
0,
0,
11,
11,
11,
10,
10,
10,
]
assert dynamic_context.token_to_input_ids[
: dynamic_context.active_token_count
].cpu().numpy().tolist() == [0, 1, 5, 6, 4, 2, 9]
assert dynamic_context.token_to_pos_ids[
: dynamic_context.active_token_count
].cpu().numpy().tolist() == [128, 128, 128, 128, 11, 11, 11]
# The first 4 requests will require an extra block.
# Since 3 requests have finished, the last 3 rows should be all -1.
if is_hybrid_model:
assert torch.all(
dynamic_context.request_to_kv_block_ids[0:10].cpu()
== torch.tensor(
[
[544, 547, -1, -1],
[545, 544, -1, -1],
[549, 551, -1, -1],
[550, 552, -1, -1],
[548, -1, -1, -1],
[546, -1, -1, -1],
[553, -1, -1, -1],
[-1, -1, -1, -1],
[-1, -1, -1, -1],
[-1, -1, -1, -1],
]
)
)
else:
assert torch.all(
dynamic_context.request_to_kv_block_ids[0:10].cpu()
== torch.tensor(
[
[479, 482, -1, -1],
[480, 479, -1, -1],
[484, 486, -1, -1],
[485, 487, -1, -1],
[483, -1, -1, -1],
[481, -1, -1, -1],
[488, -1, -1, -1],
[-1, -1, -1, -1],
[-1, -1, -1, -1],
[-1, -1, -1, -1],
]
)
)
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_release_memory_blocks_for_finished_requests(self, is_hybrid_model):
"""Test that memory blocks are correctly released for finished requests."""
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
# Set up the initial state with 5 requests
# Allocate 5 blocks for 5 requests
initial_blocks = dynamic_context.block_allocator.allocate_memory_blocks(5)
dynamic_context.total_request_count = 5
dynamic_context.paused_request_count = 0
# Record the available blocks before releasing memory
initial_available_blocks = dynamic_context.block_allocator.total_avail
# Assign blocks to the requests (one block per request)
for i in range(5):
dynamic_context.request_to_kv_block_ids[i, 0] = initial_blocks[i]
dynamic_context.request_query_lengths[i] = 1
dynamic_context.request_ids[i] = i
if is_hybrid_model:
dynamic_context.mamba_conv_states[:, i, :, :].fill_(
float(i + 1)
) # Fill with distinct values
dynamic_context.mamba_ssm_states[:, i, :, :, :].fill_(float(i + 1))
dynamic_context.mamba_metadata.request_to_mamba_state_idx[i] = i
dynamic_context.mamba_metadata.mamba_state_free_slot_count -= 1
# Create an active_requests_mask where requests 0, 2, and 4 are finished (0),
# and requests 1 and 3 are still active (1)
active_requests_mask = torch.tensor([0, 1, 0, 1, 0], device=torch.cuda.current_device())
# Call update_requests with these parameters
dynamic_context.update_requests(
active_requests_mask=active_requests_mask,
new_tokens=torch.tensor([10, 11, 12, 13, 14], device=torch.cuda.current_device()),
)
# After the update, we should have released 3 blocks (for requests 0, 2, and 4)
# and have 2 active requests (1 and 3)
assert dynamic_context.total_request_count == 2
assert dynamic_context.active_token_count == 2
# Verify that 3 blocks were released by checking the available blocks
assert dynamic_context.block_allocator.total_avail == initial_available_blocks + 3
if is_hybrid_model:
# Request at position 3 now moves into finished request position 0
# Request at position 1 remains active
mamba_idx = {
i: dynamic_context.mamba_metadata.request_to_mamba_state_idx[i] for i in range(5)
}
assert torch.all(dynamic_context.mamba_conv_states[:, mamba_idx[0], :, :] == 4.0)
assert torch.all(dynamic_context.mamba_ssm_states[:, mamba_idx[0], :, :, :] == 4.0)
assert torch.all(dynamic_context.mamba_conv_states[:, mamba_idx[1], :, :] == 2.0)
assert torch.all(dynamic_context.mamba_ssm_states[:, mamba_idx[1], :, :, :] == 2.0)
assert mamba_idx[2] == -1
assert mamba_idx[3] == -1
assert mamba_idx[4] == -1
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_finished_requests_with_multiple_blocks(self, is_hybrid_model):
"""Test that all memory blocks are correctly released for finished requests that use multiple blocks."""
self._setup_model_parallel_group(1, 1)
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
)
# Set up the initial state with 3 requests, where some use multiple blocks
# Allocate 6 blocks in total for the requests
initial_blocks = dynamic_context.block_allocator.allocate_memory_blocks(6)
dynamic_context.total_request_count = 3
dynamic_context.paused_request_count = 0
# Record the available blocks before releasing memory
initial_available_blocks = dynamic_context.block_allocator.total_avail
# Assign blocks to the requests:
# - Request 0: 1 block
# - Request 1: 2 blocks
# - Request 2: 3 blocks
dynamic_context.request_to_kv_block_ids[0, 0] = initial_blocks[0]
dynamic_context.request_to_kv_block_ids[1, 0] = initial_blocks[1]
dynamic_context.request_to_kv_block_ids[1, 1] = initial_blocks[2]
dynamic_context.request_to_kv_block_ids[2, 0] = initial_blocks[3]
dynamic_context.request_to_kv_block_ids[2, 1] = initial_blocks[4]
dynamic_context.request_to_kv_block_ids[2, 2] = initial_blocks[5]
dynamic_context.request_kv_block_counts[0] = 1
dynamic_context.request_kv_block_counts[1] = 2
dynamic_context.request_kv_block_counts[2] = 3
for i in range(3):
dynamic_context.request_query_lengths[i] = 1
dynamic_context.request_ids[i] = i
if is_hybrid_model:
dynamic_context.mamba_conv_states[:, i, :, :].fill_(float(i + 1))
dynamic_context.mamba_ssm_states[:, i, :, :, :].fill_(float(i + 1))
# Create an active_requests_mask where all requests are finished
active_requests_mask = torch.tensor([0, 0, 0], device=torch.cuda.current_device())
# Call update_requests with these parameters
dynamic_context.update_requests(
active_requests_mask=active_requests_mask,
new_tokens=torch.tensor([10, 11, 12], device=torch.cuda.current_device()),
)
# After the update, we should have released all 6 blocks and have 0 active requests
assert dynamic_context.total_request_count == 0
assert dynamic_context.active_token_count == 0
# Verify that all 6 blocks were released by checking the available blocks
assert dynamic_context.block_allocator.total_avail == initial_available_blocks + 6
@pytest.mark.internal
@rounder_override(64)
@pytest.mark.parametrize("is_hybrid_model", [False, True])
def test_mamba_states_cache(self, is_hybrid_model: bool):
self._setup_model_parallel_group(1, 1)
if not is_hybrid_model:
# If not hybrid, mamba_states_cache should fail
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=False,
)
with pytest.raises(AssertionError) as error:
conv_state, ssm_state = dynamic_context.mamba_states_cache(layer_number=1)
return
dynamic_context = self._get_dynamic_context(
params_dtype=torch.float32,
num_layers=4,
kv_channels=8,
num_attention_heads=2,
max_sequence_length=512,
buffer_size_gb=0.03,
block_size_tokens=128,
max_tokens=None,
is_hybrid_model=is_hybrid_model,
layer_type_list=[Symbols.MAMBA, Symbols.ATTENTION, Symbols.MAMBA, Symbols.ATTENTION],
)
# Add a request to populate states
context_length = 10
dynamic_context.add_request(
DynamicInferenceRequest(
request_id=0,
prompt_tokens=torch.arange(0, context_length, dtype=torch.long, device='cuda'),
sampling_params=SamplingParams(
num_tokens_to_generate=dynamic_context.max_tokens - 10
),
)
)
dynamic_context.initialize_attention_state()
# Manually set some dummy values in mamba_conv_states and mamba_ssm_states
# Mamba layers are at global indices 0 and 2 (mapped to local 0 and 1 via layer_map)
# `layer_map` will map global layer index to the corresponding Mamba/Attention index.
# For layer_type_list ["MAMBA", "ATTENTION", "MAMBA", "ATTENTION"],
# global layer 1 (index 0) is MAMBA -> local mamba layer 0
# global layer 3 (index 2) is MAMBA -> local mamba layer 1
# Test for the first Mamba layer (global layer 1, local mamba layer 0)
global_layer_1_mamba_local_idx = 0
dynamic_context.mamba_conv_states[global_layer_1_mamba_local_idx] = 10.0
dynamic_context.mamba_ssm_states[global_layer_1_mamba_local_idx] = 20.0
# Test for the second Mamba layer (global layer 3, local mamba layer 1)
global_layer_3_mamba_local_idx = 1
dynamic_context.mamba_conv_states[global_layer_3_mamba_local_idx] = 30.0