Repository navigation
Expand file tree
/
Copy pathtest_cuda_kv_cache.cpp
More file actions
2135 lines (1975 loc) · 80.3 KB
/
Copy pathtest_cuda_kv_cache.cpp
File metadata and controls
2135 lines (1975 loc) · 80.3 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) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <executorch/backends/aoti/slim/core/slim_tensor.h>
#include <executorch/backends/cuda/runtime/backend_options.h>
#include <executorch/backends/cuda/runtime/cuda_kv_cache.h>
#include <executorch/backends/cuda/runtime/cuda_kv_pool.h>
#include <executorch/extension/llm/cache/cache_registry.h>
#include <executorch/extension/llm/cache/cell_cache.h>
#include <executorch/runtime/core/evalue.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
namespace cu = ::executorch::backends::cuda;
namespace cache = ::executorch::extension::llm::cache;
namespace aoti = ::executorch::backends::aoti;
namespace slim = ::executorch::backends::aoti::slim;
namespace slimc10 = ::executorch::backends::aoti::slim::c10;
using ::executorch::runtime::Error;
using ::executorch::runtime::EValue;
namespace {
struct Binding {
void* data{nullptr};
slimc10::ScalarType dtype{slimc10::ScalarType::Undefined};
std::vector<int64_t> sizes;
std::vector<int64_t> strides;
};
struct FakeContainer {
std::vector<std::string> internal_names;
std::vector<std::string> fqns;
std::unordered_map<std::string, Binding> bound;
int updates{0};
// Compiled metadata the fake reports for a constant index. Unset entries
// report what the most recent make_cache() geometry and config declare.
std::unordered_map<size_t, int32_t> dtype_override{};
size_t last_update_pairs{0};
// Compiled dtype and bytes by FQN, for constants make_cache() cannot
// describe: storage built straight on a CudaKVPool, side buffers, and
// programs compiled for another geometry than the cache's.
std::unordered_map<std::string, std::pair<int32_t, size_t>> declared{};
// Compiled shape by FQN, as the serialized FQN-weight metadata carries it.
std::unordered_map<std::string, std::vector<int64_t>> shapes{};
};
// Declares `fqn` as compiled with `dtype` and contiguous `sizes`.
void declare(
FakeContainer& container,
const std::string& fqn,
slimc10::ScalarType dtype,
std::initializer_list<int64_t> sizes) {
size_t bytes = slimc10::elementSize(dtype);
for (const int64_t size : sizes) {
bytes *= static_cast<size_t>(size);
}
container.declared[fqn] = {static_cast<int32_t>(dtype), bytes};
container.shapes[fqn] = sizes;
}
// What the program under test was "compiled" with, for the fake's defaults.
struct Compiled {
cache::CacheGeometry geometry;
cache::CacheConfig config;
};
Compiled& compiled() {
static Compiled value;
return value;
}
std::shared_ptr<cache::Cache> make_cache(
const cache::CacheGeometry& geometry,
const cache::CacheConfig& cfg) {
compiled() = Compiled{geometry, cfg};
return cu::make_cuda_sequence_kv_cache(geometry, cfg);
}
// Rows the compiled program declares for one layer's K or V: the capacity,
// or window + max_write - 1 for a ring.
int64_t declared_rows(
const cache::LayerGeometry& layer,
const cache::CacheConfig& cfg) {
return layer.policy.kind == cache::LayerPolicy::Kind::Ring
? layer.policy.window + cfg.max_write.value_or(1) - 1
: cfg.capacity;
}
// Bytes the compiled program declares for one layer's K or V: BSHD at the
// declared rows.
size_t declared_bytes(
const cache::LayerGeometry& layer,
const cache::CacheConfig& cfg) {
return static_cast<size_t>(declared_rows(layer, cfg)) * layer.n_kv_heads *
layer.head_dim *
slimc10::elementSize(static_cast<slimc10::ScalarType>(cfg.kv_dtype));
}
size_t layer_of(const std::string& fqn) {
const std::string prefix = "__et_offgraph_kv_layer_";
return std::stoul(fqn.substr(prefix.size()));
}
// The shapes the serialized metadata carries for the container's off-graph
// constants: what declare() recorded, else what the most recent make_cache()
// geometry and config declare for a layer.
std::unordered_map<std::string, std::vector<int64_t>> compiled_shapes(
const FakeContainer& container) {
std::unordered_map<std::string, std::vector<int64_t>> shapes;
const auto& layers = compiled().geometry.layers;
for (const std::string& fqn : container.fqns) {
const auto declared = container.shapes.find(fqn);
if (declared != container.shapes.end()) {
shapes[fqn] = declared->second;
} else if (
fqn.rfind("__et_offgraph_kv_layer_", 0) == 0 &&
layer_of(fqn) < layers.size()) {
const auto& layer = layers[layer_of(fqn)];
shapes[fqn] = {
1,
declared_rows(layer, compiled().config),
layer.n_kv_heads,
layer.head_dim};
}
}
return shapes;
}
Error get_num_constants(
aoti::AOTInductorModelContainerHandle container,
size_t* count) {
*count = reinterpret_cast<FakeContainer*>(container)->fqns.size();
return Error::Ok;
}
Error get_constant_name(
aoti::AOTInductorModelContainerHandle container,
size_t index,
const char** name) {
*name = reinterpret_cast<FakeContainer*>(container)
->internal_names.at(index)
.c_str();
return Error::Ok;
}
Error get_constant_fqn(
aoti::AOTInductorModelContainerHandle container,
size_t index,
const char** fqn) {
*fqn = reinterpret_cast<FakeContainer*>(container)->fqns.at(index).c_str();
return Error::Ok;
}
Error get_constant_dtype(
aoti::AOTInductorModelContainerHandle container,
size_t index,
int32_t* dtype) {
auto* fake = reinterpret_cast<FakeContainer*>(container);
const auto it = fake->dtype_override.find(index);
if (it != fake->dtype_override.end()) {
*dtype = it->second;
return Error::Ok;
}
const auto declared = fake->declared.find(fake->fqns.at(index));
*dtype = declared != fake->declared.end() ? declared->second.first
: compiled().config.kv_dtype;
return Error::Ok;
}
Error get_constant_data_size(
aoti::AOTInductorModelContainerHandle container,
size_t index,
size_t* data_size) {
auto* fake = reinterpret_cast<FakeContainer*>(container);
const std::string& fqn = fake->fqns.at(index);
const auto declared = fake->declared.find(fqn);
if (declared != fake->declared.end()) {
*data_size = declared->second.second;
return Error::Ok;
}
*data_size = declared_bytes(
compiled().geometry.layers.at(layer_of(fqn)), compiled().config);
return Error::Ok;
}
Error update_pairs(
aoti::AOTInductorModelContainerHandle container,
const aoti::AOTInductorConstantMapEntry* pairs,
size_t count,
bool,
bool) {
auto* fake = reinterpret_cast<FakeContainer*>(container);
++fake->updates;
fake->last_update_pairs = count;
for (size_t index = 0; index < count; ++index) {
auto* tensor = reinterpret_cast<slim::SlimTensor*>(pairs[index].handle);
fake->bound[pairs[index].name] = Binding{
tensor->data_ptr(),
tensor->dtype(),
std::vector<int64_t>(tensor->sizes().begin(), tensor->sizes().end()),
std::vector<int64_t>(
tensor->strides().begin(), tensor->strides().end())};
}
return Error::Ok;
}
cu::CudaDelegateHandle make_handle(FakeContainer& container) {
cu::CudaDelegateHandle handle;
handle.container_handle =
reinterpret_cast<aoti::AOTInductorModelContainerHandle>(&container);
handle.get_num_constants = get_num_constants;
handle.get_constant_name = get_constant_name;
handle.get_constant_original_fqn = get_constant_fqn;
handle.get_constant_dtype = get_constant_dtype;
handle.get_constant_data_size = get_constant_data_size;
handle.update_user_managed_constant_buffer_pairs = update_pairs;
handle.offgraph_kv_sizes = compiled_shapes(container);
return handle;
}
bool has_cuda_device() {
int count = 0;
return cudaGetDeviceCount(&count) == cudaSuccess && count > 0;
}
constexpr int kHeads = 2;
constexpr int kDim = 8;
constexpr int kRow = kHeads * kDim; // elements in one sequence row
cache::CacheGeometry flat_and_ring(int window) {
cache::CacheGeometry geometry;
geometry.layers = {
{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim},
{{cache::LayerPolicy::Kind::Ring, window}, kHeads, kDim},
};
return geometry;
}
FakeContainer flat_and_ring_container() {
return FakeContainer{
{"flat_k", "flat_v", "ring_k", "ring_v"},
{"__et_offgraph_kv_layer_0_k",
"__et_offgraph_kv_layer_0_v",
"__et_offgraph_kv_layer_1_k",
"__et_offgraph_kv_layer_1_v"},
{},
0};
}
std::vector<uint16_t> iota_rows(int rows) {
std::vector<uint16_t> values(static_cast<size_t>(rows) * kRow);
for (size_t index = 0; index < values.size(); ++index) {
values[index] = static_cast<uint16_t>(index + 1);
}
return values;
}
std::vector<uint16_t> read_rows(void* device, int rows) {
std::vector<uint16_t> values(static_cast<size_t>(rows) * kRow);
EXPECT_EQ(
cudaMemcpy(
values.data(),
device,
values.size() * sizeof(uint16_t),
cudaMemcpyDeviceToHost),
cudaSuccess);
return values;
}
class CudaKVCacheTest : public ::testing::Test {
protected:
void SetUp() override {
if (!has_cuda_device()) {
GTEST_SKIP() << "CUDA device required";
}
}
static cache::CacheConfig config(int capacity, int initial, int max_write) {
cache::CacheConfig cfg;
cfg.capacity = capacity;
cfg.initial_capacity = initial;
cfg.max_write = max_write;
cfg.kv_dtype = static_cast<int>(slimc10::ScalarType::BFloat16);
return cfg;
}
};
} // namespace
TEST_F(CudaKVCacheTest, FlatLayersGrowGeometricallyAndKeepHistory) {
constexpr int kWindow = 4;
constexpr int kMaxWrite = 9;
auto cache_ptr = make_cache(flat_and_ring(kWindow), config(32, 4, kMaxWrite));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
// Nothing is allocated until the first step asks for it.
EXPECT_EQ(kv.metrics().allocated_bytes, 0);
ASSERT_EQ(kv.prepare_step(3, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
constexpr int kRingRows = kWindow + kMaxWrite - 1;
EXPECT_EQ(kv.metrics().flat_capacity, 4);
EXPECT_EQ(kv.metrics().growth_count, 0);
EXPECT_EQ(
kv.metrics().allocated_bytes,
2 * (4 + kRingRows) * kRow * static_cast<int64_t>(sizeof(uint16_t)));
// Stand in for the kernels: the step writes rows [0, 3).
const auto history = iota_rows(3);
ASSERT_EQ(
cudaMemcpy(
container.bound["flat_k"].data,
history.data(),
history.size() * sizeof(uint16_t),
cudaMemcpyHostToDevice),
cudaSuccess);
void* first_flat = container.bound["flat_k"].data;
void* first_ring = container.bound["ring_k"].data;
ASSERT_EQ(kv.commit_step(3), Error::Ok);
// 3 + 2 > 4: doubles to 8, moves the flat storage, keeps what was written.
ASSERT_EQ(kv.prepare_step(2, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(kv.metrics().flat_capacity, 8);
EXPECT_EQ(kv.metrics().growth_count, 1);
EXPECT_NE(container.bound["flat_k"].data, first_flat);
EXPECT_EQ(container.bound["ring_k"].data, first_ring);
EXPECT_EQ(read_rows(container.bound["flat_k"].data, 3), history);
ASSERT_EQ(kv.commit_step(2), Error::Ok);
// A step wider than doubling asks for: grows straight to what it needs.
ASSERT_EQ(kv.prepare_step(9, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(kv.metrics().flat_capacity, 16);
ASSERT_EQ(kv.commit_step(9), Error::Ok);
ASSERT_EQ(kv.prepare_step(9, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(kv.metrics().flat_capacity, 32);
EXPECT_EQ(kv.metrics().growth_count, 3);
ASSERT_EQ(kv.commit_step(9), Error::Ok);
// Filling to exactly the declared capacity needs no growth; one more token
// past it is refused, not grown into.
ASSERT_EQ(kv.prepare_step(9, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(kv.metrics().growth_count, 3);
ASSERT_EQ(kv.commit_step(9), Error::Ok);
EXPECT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::InvalidArgument);
EXPECT_EQ(kv.metrics().logical_length, 32);
// A reset keeps the grown storage, so it neither regrows nor moves.
cache_ptr->as<cache::SequenceControl>()->clear();
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(kv.metrics().logical_length, 0);
EXPECT_EQ(kv.metrics().flat_capacity, 32);
EXPECT_EQ(kv.metrics().growth_count, 3);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, BindsTheDeclaredShapeOverTheCurrentAllocation) {
constexpr int kWindow = 4;
constexpr int kMaxWrite = 4;
auto cache_ptr = make_cache(flat_and_ring(kWindow), config(64, 8, kMaxWrite));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
// The program's own declaration: BSHD at the maximum rows, although only
// 8 flat rows are allocated. The ring is fixed at window + max_write - 1.
const std::vector<int64_t> flat_sizes{1, 64, kHeads, kDim};
const std::vector<int64_t> flat_strides{64 * kRow, kRow, kDim, 1};
const std::vector<int64_t> ring_sizes{
1, kWindow + kMaxWrite - 1, kHeads, kDim};
EXPECT_EQ(container.bound["flat_k"].sizes, flat_sizes);
EXPECT_EQ(container.bound["flat_k"].strides, flat_strides);
EXPECT_EQ(container.bound["flat_v"].sizes, flat_sizes);
EXPECT_EQ(container.bound["ring_k"].sizes, ring_sizes);
EXPECT_EQ(kv.metrics().flat_capacity, 8);
// Rebinding is cached until storage moves.
const int updates = container.updates;
ASSERT_EQ(kv.commit_step(1), Error::Ok);
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(container.updates, updates);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, GrowthIsOrderedOnTheStepStream) {
cudaStream_t stream = nullptr;
ASSERT_EQ(
cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), cudaSuccess);
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cache_ptr = make_cache(geometry, config(1 << 16, 4, 4096));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"flat_k", "flat_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
// Enough rows that an unordered copy would plausibly overtake the write.
constexpr int kRows = 4096;
ASSERT_EQ(kv.prepare_step(kRows, stream), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
const auto history = iota_rows(kRows);
// The "kernel" writes asynchronously on the step stream, exactly as the
// compiled program would; nothing waits for it before the next step grows.
ASSERT_EQ(
cudaMemcpyAsync(
container.bound["flat_k"].data,
history.data(),
history.size() * sizeof(uint16_t),
cudaMemcpyHostToDevice,
stream),
cudaSuccess);
ASSERT_EQ(kv.commit_step(kRows), Error::Ok);
ASSERT_EQ(kv.prepare_step(1, stream), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
ASSERT_EQ(kv.metrics().growth_count, 1);
ASSERT_EQ(cudaStreamSynchronize(stream), cudaSuccess);
EXPECT_EQ(read_rows(container.bound["flat_k"].data, kRows), history);
kv.forget_handle(&handle);
cache_ptr.reset();
ASSERT_EQ(cudaStreamDestroy(stream), cudaSuccess);
}
TEST_F(CudaKVCacheTest, FailedGrowthLeavesTheCacheAsItWas) {
// Layer 0 grows first and fits; layer 1 is sized so its growth cannot be
// allocated on any device (tens of GB per row times tens of thousands of
// rows), so the failure lands after one layer has already grown.
constexpr int kHugeDim = 1 << 22;
cache::CacheGeometry geometry;
geometry.layers = {
{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim},
{{cache::LayerPolicy::Kind::Flat, 0}, 1, kHugeDim},
};
auto cache_ptr = make_cache(geometry, config(1 << 16, 4, 1 << 16));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"small_k", "small_v", "huge_k", "huge_v"},
{"__et_offgraph_kv_layer_0_k",
"__et_offgraph_kv_layer_0_v",
"__et_offgraph_kv_layer_1_k",
"__et_offgraph_kv_layer_1_v"},
{},
0};
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_EQ(kv.prepare_step(3, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
const auto history = iota_rows(3);
ASSERT_EQ(
cudaMemcpy(
container.bound["small_k"].data,
history.data(),
history.size() * sizeof(uint16_t),
cudaMemcpyHostToDevice),
cudaSuccess);
ASSERT_EQ(kv.commit_step(3), Error::Ok);
const auto before = kv.metrics();
void* small_k = container.bound["small_k"].data;
void* huge_k = container.bound["huge_k"].data;
const int updates = container.updates;
EXPECT_EQ(
kv.prepare_step(60000, cudaStreamPerThread),
Error::MemoryAllocationFailed);
// Nothing moved: the bindings still point at live storage, which still holds
// the history, and capacity and accounting are unchanged.
const auto after = kv.metrics();
EXPECT_EQ(after.flat_capacity, before.flat_capacity);
EXPECT_EQ(after.growth_count, 0);
EXPECT_EQ(after.allocated_bytes, before.allocated_bytes);
EXPECT_EQ(after.logical_length, 3);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(container.updates, updates);
EXPECT_EQ(container.bound["small_k"].data, small_k);
EXPECT_EQ(container.bound["huge_k"].data, huge_k);
EXPECT_EQ(read_rows(small_k, 3), history);
// And the cache is still usable: a step that fits runs, and a modest growth
// succeeds.
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.commit_step(1), Error::Ok);
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(kv.metrics().flat_capacity, 8);
EXPECT_EQ(kv.metrics().growth_count, 1);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, FailedFirstAllocationCanBeRetried) {
cache::CacheGeometry geometry;
geometry.layers = {
{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim},
{{cache::LayerPolicy::Kind::Flat, 0}, 1, 1 << 22},
};
auto cache_ptr = make_cache(geometry, config(1 << 16, 4, 1 << 16));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"small_k", "small_v", "huge_k", "huge_v"},
{"__et_offgraph_kv_layer_0_k",
"__et_offgraph_kv_layer_0_v",
"__et_offgraph_kv_layer_1_k",
"__et_offgraph_kv_layer_1_v"},
{},
0};
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
// A first step too wide to allocate frees what it did allocate...
EXPECT_EQ(
kv.prepare_step(60000, cudaStreamPerThread),
Error::MemoryAllocationFailed);
EXPECT_EQ(kv.metrics().allocated_bytes, 0);
// ...and a narrower one then allocates normally.
ASSERT_EQ(kv.prepare_step(3, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(kv.metrics().flat_capacity, 4);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, StepOnAnotherStreamWaitsForThePreviousOne) {
cudaStream_t first = nullptr;
cudaStream_t second = nullptr;
ASSERT_EQ(
cudaStreamCreateWithFlags(&first, cudaStreamNonBlocking), cudaSuccess);
ASSERT_EQ(
cudaStreamCreateWithFlags(&second, cudaStreamNonBlocking), cudaSuccess);
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cache_ptr = make_cache(geometry, config(1 << 16, 4, 4096));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"flat_k", "flat_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
constexpr int kRows = 1024;
ASSERT_EQ(kv.prepare_step(kRows, first), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
// The previous step's "kernel" is held back on its stream, then writes.
const size_t bytes = static_cast<size_t>(kRows) * kRow * sizeof(uint16_t);
uint16_t* pinned = nullptr;
ASSERT_EQ(cudaMallocHost(&pinned, bytes), cudaSuccess);
const auto history = iota_rows(kRows);
std::copy(history.begin(), history.end(), pinned);
ASSERT_EQ(
cudaLaunchHostFunc(
first,
[](void*) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
},
nullptr),
cudaSuccess);
ASSERT_EQ(
cudaMemcpyAsync(
container.bound["flat_k"].data,
pinned,
bytes,
cudaMemcpyHostToDevice,
first),
cudaSuccess);
ASSERT_EQ(kv.commit_step(kRows), Error::Ok);
// The next step runs on another stream and grows. Its copy must wait for the
// held-back write rather than copy what was there before it.
ASSERT_EQ(kv.prepare_step(1, second), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
ASSERT_EQ(kv.metrics().growth_count, 1);
ASSERT_EQ(cudaStreamSynchronize(second), cudaSuccess);
EXPECT_EQ(read_rows(container.bound["flat_k"].data, kRows), history);
ASSERT_EQ(cudaStreamSynchronize(first), cudaSuccess);
ASSERT_EQ(cudaFreeHost(pinned), cudaSuccess);
kv.forget_handle(&handle);
cache_ptr.reset();
ASSERT_EQ(cudaStreamDestroy(first), cudaSuccess);
ASSERT_EQ(cudaStreamDestroy(second), cudaSuccess);
}
TEST_F(CudaKVCacheTest, CacheNotMatchingTheCompiledRingIsRejected) {
// Compiled with max_write 8: the ring constants span window + 8 - 1 rows.
// A cache installed with max_write 1 would allocate window rows and let a
// one-token step at position `window` write past them.
constexpr int kWindow = 16;
auto cache_ptr = make_cache(flat_and_ring(kWindow), config(64, 4, 1));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
for (const char* fqn :
{"__et_offgraph_kv_layer_1_k", "__et_offgraph_kv_layer_1_v"}) {
declare(
container,
fqn,
slimc10::ScalarType::BFloat16,
{1, kWindow + 8 - 1, kHeads, kDim});
}
auto handle = make_handle(container);
EXPECT_EQ(kv.note_handle(&handle).error(), Error::InvalidProgram);
EXPECT_EQ(container.updates, 0);
}
TEST_F(CudaKVCacheTest, RingWithinTheSamePaddedBytesIsRejected) {
// One bf16 head of 16: a ring compiled at window 2 spans 64 bytes, and one
// installed at window 1 allocates 32, which AOTI's 64-byte rounding also
// reports as 64. A step at position 1 would index the second row, past the
// allocation, so only the shape may decide.
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Ring, 1}, 1, 16}};
auto cache_ptr = make_cache(geometry, config(64, 4, 1));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"ring_k", "ring_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
for (const char* fqn :
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"}) {
declare(container, fqn, slimc10::ScalarType::BFloat16, {1, 2, 1, 16});
}
ASSERT_EQ(container.declared["__et_offgraph_kv_layer_0_k"].second, 64u);
auto handle = make_handle(container);
EXPECT_EQ(kv.note_handle(&handle).error(), Error::InvalidProgram);
EXPECT_EQ(container.updates, 0);
}
TEST_F(CudaKVCacheTest, CacheNotMatchingTheCompiledCapacityIsRejected) {
auto cache_ptr = make_cache(flat_and_ring(4), config(64, 4, 4));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
for (const char* fqn :
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"}) {
declare(
container, fqn, slimc10::ScalarType::BFloat16, {1, 128, kHeads, kDim});
}
auto handle = make_handle(container);
EXPECT_EQ(kv.note_handle(&handle).error(), Error::InvalidProgram);
}
TEST_F(CudaKVCacheTest, CacheNotMatchingTheCompiledDtypeIsRejected) {
// One-byte storage for a program whose kernels read bf16 would under-
// allocate by half; the dtype check refuses it before any binding.
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cfg = config(32, 4, 4);
cfg.kv_dtype = static_cast<int>(slimc10::ScalarType::Byte);
auto cache_ptr = make_cache(geometry, cfg);
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"flat_k", "flat_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
const auto bf16 = static_cast<int32_t>(slimc10::ScalarType::BFloat16);
container.dtype_override = {{0, bf16}, {1, bf16}};
auto handle = make_handle(container);
EXPECT_EQ(kv.note_handle(&handle).error(), Error::InvalidProgram);
}
TEST_F(CudaKVCacheTest, ReloadingAHandleBindsEachConstantOnce) {
auto cache_ptr = make_cache(flat_and_ring(4), config(64, 4, 4));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_EQ(kv.prepare_step(2, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(container.updates, 1);
EXPECT_EQ(container.last_update_pairs, 4);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, CommitAdmitsTheStepOnEveryLayer) {
// The flat layer alone would accept an 8-token step; the ring, sized for
// max_write 4, cannot, and commit must refuse it as prepare would.
auto cache_ptr = make_cache(flat_and_ring(4), config(64, 4, 4));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_EQ(kv.prepare_step(2, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.commit_step(2), Error::Ok);
EXPECT_EQ(kv.commit_step(8), Error::InvalidArgument);
EXPECT_EQ(kv.metrics().logical_length, 2);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, CacheOutlivesTheStreamItLastSteppedOn) {
cudaStream_t stream = nullptr;
ASSERT_EQ(
cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), cudaSuccess);
auto cache_ptr = make_cache(flat_and_ring(4), config(64, 4, 4));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto container = flat_and_ring_container();
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_EQ(kv.prepare_step(2, stream), Error::Ok);
ASSERT_EQ(kv.commit_step(2), Error::Ok);
kv.forget_handle(&handle);
// The caller's stream goes first; tearing the cache down must not use it.
ASSERT_EQ(cudaStreamDestroy(stream), cudaSuccess);
cache_ptr.reset();
EXPECT_EQ(cudaGetLastError(), cudaSuccess);
EXPECT_EQ(cudaDeviceSynchronize(), cudaSuccess);
}
TEST(OffGraphKVRequirementTest, ReadFromTheProgramNotTheCaller) {
// A program lowered off-graph must not run without a cache even when the
// caller passed no key; one that is not must not be asked for one.
auto offgraph = flat_and_ring_container();
auto offgraph_handle = make_handle(offgraph);
const auto needs = cu::requires_offgraph_kv_storage(offgraph_handle);
ASSERT_TRUE(needs.ok());
EXPECT_TRUE(needs.get());
FakeContainer in_graph{{"weight"}, {"tok_embeddings.weight"}, {}, 0};
auto in_graph_handle = make_handle(in_graph);
const auto plain = cu::requires_offgraph_kv_storage(in_graph_handle);
ASSERT_TRUE(plain.ok());
EXPECT_FALSE(plain.get());
}
TEST_F(CudaKVCacheTest, RingLayersRequireMaxWrite) {
auto cfg = config(32, 4, 4);
cfg.max_write.reset();
EXPECT_EQ(make_cache(flat_and_ring(4), cfg), nullptr);
cache::CacheGeometry flat_only;
flat_only.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
EXPECT_NE(make_cache(flat_only, cfg), nullptr);
}
TEST_F(CudaKVCacheTest, ProgramWithoutStorageIsNotServed) {
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cache_ptr = make_cache(geometry, config(32, 4, 4));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer embedding{{"weight"}, {"tok_embeddings.weight"}, {}, 0};
auto handle = make_handle(embedding);
const auto serves = kv.note_handle(&handle);
ASSERT_EQ(serves.error(), Error::Ok);
EXPECT_FALSE(serves.get());
EXPECT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(embedding.updates, 0);
}
TEST_F(CudaKVCacheTest, SupportedDenseDtypesControlStorageAndBindings) {
for (const auto dtype : {
slimc10::ScalarType::Byte,
slimc10::ScalarType::Char,
slimc10::ScalarType::Short,
slimc10::ScalarType::Int,
slimc10::ScalarType::Long,
slimc10::ScalarType::Half,
slimc10::ScalarType::Float,
slimc10::ScalarType::Bool,
slimc10::ScalarType::BFloat16,
}) {
SCOPED_TRACE(slimc10::toString(dtype));
auto cfg = config(8, 4, 4);
cfg.kv_dtype = static_cast<int>(dtype);
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cache_ptr = make_cache(geometry, cfg);
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"flat_k", "flat_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
ASSERT_EQ(kv.prepare_step(4, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(container.bound["flat_k"].dtype, dtype);
EXPECT_EQ(container.bound["flat_v"].dtype, dtype);
const int64_t element_size =
static_cast<int64_t>(slimc10::elementSize(dtype));
EXPECT_EQ(kv.metrics().allocated_bytes, 2 * 4 * kRow * element_size);
// Growth carries the rows across byte-for-byte whatever the dtype.
std::vector<uint8_t> values(4 * kRow * element_size);
for (size_t index = 0; index < values.size(); ++index) {
values[index] = static_cast<uint8_t>(index % 251 + 1);
}
ASSERT_EQ(
cudaMemcpy(
container.bound["flat_k"].data,
values.data(),
values.size(),
cudaMemcpyHostToDevice),
cudaSuccess);
ASSERT_EQ(kv.commit_step(4), Error::Ok);
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
EXPECT_EQ(kv.metrics().flat_capacity, 8);
std::vector<uint8_t> copied(values.size());
ASSERT_EQ(
cudaMemcpy(
copied.data(),
container.bound["flat_k"].data,
copied.size(),
cudaMemcpyDeviceToHost),
cudaSuccess);
EXPECT_EQ(copied, values);
kv.forget_handle(&handle);
}
}
TEST(OffGraphKVStepWidthTest, ParsesInputIndexAndDim) {
const auto parsed = cu::parse_offgraph_kv_step_width("12:3");
ASSERT_EQ(parsed.error(), Error::Ok);
EXPECT_EQ(parsed.get().input, 12);
EXPECT_EQ(parsed.get().dim, 3);
for (const char* bad : {"", "1", ":0", "1:", "a:0", "1:-1", "-1:0", "1:0x"}) {
SCOPED_TRACE(bad);
EXPECT_EQ(
cu::parse_offgraph_kv_step_width(bad).error(), Error::InvalidArgument);
}
}
TEST(OffGraphKVStepWidthTest, ReadsTheExtentOfTheNamedInput) {
namespace etensor = ::executorch::runtime::etensor;
etensor::TensorImpl::SizesType sizes[] = {1, 7};
etensor::TensorImpl::DimOrderType dim_order[] = {0, 1};
int64_t data[7] = {};
etensor::TensorImpl impl(
etensor::ScalarType::Long, 2, sizes, data, dim_order);
EValue scalar(static_cast<int64_t>(3));
EValue tensor{etensor::Tensor(&impl)};
EValue* inputs[] = {&scalar, &tensor};
const ::executorch::runtime::Span<EValue*> span(inputs, 2);
const auto width = cu::read_offgraph_kv_step_width({1, 1}, span);
ASSERT_EQ(width.error(), Error::Ok);
EXPECT_EQ(width.get(), 7);
// Wrong input, a non-tensor, a dim past the rank, and an empty step.
EXPECT_EQ(
cu::read_offgraph_kv_step_width({2, 0}, span).error(),
Error::InvalidArgument);
EXPECT_EQ(
cu::read_offgraph_kv_step_width({0, 0}, span).error(),
Error::InvalidArgument);
EXPECT_EQ(
cu::read_offgraph_kv_step_width({1, 2}, span).error(),
Error::InvalidArgument);
sizes[1] = 0;
etensor::TensorImpl empty(
etensor::ScalarType::Long, 2, sizes, data, dim_order);
EValue empty_tensor{etensor::Tensor(&empty)};
EValue* empty_inputs[] = {&scalar, &empty_tensor};
EXPECT_EQ(
cu::read_offgraph_kv_step_width(
{1, 1}, ::executorch::runtime::Span<EValue*>(empty_inputs, 2))
.error(),
Error::InvalidArgument);
}
TEST_F(CudaKVCacheTest, GrowthDropsACapturedGraphOnlyWhenStorageMoves) {
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cache_ptr = make_cache(geometry, config(32, 4, 4));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
FakeContainer container{
{"flat_k", "flat_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
auto handle = make_handle(container);
ASSERT_TRUE(kv.note_handle(&handle).get());
// A decode graph captured against the initial storage.
ASSERT_EQ(kv.prepare_step(3, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.rebind_for_execute(&handle), Error::Ok);
auto& graph = handle.cuda_graph_state;
graph.phase = cu::CudaGraphPhase::Replay;
void* static_input = nullptr;
ASSERT_EQ(cudaMalloc(&static_input, 16), cudaSuccess);
graph.static_input_ptrs = {static_input};
graph.static_input_nbytes = {16};
ASSERT_EQ(kv.commit_step(3), Error::Ok);
// Fits the current storage: the graph keeps replaying.
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(kv.metrics().growth_count, 0);
EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Replay);
EXPECT_EQ(graph.static_input_ptrs.size(), 1);
ASSERT_EQ(kv.commit_step(1), Error::Ok);
// Grows: the graph points at freed storage, so the growth itself drops it
// -- freeing what the capture pinned -- and this very call captures again,
// after one eager step that absorbs AOTI's constant fold.
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.metrics().growth_count, 1);
EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Warmup);
EXPECT_EQ(graph.warmup_remaining, 1);
EXPECT_TRUE(graph.static_input_ptrs.empty());
EXPECT_TRUE(graph.static_input_nbytes.empty());
EXPECT_EQ(graph.graph_exec, nullptr);
// Once recaptured, later steps that fit replay it untouched.
graph.phase = cu::CudaGraphPhase::Replay;
ASSERT_EQ(kv.commit_step(1), Error::Ok);
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Replay);
kv.forget_handle(&handle);
}
TEST_F(CudaKVCacheTest, GrowthJustBeforeFirstCaptureKeepsAnEagerStep) {
// A handle whose warmup has run out captures on its next call. A growth
// now rebinds its constants, which must first be folded eagerly, so it gets
// one eager step back -- while a longer outstanding warmup is left alone.
cache::CacheGeometry geometry;
geometry.layers = {{{cache::LayerPolicy::Kind::Flat, 0}, kHeads, kDim}};
auto cache_ptr = make_cache(geometry, config(64, 4, 16));
ASSERT_NE(cache_ptr, nullptr);
auto& kv = *cache_ptr->as<cu::CudaKVCache>();
auto names = [] {
return FakeContainer{
{"flat_k", "flat_v"},
{"__et_offgraph_kv_layer_0_k", "__et_offgraph_kv_layer_0_v"},
{},
0};
};
auto about_container = names();
auto warming_container = names();
auto about_to_capture = make_handle(about_container);
auto still_warming = make_handle(warming_container);
ASSERT_TRUE(kv.note_handle(&about_to_capture).get());
ASSERT_TRUE(kv.note_handle(&still_warming).get());
about_to_capture.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup;
about_to_capture.cuda_graph_state.warmup_remaining = 0;
still_warming.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup;
still_warming.cuda_graph_state.warmup_remaining = 2;
ASSERT_EQ(kv.prepare_step(4, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.commit_step(4), Error::Ok);
ASSERT_EQ(kv.prepare_step(1, cudaStreamPerThread), Error::Ok);
ASSERT_EQ(kv.metrics().growth_count, 1);
EXPECT_EQ(
about_to_capture.cuda_graph_state.phase, cu::CudaGraphPhase::Warmup);
EXPECT_EQ(about_to_capture.cuda_graph_state.warmup_remaining, 1);
EXPECT_EQ(still_warming.cuda_graph_state.warmup_remaining, 2);
kv.forget_handle(&about_to_capture);
kv.forget_handle(&still_warming);