-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathdisaggServerBenchmark.cpp
1584 lines (1421 loc) · 68.8 KB
/
disaggServerBenchmark.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-FileCopyrightText: Copyright (c) 2022-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tensorrt_llm/common/assert.h"
#include "tensorrt_llm/common/logger.h"
#include "tensorrt_llm/executor/disaggServerUtil.h"
#include "tensorrt_llm/executor/executor.h"
#include "tensorrt_llm/executor/types.h"
#include "tensorrt_llm/plugins/api/tllmPlugin.h"
#include "tensorrt_llm/runtime/common.h"
#include "tensorrt_llm/runtime/generationConfig.h"
#include "tensorrt_llm/runtime/gptJsonConfig.h"
#include "tensorrt_llm/runtime/tllmLogger.h"
#include "tensorrt_llm/runtime/utils/mpiUtils.h"
#include "utils/utils.h"
#include "cxxopts.hpp"
#include <nlohmann/json.hpp>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <memory>
#include <mutex>
#include <numeric>
#include <optional>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
using namespace tensorrt_llm::batch_manager;
using namespace tensorrt_llm::runtime;
using namespace tensorrt_llm::benchmark;
using namespace tensorrt_llm::executor::disagg_executor;
namespace texec = tensorrt_llm::executor;
namespace trt = nvinfer1;
namespace
{
class Recorder
{
public:
explicit Recorder(std::string opCsvFile, bool streaming = false, int beamWidth = 1,
bool calculateKvCacheTransferTime = true, bool calculateQueueTime = true, std::string responsesJsonFile = "",
bool excludeInputInOutput = false)
: mOpCsvFile(std::move(opCsvFile))
, mStreaming(streaming)
, mBeamWidth(beamWidth)
, mRespJsonFile(std::move(responsesJsonFile))
, mOutputHasInput(!excludeInputInOutput)
, mCalculateKVCacheTransferTime(calculateKvCacheTransferTime)
, mCalculateQueueTime(calculateQueueTime)
{
}
void initialize()
{
mStart = std::chrono::steady_clock::now();
mSeqLatency.mDataTimes.clear();
mFtLatency.mDataTimes.clear();
mGenLatency.mDataTimes.clear();
mGenFirstTokenLatency.mDataTimes.clear();
mGenT2TLatency.mDataTimes.clear();
mGenExcludeFirstIterT2TLatency.mDataTimes.clear();
mContextReqQueuingLatency.mDataTimes.clear();
mGenReqQueuingLatency.mDataTimes.clear();
mGenReqKvCacheTransferLatency.mDataTimes.clear();
mKvCacheThroughput.mDataTps.clear();
}
void finalize()
{
mEnd = std::chrono::steady_clock::now();
}
void recordContextQueueLatency(std::vector<float> const& latencies)
{
mContextReqQueuingLatency.mDataTimes.insert(
mContextReqQueuingLatency.mDataTimes.end(), latencies.begin(), latencies.end());
}
void recordGenQueueLatency(std::vector<float> const& latencies)
{
mGenReqQueuingLatency.mDataTimes.insert(
mGenReqQueuingLatency.mDataTimes.end(), latencies.begin(), latencies.end());
}
void recordKvCacheTransferLatency(std::vector<float> const& latencies)
{
mGenReqKvCacheTransferLatency.mDataTimes.insert(
mGenReqKvCacheTransferLatency.mDataTimes.end(), latencies.begin(), latencies.end());
}
void recordKvCacheThroughput(std::vector<float> const& throughputs)
{
mKvCacheThroughput.mDataTps.insert(mKvCacheThroughput.mDataTps.end(), throughputs.begin(), throughputs.end());
}
void recordContextStart(SizeType32 inputLength, SizeType32 maxNewTokens, uint64_t requestId,
std::chrono::time_point<std::chrono::steady_clock> const& start)
{
mRequestBenchInfos[requestId] = BenchInfo(inputLength, start);
}
void recordContextEnd(tensorrt_llm::executor::IdType requestId, bool hasError)
{
TLLM_CHECK(mRequestBenchInfos.find(requestId) != mRequestBenchInfos.end());
mRequestBenchInfos.at(requestId).contextEnd = std::chrono::steady_clock::now();
mRequestBenchInfos.at(requestId).contextHasError = hasError;
mRequestBenchInfos.at(requestId).decodingIter += 1;
}
void recordToken(tensorrt_llm::executor::IdType requestId)
{
TLLM_CHECK(mStreaming);
TLLM_CHECK_WITH_INFO(mBeamWidth == 1, "gptManagerBenchmark streaming mode does not support beam > 1");
TLLM_CHECK(mRequestBenchInfos.find(requestId) != mRequestBenchInfos.end());
if (!mRequestBenchInfos.at(requestId).genFirstTokenSeen)
{
mRequestBenchInfos.at(requestId).genFirstTokenTs = std::chrono::steady_clock::now();
mRequestBenchInfos.at(requestId).genFirstTokenSeen = true;
}
mRequestBenchInfos.at(requestId).decodingIter += 1;
}
void recordToken(tensorrt_llm::executor::IdType requestId, texec::Response const& response)
{
TLLM_CHECK(mRequestBenchInfos.find(requestId) != mRequestBenchInfos.end());
auto outputTokenIds = response.getResult().outputTokenIds;
int32_t outputLength = 1;
for (auto const& beam : outputTokenIds)
{
outputLength = std::max(static_cast<int32_t>(beam.size()), outputLength);
}
mRequestBenchInfos[requestId].outputLength += outputLength;
this->recordToken(requestId);
}
void recordGenStart(
tensorrt_llm::executor::IdType requestId, std::chrono::time_point<std::chrono::steady_clock> const& start)
{
TLLM_CHECK(mRequestBenchInfos.find(requestId) != mRequestBenchInfos.end());
mRequestBenchInfos.at(requestId).genStart = start;
}
void recordGenEnd(tensorrt_llm::executor::IdType requestId, bool hasError)
{
TLLM_CHECK(mRequestBenchInfos.find(requestId) != mRequestBenchInfos.end());
mRequestBenchInfos.at(requestId).genEnd = std::chrono::steady_clock::now();
mRequestBenchInfos.at(requestId).genHasError = hasError;
}
void recordGenEnd(tensorrt_llm::executor::IdType requestId, texec::Response const& response)
{
recordGenEnd(requestId, response.hasError());
if (!response.hasError())
{
if (!mStreaming)
{
TLLM_LOG_DEBUG("response.getResult().outputTokenIds");
auto outputTokenIds = response.getResult().outputTokenIds;
int32_t outSeqLen = 0;
for (auto const& beam : outputTokenIds)
{
outSeqLen = std::max(static_cast<int32_t>(beam.size()), outSeqLen);
}
if (mOutputHasInput)
{
int inputSeqLen = mRequestBenchInfos[requestId].inputLength;
outSeqLen -= inputSeqLen;
}
mRequestBenchInfos[requestId].outputLength = outSeqLen;
mRequestBenchInfos[requestId].decodingIter = response.getResult().decodingIter;
}
else
{
recordToken(requestId, response);
}
}
}
void reserve(size_t size)
{
mRequestBenchInfos.reserve(size);
}
void calculateLatencies()
{
for (auto& reqInfo : mRequestBenchInfos)
{
reqInfo.second.latency
= std::chrono::duration<float, std::milli>(reqInfo.second.genEnd - reqInfo.second.contextStart).count();
reqInfo.second.firstTokenLatency
= std::chrono::duration<float, std::milli>(reqInfo.second.contextEnd - reqInfo.second.contextStart)
.count();
reqInfo.second.genLatency
= std::chrono::duration<float, std::milli>(reqInfo.second.genEnd - reqInfo.second.genStart).count();
if (mStreaming)
{
reqInfo.second.genFirstTokenLatency
= std::chrono::duration<float, std::milli>(reqInfo.second.genFirstTokenTs - reqInfo.second.genStart)
.count();
// include the latency of the second token+ kv Cache transfer latency
if (reqInfo.second.outputLength > 1)
{
reqInfo.second.avgGenT2TLatency
= std::chrono::duration<float, std::milli>(reqInfo.second.genEnd - reqInfo.second.genStart)
.count()
/ static_cast<float>(reqInfo.second.outputLength - 1);
}
if (reqInfo.second.outputLength > 2)
{
reqInfo.second.avgGenExcludeFirstIterT2TLatency
= std::chrono::duration<float, std::milli>(
reqInfo.second.genEnd - reqInfo.second.genFirstTokenTs)
.count()
/ static_cast<float>(reqInfo.second.outputLength - 2);
}
}
}
}
void calculateMetrics()
{
calculateLatencies();
int totalOutputTokens{0};
int totalDecodingIter{0};
mNumContextErrorSamples = 0;
mNumGenErrorSamples = 0;
mNumSamples = 0;
for (auto const& reqInfo : mRequestBenchInfos)
{
if (!reqInfo.second.contextHasError && !reqInfo.second.genHasError)
{
mSeqLatency.mDataTimes.push_back(reqInfo.second.latency);
mNumSamples++;
}
if (!reqInfo.second.contextHasError)
{
mFtLatency.mDataTimes.push_back(reqInfo.second.firstTokenLatency);
}
else
{
mNumContextErrorSamples++;
}
if (!reqInfo.second.genHasError)
{
mGenLatency.mDataTimes.push_back(reqInfo.second.genLatency);
totalOutputTokens += reqInfo.second.outputLength;
totalDecodingIter += reqInfo.second.decodingIter;
if (mStreaming)
{
mGenFirstTokenLatency.mDataTimes.push_back(reqInfo.second.genFirstTokenLatency);
if (reqInfo.second.avgGenT2TLatency.has_value())
{
mGenT2TLatency.mDataTimes.push_back(reqInfo.second.avgGenT2TLatency.value());
}
if (reqInfo.second.avgGenExcludeFirstIterT2TLatency.has_value())
{
mGenExcludeFirstIterT2TLatency.mDataTimes.push_back(
reqInfo.second.avgGenExcludeFirstIterT2TLatency.value());
}
}
}
else
{
mNumGenErrorSamples++;
}
}
mTotalLatency = std::chrono::duration<float, std::milli>(mEnd - mStart).count();
mSeqThroughput = mNumSamples / (mTotalLatency / 1000);
mTokenThroughput = totalOutputTokens / (mTotalLatency / 1000);
mAcceptanceRate = totalDecodingIter
? (static_cast<float>(totalOutputTokens) / static_cast<float>(totalDecodingIter))
: 0.0F;
mSeqLatency.calculate();
mFtLatency.calculate();
mGenLatency.calculate();
if (mStreaming)
{
mGenFirstTokenLatency.calculate();
if (!mGenT2TLatency.mDataTimes.empty())
{
mGenT2TLatency.calculate();
std::vector<float> userTokensPerSecond;
userTokensPerSecond.reserve(mGenT2TLatency.mDataTimes.size());
for (auto const& latency : mGenT2TLatency.mDataTimes)
{
userTokensPerSecond.push_back(1000.F / latency);
}
mAvgUserTokensPerSecond = std::accumulate(userTokensPerSecond.begin(), userTokensPerSecond.end(), 0.F)
/ userTokensPerSecond.size();
}
if (!mGenExcludeFirstIterT2TLatency.mDataTimes.empty())
{
mGenExcludeFirstIterT2TLatency.calculate();
}
}
if (mCalculateQueueTime)
{
mContextReqQueuingLatency.calculate();
mGenReqQueuingLatency.calculate();
}
if (mCalculateKVCacheTransferTime)
{
mGenReqKvCacheTransferLatency.calculate();
mKvCacheThroughput.calculate();
}
}
void report()
{
printf("[BENCHMARK] num_samples %d\n", mNumSamples);
printf("[BENCHMARK] num_context_error_samples %d\n", mNumContextErrorSamples);
printf("[BENCHMARK] num_gen_error_samples %d\n", mNumGenErrorSamples);
printf("\n[BENCHMARK] num_samples %d\n", mNumSamples);
printf("[BENCHMARK] total_latency(ms) %.2f\n", mTotalLatency);
printf("[BENCHMARK] seq_throughput(seq/sec) %.2f\n", mSeqThroughput);
printf("[BENCHMARK] token_throughput(token/sec) %.2f\n", mTokenThroughput);
if (mStreaming)
{
printf("[BENCHMARK] user_tokens_per_second(tokens/sec/user) %.2f\n", mAvgUserTokensPerSecond);
}
printf("[BENCHMARK] avg_acceptance_rate(tokens/decoding steps) %.2f\n\n", mAcceptanceRate);
mSeqLatency.report();
mFtLatency.report();
mGenLatency.report();
if (mStreaming)
{
mGenFirstTokenLatency.report();
mGenT2TLatency.report();
mGenExcludeFirstIterT2TLatency.report();
}
if (mCalculateQueueTime)
{
mContextReqQueuingLatency.report();
mGenReqQueuingLatency.report();
}
if (mCalculateKVCacheTransferTime)
{
mGenReqKvCacheTransferLatency.report();
mKvCacheThroughput.report();
}
}
void writeOpMetricsToCsv()
{
if (!mOpCsvFile.empty())
{
std::vector<std::string> headers{"num_samples", "num_context_error_samples", "num_gen_error_samples",
"total_latency(ms)", "seq_throughput(seq/sec)", "token_throughput(token/sec)"};
auto seqLatencyHeader = mSeqLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(seqLatencyHeader.begin()),
std::make_move_iterator(seqLatencyHeader.end()));
auto contextLatencyHeader = mFtLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(contextLatencyHeader.begin()),
std::make_move_iterator(contextLatencyHeader.end()));
auto genLatencyHeader = mGenLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(genLatencyHeader.begin()),
std::make_move_iterator(genLatencyHeader.end()));
if (mStreaming)
{
auto genFirstTokenHeader = mGenFirstTokenLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(genFirstTokenHeader.begin()),
std::make_move_iterator(genFirstTokenHeader.end()));
auto genIngterHeader = mGenT2TLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(genIngterHeader.begin()),
std::make_move_iterator(genIngterHeader.end()));
auto excludeFirstIterIngterHeader = mGenExcludeFirstIterT2TLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(excludeFirstIterIngterHeader.begin()),
std::make_move_iterator(excludeFirstIterIngterHeader.end()));
headers.push_back("avg_user_tokens_per_second(tokens/sec/user)");
}
if (mCalculateKVCacheTransferTime)
{
auto genReqKVCacheTransferHeader = mGenReqKvCacheTransferLatency.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(genReqKVCacheTransferHeader.begin()),
std::make_move_iterator(genReqKVCacheTransferHeader.end()));
auto kvCacheTpHeader = mKvCacheThroughput.genHeaders();
headers.insert(headers.end(), std::make_move_iterator(kvCacheTpHeader.begin()),
std::make_move_iterator(kvCacheTpHeader.end()));
}
std::ofstream outputFile(mOpCsvFile);
if (outputFile.is_open())
{
for (auto const& header : headers)
{
outputFile << header << ",";
}
outputFile << "\n";
outputFile << mNumSamples << "," << mNumContextErrorSamples << "," << mNumGenErrorSamples << ","
<< mTotalLatency << "," << mSeqThroughput << "," << mTokenThroughput << "," << mSeqLatency
<< "," << mFtLatency << "," << mGenLatency;
if (mStreaming)
{
outputFile << "," << mGenFirstTokenLatency << "," << mGenT2TLatency << ","
<< mGenExcludeFirstIterT2TLatency << "," << mAvgUserTokensPerSecond;
}
if (mCalculateKVCacheTransferTime)
{
outputFile << "," << mGenReqKvCacheTransferLatency << "," << mKvCacheThroughput;
}
outputFile << "\n";
}
else
{
std::cerr << "Error opening file '" << mOpCsvFile << "' for writing.\n";
}
}
}
private:
struct BenchInfo
{
BenchInfo() = default;
BenchInfo(int inputLength, std::chrono::time_point<std::chrono::steady_clock> start)
: inputLength(inputLength)
, contextStart(start)
{
}
int inputLength{};
int outputLength{};
std::chrono::time_point<std::chrono::steady_clock> contextStart;
std::chrono::time_point<std::chrono::steady_clock> contextEnd;
std::chrono::time_point<std::chrono::steady_clock> genFirstTokenTs;
std::chrono::time_point<std::chrono::steady_clock> genStart;
std::chrono::time_point<std::chrono::steady_clock> genEnd;
float latency{}; // millisecond
float genLatency{};
bool contextHasError{false};
bool genHasError{false};
float firstTokenLatency{};
float genFirstTokenLatency{};
std::optional<float> avgGenT2TLatency;
std::optional<float> avgGenExcludeFirstIterT2TLatency;
bool genFirstTokenSeen{false};
SizeType32 decodingIter{0};
};
std::unordered_map<uint64_t, BenchInfo> mRequestBenchInfos;
std::chrono::time_point<std::chrono::steady_clock> mStart;
std::chrono::time_point<std::chrono::steady_clock> mEnd;
int mNumSamples{};
int mNumContextErrorSamples{};
int mNumGenErrorSamples{};
float mTotalLatency{};
float mSeqThroughput{};
RecordTimeMetric mSeqLatency{"sequence_latency"};
RecordTimeMetric mFtLatency{"context_latency"};
RecordTimeMetric mGenLatency{"gen_latency"};
RecordTimeMetric mGenFirstTokenLatency{"time_to_gen_first_token"};
RecordTimeMetric mGenT2TLatency{"inter_token_latency"};
RecordTimeMetric mGenExcludeFirstIterT2TLatency{"exclude_first_iter_inter_token_latency"};
RecordTimeMetric mContextReqQueuingLatency{"context_req_queueing_latency"};
RecordTimeMetric mGenReqQueuingLatency{"gen_req_queueing_latency"};
RecordTimeMetric mGenReqKvCacheTransferLatency{"gen_req_kv_cache_transfer_latency"};
RecordBwMetric mKvCacheThroughput{"gen_req_kv_cache_transfer_throughput"};
float mTokenThroughput{};
float mAcceptanceRate{};
std::string mOpCsvFile;
bool mStreaming;
int mBeamWidth;
std::string mRespJsonFile;
std::unordered_map<uint64_t, tensorrt_llm::executor::TensorPtr> mResponseTensors;
bool mOutputHasInput;
bool mCalculateKVCacheTransferTime;
bool mCalculateQueueTime;
float mAvgUserTokensPerSecond{};
};
texec::Request makeExecutorContextRequest(Sample const& sample, SizeType32 const& beamWidth,
std::optional<SizeType32> const& eosId, std::optional<SizeType32> const& padId, bool streaming = false,
bool const& returnContextLogits = false, bool const& returnGenerationLogits = false,
std::optional<texec::LoraConfig> const& loraConfig = std::nullopt,
std::optional<texec::LookaheadDecodingConfig> const& lookaheadConfig = std::nullopt,
std::optional<texec::VecTokens> const& encoderInputTokenIds = std::nullopt)
{
auto samplingConfig = texec::SamplingConfig{beamWidth};
auto outputConfig = texec::OutputConfig{false, returnContextLogits, returnGenerationLogits, false};
auto request
= texec::Request(sample.inputIds, sample.outputLen, streaming, samplingConfig, outputConfig, eosId, padId,
std::nullopt, // positionIds
std::nullopt, // badWords
std::nullopt, // stopWords
std::nullopt, // embeddingBias
std::nullopt, // speculativeDecoding
std::nullopt, // pTuning
std::nullopt, // mRopeConfig
loraConfig, // loraConfig
lookaheadConfig, // lookaheadConfig
std::nullopt, // kvCacheRetentionConfig
std::nullopt, // logitsPostProcessorName
std::nullopt, // logitsPostProcessor
encoderInputTokenIds.has_value() ? encoderInputTokenIds : std::nullopt);
request.setRequestType(tensorrt_llm::executor::RequestType::REQUEST_TYPE_CONTEXT_ONLY);
return request;
}
class DisaggExecutorServer
{
public:
DisaggExecutorServer(std::vector<std::filesystem::path> const& contextEnginePaths,
std::vector<std::filesystem::path> const& genEnginePaths,
std::optional<std::vector<std::vector<SizeType32>>> const& deviceIdsForInstance, int32_t maxBeamWidth,
texec::CapacitySchedulerPolicy capacitySchedulerPolicy, BenchmarkParams const& benchmarkParams,
std::shared_ptr<Recorder> recorder, std::chrono::milliseconds waitSleep, bool logIterationData,
bool hasContextAwaitThreads, bool hasGenAwaitThreads)
: mRecorder(std::move(recorder))
, mWaitSleep(waitSleep)
, mConcurrency(benchmarkParams.concurrency)
, mShutdown(false)
, mLogIterationData(logIterationData)
, mEnableCollectKvCacheTransferTime(benchmarkParams.enableCollectkvCacheTransferTime)
, mEnableCollectIterStats(benchmarkParams.enableCollectIterStats)
{
int worldRank = tensorrt_llm::mpi::MpiComm::world().getRank();
int worldSize = tensorrt_llm::mpi::MpiComm::world().getSize();
mIsOrchestrator = (worldRank == 0);
auto contextNum = contextEnginePaths.size();
auto genNum = genEnginePaths.size();
int deviceCount = -1;
TLLM_CUDA_CHECK(cudaGetDeviceCount(&deviceCount));
std::vector<std::unique_ptr<tensorrt_llm::executor::Executor>> instances;
auto instanceNum = genNum + contextNum;
if (worldRank == 0)
{
TLLM_LOG_INFO("context enigne num :%d gen enigne num:%d", contextNum, genNum);
}
int startRank = 0;
std::vector<texec::ExecutorConfig> ctxExecutorConfigs;
std::vector<texec::ExecutorConfig> genExecutorConfigs;
for (auto in = 0; in < instanceNum; in++)
{
auto&& enginePath = in < contextNum ? contextEnginePaths.at(in) : genEnginePaths.at(in - contextNum);
auto decoderJsonConfig = tensorrt_llm::runtime::GptJsonConfig::parse(enginePath / "config.json");
size_t instanceRanks = decoderJsonConfig.getWorldSize();
std::vector<SizeType32> participateRank(instanceRanks);
std::vector<SizeType32> deviceIds;
if (deviceIdsForInstance.has_value())
{
deviceIds = deviceIdsForInstance.value().at(in);
}
for (int i = 0; i < instanceRanks; i++)
{
startRank++;
participateRank.at(i) = startRank;
if (!deviceIdsForInstance.has_value())
{
deviceIds.push_back((startRank - 1) % deviceCount);
}
}
texec::DynamicBatchConfig dynamicBatchConfig(benchmarkParams.enableBatchSizeTuning);
texec::SchedulerConfig schedulerConfig(capacitySchedulerPolicy, std::nullopt, dynamicBatchConfig);
texec::KvCacheConfig kvCacheConfig(benchmarkParams.enableBlockReuse,
benchmarkParams.maxTokensInPagedKvCache, benchmarkParams.maxAttentionWindowVec,
benchmarkParams.sinkTokenLength, benchmarkParams.freeGpuMemoryFractions.at(in),
benchmarkParams.kvHostCacheSize, benchmarkParams.kvOnboardBlocks);
texec::ExtendedRuntimePerfKnobConfig extendedRuntimePerfKnobConfig(benchmarkParams.multiBlockMode,
benchmarkParams.enableContextFMHAFP32Acc, benchmarkParams.cudaGraphMode,
benchmarkParams.cudaGraphCacheSize);
texec::ExecutorConfig executorConfig(maxBeamWidth, schedulerConfig, kvCacheConfig,
benchmarkParams.enableChunekedContextVec.at(in).value_or(false));
executorConfig.setGpuWeightsPercent(benchmarkParams.gpuWeightsPercent);
texec::OrchestratorConfig orchestratorConfig{mIsOrchestrator, "", nullptr, false};
texec::ParallelConfig parallelConfig{tensorrt_llm::executor::CommunicationType::kMPI,
tensorrt_llm::executor::CommunicationMode::kORCHESTRATOR, deviceIds, participateRank,
orchestratorConfig};
executorConfig.setParallelConfig(parallelConfig);
if (benchmarkParams.maxBatchSizes.at(in))
{
executorConfig.setMaxBatchSize(benchmarkParams.maxBatchSizes.at(in).value());
}
if (benchmarkParams.maxNumTokensVec.at(in))
{
executorConfig.setMaxNumTokens(benchmarkParams.maxNumTokensVec.at(in).value());
}
executorConfig.setDecodingConfig(
texec::DecodingConfig(benchmarkParams.medusaChoices.has_value() ? texec::DecodingMode::Medusa()
: benchmarkParams.executorLookaheadConfig.has_value() ? texec::DecodingMode::Lookahead()
: texec::DecodingMode::Auto(),
benchmarkParams.executorLookaheadConfig, benchmarkParams.medusaChoices));
executorConfig.setExtendedRuntimePerfKnobConfig(extendedRuntimePerfKnobConfig);
constexpr int maxIterationsForRequestStats = 1000;
if (mEnableCollectKvCacheTransferTime)
{
executorConfig.setRequestStatsMaxIterations(maxIterationsForRequestStats);
}
if (!benchmarkParams.enableCollectIterStats)
{
executorConfig.setIterStatsMaxIterations(0);
}
if (in < contextNum)
{
ctxExecutorConfigs.push_back(executorConfig);
}
else
{
genExecutorConfigs.push_back(executorConfig);
}
}
mDisaggExecutor = std::make_unique<DisaggExecutorOrchestrator>(contextEnginePaths, genEnginePaths,
ctxExecutorConfigs, genExecutorConfigs, hasContextAwaitThreads, hasGenAwaitThreads);
if (mIsOrchestrator)
{
if (mEnableCollectIterStats || mEnableCollectKvCacheTransferTime)
{
mCollectStatsThread = std::thread(&DisaggExecutorServer::collectStats, this);
}
}
tensorrt_llm::mpi::MpiComm::world().barrier();
}
std::vector<tensorrt_llm::executor::IdType> enqueueContext(std::vector<texec::Request> const& requests,
std::optional<int> selectContextId = std::nullopt, bool warmup = false, bool batch = false)
{
std::vector<SizeType32> inputLengths;
std::vector<SizeType32> maxNewTokens;
if (!warmup)
{
for (auto const& request : requests)
{
inputLengths.push_back(static_cast<SizeType32>(request.getInputTokenIds().size()));
maxNewTokens.push_back(request.getMaxTokens());
}
}
auto const start = std::chrono::steady_clock::now();
std::vector<tensorrt_llm::executor::IdType> globalReqIds
= mDisaggExecutor->enqueueContext(requests, selectContextId, batch);
if (!warmup)
{
for (size_t i = 0; i < requests.size(); ++i)
{
mRecorder->recordContextStart(inputLengths.at(i), maxNewTokens.at(i), globalReqIds.at(i), start);
}
}
mNumContextActive += requests.size();
return globalReqIds;
}
void enqueueGeneration(std::vector<texec::Request> const& requests,
std::vector<tensorrt_llm::executor::IdType> const& globalRequestIds,
std::optional<int> selectGenIdx = std::nullopt, bool warmup = false, bool batch = false)
{
TLLM_CHECK(globalRequestIds.size() == requests.size());
auto const start = std::chrono::steady_clock::now();
mDisaggExecutor->enqueueGeneration(requests, globalRequestIds, selectGenIdx, batch);
if (!warmup)
{
for (int i = 0; i < requests.size(); i++)
{
mRecorder->recordGenStart(globalRequestIds.at(i), start);
}
}
mNumGenActive += requests.size();
}
std::vector<ResponseWithId> waitForContextResponse(SizeType32 numRequests, bool warmup = false)
{
std::vector<ResponseWithId> ret;
ret.reserve(numRequests);
while ((mNumContextActive != 0) || (mNumContextFinished < numRequests))
{
auto responses = mDisaggExecutor->awaitContextResponses(mWaitSleep);
for (auto&& response : responses)
{
TLLM_CHECK(response.response.getResult().isFinal);
if (response.response.getResult().isFinal)
{
mNumContextActive--;
mNumContextFinished++;
}
if (!warmup)
{
mRecorder->recordContextEnd(response.gid, response.response.hasError());
}
ret.emplace_back(std::move(response));
}
}
return ret;
}
void waitForGenResponse(SizeType32 numRequests, bool warmup = false)
{
while (mNumGenActive > 0 || (mNumGenFinished < numRequests))
{
auto responses = mDisaggExecutor->awaitGenerationResponses(mWaitSleep);
for (auto&& response : responses)
{
if (response.response.getResult().isFinal)
{
mNumGenActive--;
mNumGenFinished++;
if (!warmup)
{
mRecorder->recordGenEnd(response.gid, response.response);
}
}
else
{
// streaming
if (!warmup && !response.response.hasError())
{
mRecorder->recordToken(response.gid, response.response);
}
}
}
}
}
bool canEnqueue(int numSentRequests) const
{
return mIsOrchestrator && (!mConcurrency || (numSentRequests - mNumGenFinished < mConcurrency));
}
~DisaggExecutorServer()
{
mShutdown = true;
if (mCollectStatsThread.joinable())
{
mCollectStatsThread.join();
}
}
void resetNumFinished()
{
mNumContextFinished = 0;
mNumGenFinished = 0;
}
void resetNumActive()
{
mNumContextActive = 0;
mNumGenActive = 0;
}
void collectStats() const
{
while (!mShutdown)
{
std::vector<std::deque<tensorrt_llm::executor::IterationStats>> contextStats;
std::vector<std::deque<tensorrt_llm::executor::IterationStats>> generationStats;
std::vector<std::deque<tensorrt_llm::executor::RequestStatsPerIteration>>
generationRequestStatsPerIteration;
contextStats.reserve(mDisaggExecutor->getContextExecutors().size());
for (auto&& executor : mDisaggExecutor->getContextExecutors())
{
if (executor->canEnqueueRequests())
{
contextStats.emplace_back(executor->getLatestIterationStats());
}
}
generationStats.reserve(mDisaggExecutor->getGenExecutors().size());
for (auto&& executor : mDisaggExecutor->getGenExecutors())
{
if (executor->canEnqueueRequests())
{
if (mEnableCollectIterStats)
{
generationStats.emplace_back(executor->getLatestIterationStats());
}
if (mEnableCollectKvCacheTransferTime)
{
generationRequestStatsPerIteration.emplace_back(executor->getLatestRequestStats());
}
}
}
if (mEnableCollectIterStats)
{
for (std::size_t i = 0; i < contextStats.size(); i++)
{
auto const& iterStats = contextStats.at(i);
for (auto const& stat : iterStats)
{
SizeType32 numNewActiveRequests = stat.numNewActiveRequests;
if (numNewActiveRequests > 0)
{
auto avgQueueingTime
= static_cast<float>(stat.newActiveRequestsQueueLatencyMS / numNewActiveRequests);
std::vector<float> requestsQueueLatencyMS(numNewActiveRequests, avgQueueingTime);
mRecorder->recordContextQueueLatency(requestsQueueLatencyMS);
}
if (mLogIterationData)
{
TLLM_LOG_INFO(
"ctx_id %d, ctx_stat: %s", i, texec::JsonSerialization::toJsonStr(stat).c_str());
}
}
}
for (std::size_t i = 0; i < generationStats.size(); i++)
{
auto const& iterStats = generationStats.at(i);
for (auto const& stat : iterStats)
{
SizeType32 numNewActiveRequests = stat.numNewActiveRequests;
if (numNewActiveRequests > 0)
{
float avgQueueingTime
= static_cast<float>(stat.newActiveRequestsQueueLatencyMS / numNewActiveRequests);
std::vector<float> requestsQueueLatencyMS(numNewActiveRequests, avgQueueingTime);
mRecorder->recordGenQueueLatency(requestsQueueLatencyMS);
}
if (mLogIterationData)
{
TLLM_LOG_INFO(
"gen_id %d, gen_stat: %s", i, texec::JsonSerialization::toJsonStr(stat).c_str());
}
}
}
}
if (mEnableCollectKvCacheTransferTime)
{
for (std::size_t i = 0; i < generationRequestStatsPerIteration.size(); i++)
{
auto const& stats = generationRequestStatsPerIteration.at(i);
for (auto const& stat : stats)
{
std::vector<float> kvCacheTransferMs;
std::vector<float> kvCacheThroughput;
for (auto const& requestStat : stat.requestStats)
{
if (requestStat.stage == tensorrt_llm::executor::RequestStage::kGENERATION_COMPLETE)
{
kvCacheTransferMs.push_back(
static_cast<float>(requestStat.disServingStats->kvCacheTransferMS));
kvCacheThroughput.push_back(static_cast<float>(requestStat.disServingStats->kvCacheSize)
* 8 / (static_cast<float>(requestStat.disServingStats->kvCacheTransferMS) / 1000)
/ 1e9f);
}
}
if (kvCacheTransferMs.size() > 0)
{
mRecorder->recordKvCacheTransferLatency(kvCacheTransferMs);
}
if (kvCacheThroughput.size() > 0)
{
mRecorder->recordKvCacheThroughput(kvCacheThroughput);
}
if (mLogIterationData)
{
TLLM_LOG_INFO(
"gen_id %d, gen_req_stat: %s", i, texec::JsonSerialization::toJsonStr(stat).c_str());
}
}
}
}
auto const waitSleep = std::chrono::milliseconds(50);
std::this_thread::sleep_for(waitSleep);
}
}
std::unique_ptr<DisaggExecutorOrchestrator> const& getDisaggExecutor() const noexcept
{
return mDisaggExecutor;
}
private:
std::unique_ptr<DisaggExecutorOrchestrator> mDisaggExecutor;
std::atomic<bool> mShutdown{false};
bool mIsOrchestrator{false};
std::shared_ptr<Recorder> mRecorder;
std::chrono::milliseconds mWaitSleep;
std::optional<int> mConcurrency;
bool mLogIterationData{false};
bool const mEnableCollectKvCacheTransferTime;
bool const mEnableCollectIterStats;
std::thread mCollectStatsThread;
std::atomic<uint64_t> mNumGenFinished{0};
std::atomic<uint64_t> mNumContextFinished{0};
std::atomic<uint64_t> mNumGenActive{0};
std::atomic<uint64_t> mNumContextActive{0};
};
} // namespace
void benchmark(std::vector<std::filesystem::path> const& contextEngineDirs,
std::vector<std::filesystem::path> const& generationEngineDirs,
std::optional<std::vector<std::vector<int>>> const& deviceIdsForInstances, std::string const& datasetPath,
std::string const& opCsvFile, int maxNumSamples, int beamWidth, int warmUp, std::optional<int32_t> const& eosId,
std::optional<int32_t> const& padId, BenchmarkParams const& benchmarkParams,
texec::CapacitySchedulerPolicy capacitySchedulerPolicy, std::chrono::milliseconds waitSleep,
bool returnContextLogits, bool returnGenerationLogits, std::optional<int> const staticEmulatedBatchSize,
bool logIterationData, std::optional<SizeType32> const maxPromptLen, bool hasContextAwait, bool hasGenAwait)
{
auto const& world = tensorrt_llm::mpi::MpiComm::world();
auto worldRank = world.getRank();
// Load dataset
auto const samples = parseWorkloadJson(datasetPath, maxNumSamples, maxPromptLen);
auto const numSamples = samples.size();
auto recorder = std::make_shared<Recorder>(opCsvFile, benchmarkParams.streaming, beamWidth,
benchmarkParams.enableCollectkvCacheTransferTime, benchmarkParams.enableCollectIterStats);
auto disaggExecutor = std::make_shared<DisaggExecutorServer>(contextEngineDirs, generationEngineDirs,
deviceIdsForInstances, beamWidth, capacitySchedulerPolicy, benchmarkParams, recorder, waitSleep,
logIterationData, hasContextAwait, hasGenAwait);
constexpr size_t numMap = 8;
std::vector<std::unordered_map<tensorrt_llm::executor::IdType, tensorrt_llm::executor::Request>> gidToRequestMaps(
numMap);
std::vector<std::mutex> mtxForMaps(numMap);
auto fillRequestMap = [&](std::vector<tensorrt_llm::executor::IdType> const& reqIds,
std::vector<tensorrt_llm::executor::Request>&& requests)
{
TLLM_CHECK(reqIds.size() == requests.size());
for (size_t i = 0; i < reqIds.size(); i++)
{
size_t mapIdx = reqIds[i] % numMap;
std::scoped_lock<std::mutex> lock(mtxForMaps[mapIdx]);
gidToRequestMaps.at(mapIdx).emplace(reqIds[i], std::move(requests[i]));
}
};
auto makeGenRequest = [&](std::vector<ResponseWithId>&& contextResponse)
{
std::vector<tensorrt_llm::executor::IdType> gids;
gids.reserve(contextResponse.size());
std::vector<tensorrt_llm::executor::Request> genRequest;
genRequest.reserve(contextResponse.size());
for (auto&& ctxResponse : contextResponse)
{
gids.emplace_back(ctxResponse.gid);
size_t mapIdx = ctxResponse.gid % numMap;
std::unique_lock<std::mutex> lock(mtxForMaps[mapIdx]);
TLLM_CHECK(gidToRequestMaps.at(mapIdx).find(ctxResponse.gid) != gidToRequestMaps.at(mapIdx).end());
auto ctxRequest = std::move(gidToRequestMaps.at(mapIdx).at(ctxResponse.gid));
gidToRequestMaps.at(mapIdx).erase(ctxResponse.gid);
lock.unlock();
ctxRequest.setRequestType(tensorrt_llm::executor::RequestType::REQUEST_TYPE_GENERATION_ONLY);
ctxRequest.setContextPhaseParams(ctxResponse.response.getResult().contextPhaseParams.value());
genRequest.emplace_back(std::move(ctxRequest));
}
return std::make_pair(genRequest, gids);