-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathautotuner.py
More file actions
1624 lines (1377 loc) · 66.8 KB
/
Copy pathautotuner.py
File metadata and controls
1624 lines (1377 loc) · 66.8 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
import ast
import contextlib
import copy
import enum
import fcntl
import inspect
import itertools
import json
import os
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import torch
from cuda.bindings import driver
import tensorrt_llm
from tensorrt_llm._torch.distributed import Distributed
from tensorrt_llm._utils import nvtx_range
from tensorrt_llm.bindings.internal.runtime import delay_kernel
from tensorrt_llm.logger import logger
from tensorrt_llm.mapping import Mapping
# Unique tag to avoid collisions with other comms
PP_COMM_TAG_AUTOTUNING = 30000
class DistributedTuningStrategy(enum.Enum):
"""
Strategy for distributed tuning.
Args:
BROADCAST: One rank (rank 0) tunes and broadcasts results to others
INDEPENDENT: Each rank tunes independently (default for non-comm ops)
MERGE: All ranks participate in tuning and reach merge
PARALLEL: All ranks participate in tuning with partial tactics
"""
BROADCAST = "broadcast"
INDEPENDENT = "independent"
MERGE = "merge"
PARALLEL = "parallel"
@dataclass(slots=True, unsafe_hash=True)
class DynamicTensorSpec:
"""
A specification for a dynamic tensor dimension.
Args:
input_idx: The index of the input tensor.
dim_idx: The index of the dimension to tune.
gen_tuning_buckets: A tuple of values to try or a function generating values.
map_to_tuning_buckets: A function to map dimensions to tuning buckets during inference.
"""
input_idx: int
dim_idx: int
gen_tuning_buckets: Union[Tuple[int], Callable] = ()
map_to_tuning_buckets: Callable = lambda x: x
@dataclass(slots=True, unsafe_hash=True)
class ConstraintSpec:
"""
A specification for a constraint on a tensor dimension.
Args:
input_idx: The index of the input tensor.
dim_idx: The index of the dimension to constrain.
infer_shape: A function to infer the shape of the dimension.
"""
input_idx: int
dim_idx: int
infer_shape: Callable
@dataclass(kw_only=True)
class TuningConfig:
"""Configuration for autotuning.
This class specifies all the tuning configurations for a single tuning process.
Args:
dynamic_tensor_specs (Tuple[DynamicTensorSpec]): Specifications for how different tensor dimensions
should be tuned to optimize performance. Each spec defines:
- Which input tensor dimension is dynamic
- How to generate tuning values
- How to map dimensions to tuning values during inference
Example:
>>> config = TuningConfig(
... dynamic_tensor_specs=(
... DynamicTensorSpec(
... input_idx=0,
... dim_idx=1,
... gen_tuning_buckets=(32, 64, 128),
... map_to_tuning_buckets=lambda x: ((x + 31) // 32) * 32
... ),
... )
... )
constraint_specs (Tuple[ConstraintSpec]): Specifications for constraints on tensor dimensions.
Each spec defines:
- Which input tensor dimension is constrained
- How to infer the shape of the dimension based on other dimensions
Example:
>>> config = TuningConfig(
... constraint_specs=(
... ConstraintSpec(
... input_idx=1,
... dim_idx=2,
... infer_shape=lambda shapes: shapes[0][0] * 2
... ),
... )
... )
tune_max_num_tokens (int): The maximum saturation number of tokens to be tuned.
During the inference, the input tensor will be saturated with the same value. Or if
any value is provided to the choose_one function, the input tensor will be saturated
with the provided value.
If not provided, the autotuner will not consider the max num tokens.
inputs_pre_hook (Callable): A function that takes a list of input tensors, returns a list of modified input tensors.
It is called before the input tensors are prepared for the tuning process to match the real data distribution.
use_cold_l2_cache (bool): Whether to use cold L2 cache.
This flag is to create circular buffer of input tensors to avoid L2 cache hits to simulate cold L2 cache.
Notice that not all tuning processes can benefit from this feature.
use_cuda_graph (bool): Whether to use CUDA graph for the tuning process.
distributed_tuning_strategy (DistributedTuningStrategy): Strategy for distributed tuning.
"""
dynamic_tensor_specs: Tuple[DynamicTensorSpec, ...] = ()
constraint_specs: Tuple[ConstraintSpec, ...] = ()
tune_max_num_tokens: int = None
inputs_pre_hook: Callable = None
use_cold_l2_cache: bool = False
use_cuda_graph: bool = True
distributed_tuning_strategy: DistributedTuningStrategy = DistributedTuningStrategy.INDEPENDENT
@dataclass(unsafe_hash=True)
class StaticDim:
val: int
def _opt(self):
return self.val
@dataclass(unsafe_hash=True)
class DynamicDim:
'''Range of one dimension'''
min: int
opt: int
max: int
def _opt(self):
return self.opt
Dim = Union[DynamicDim, StaticDim]
@dataclass
class OptimizationProfile:
'''Ranges of all tensors, all dimension
'''
shapes: List[List[Dim]] = field(default_factory=lambda: [[]])
def get_hash_key(self):
return self.get_opt_shapes()
def get_opt_shapes(self):
'''Only the opt shapes are considered as hash key
'''
# TODO: remove duplicate shape generation
opt_shapes = []
for t in self.shapes:
opt_shapes.append(tuple([d._opt() for d in t]))
return tuple(opt_shapes)
#TODO: can/shall we use the torch builtin FakeTensor class?
@dataclass
class FakeTensor:
dtype: torch.dtype
device: torch.device
shape: List[Dim]
class TunableRunner(ABC):
@abstractmethod
def get_valid_tactics(self, inputs: List[torch.Tensor],
profile: OptimizationProfile, **kwargs) -> List[Any]:
"""One tactic corresponding to one cuda kernel normally, but how to interpret the meaning
of tactic is pure internal details of the runner.
The autotuner will just pass the tactic value to the forward w/o. any knowledge on what the tactic
means. User can choose to implement their own types of tactic for flexibility, such as using a dict-typed
to represent a collection of named configs.
The type of the tactic is arbitrary. But serialization/deserialization of the cache requires that the type is compatible with json.dumps/json.loads.
To evaluate if a type of tactic is compatible with current workflow, try the following code:
* assert YOUR_TACTIC_OBJECT == eval(repr(YOUR_TACTIC_OBJECT))
tactic==-1 has special meaning, means the fallback kernel which should be able to implement any shapes
This fallback tactic is needed for 2 reasons:
* when the autotuner cannot find a valid tactic in it's cache.
* in eager mode, w/o autotunning the custom op should have at least one kernel, which makes the autotuning
process an optional process, such that user can opt out.
We choose not to have a standalone can_implement function, the tactics returned by get_valid_tactics should return
valid kernel for these given input tensors.
"""
return [-1]
def __call__(self, inputs, **kwargs):
return self.forward(inputs, **kwargs)
@abstractmethod
def forward(
self,
/, # tensors are position only
inputs: List[torch.Tensor],
*, # all others are keyword args only
tactic: Any = -1,
do_preparation: bool = False,
**kwargs) -> Any:
"""Forward pass for tunable runners.
Args:
inputs: List of input tensors (position-only argument)
tactic: A arbitrary type that represents a specific kernel config.
For instance, it can be an integer number that specifies the unique ID of the implementation tactic to use.
-1 (default) represents the fallback tactic that must be implemented
to handle any input shapes when autotuning is disabled.
do_preparation: When True, allows one-time setup operations to be performed
before tactic evaluation begins. These operations are excluded
from the performance measurements during autotuning. Notice that
anything prepared in this phase should be persistent in the forward
and can be accessed by the following forward calls.
Returns:
Any: Output of the forward pass.
"""
raise NotImplementedError
def unique_id(self):
"""
Returns a tuple of the unique id of the runner. The unique id will be converted to a string for the cache key.
A common practice is to return a tuple of the runner's attributes, for example:
return (self.output_dtype, self.attribute_1, ...)
Returns:
Any: The unique id of the runner, which can be converted to a string for the cache key.
"""
return tuple(self.__dict__.values())
@contextlib.contextmanager
def autotune(tune_mode: bool = True, cache_path: str = None):
"""Context manager for autotuning with distributed support.
Args:
tune_mode: Whether to enable tuning mode
cache_path: Path to save/load cache files
"""
autotuner = AutoTuner.get()
rank = autotuner.mapping.rank
# if cache_path is provided, use the rank-specific file
tune_required = tune_mode
if cache_path is not None:
# check if the rank-specific file exists
# if the rank-specific file exists, load it
file_exists = os.path.exists(cache_path)
if file_exists:
logger.info(f"[Autotuner] Loading cache from {cache_path}")
autotuner.profiling_cache.load_cache(cache_path, rank)
# record the old tuning mode
old_mode = autotuner.is_tuning_mode
autotuner.is_tuning_mode = tune_required
autotune_enabled = tune_required and not old_mode
if autotune_enabled:
logger.info("[Autotuner] Autotuning process starts ...")
try:
yield
finally:
autotuner.is_tuning_mode = old_mode
if autotune_enabled:
logger.info("[Autotuner] Autotuning process ends")
# save cache
if cache_path is not None:
logger.info(f"[Autotuner] Saving cache to {cache_path}")
autotuner.profiling_cache.save_cache(cache_path, rank)
@dataclass
class AutoTunerStatistics:
"""Statistics collected by the AutoTuner.
Attributes:
cache_misses (int): Number of cache misses requiring fallback
cache_miss_config_collection (Dict[str, Set[OptimizationProfile]]): Collection of configs that caused cache misses
failed_profiling_count (Dict[str, int]): Number of failed profiling attempts per operation
tuned_op_profiled_configs (Dict[str, int]): Profiled configurations per operation
tuned_op_time_cost (Dict[str, float]): Time cost per operation
"""
cache_misses: int = 0
cache_miss_config_collection: Dict[str,
Set[tuple]] = field(default_factory=dict)
failed_profiling_count: Dict[str, Set[Tuple[str, TunableRunner,
OptimizationProfile]]] = field(
default_factory=dict)
tuned_op_profiled_configs: Dict[str, int] = field(default_factory=dict)
tuned_op_time_cost: Dict[str, float] = field(default_factory=dict)
def __str__(self) -> str:
"""Return a string representation of collected statistics.
"""
stats_str = ""
stats_str += f"Cache misses: {self.cache_misses}\n"
if self.cache_miss_config_collection:
stats_str += "Cache miss config collection:\n"
for op, profiles in sorted(
self.cache_miss_config_collection.items()):
stats_str += f" {op}:\n"
for profile in sorted(profiles, key=str):
stats_str += f" - Config: {profile}\n"
if self.tuned_op_profiled_configs:
stats_str += "Tuned operations:\n"
for op in sorted(self.tuned_op_profiled_configs.keys()):
successful = self.tuned_op_profiled_configs[op]
failed = len(self.failed_profiling_count[op])
stats_str += f" {op}:\n"
stats_str += f" - Successful configs: {successful}\n"
stats_str += f" - Failed profiling count: {failed}\n"
if failed > 0:
stats_str += f" - Failed profiling combinations:\n"
for failed_key in self.failed_profiling_count[op]:
stats_str += f" - {failed_key}\n"
if self.tuned_op_time_cost:
stats_str += "Tuned operations time cost:\n"
for op in sorted(self.tuned_op_time_cost.keys()):
stats_str += f" {op}: {self.tuned_op_time_cost[op] * 1000:.4f} milliseconds\n"
return stats_str
class AutoTunerProfilingCache:
"""AutoTunerCache for caching profiling results.
The profiling cache can be serialized to disk for persistence across sessions:
- Use save_cache() to save the cache after tuning
- Use load_cache() to restore cached results before inference
- JSON format provides human-readable output and cross-platform compatibility
"""
def __init__(self):
self.cache: Dict[Tuple, Tuple] = dict()
# Cache metadata for local storage and validation
self.lib_version = tensorrt_llm.__version__
self.creation_timestamp = time.time()
# gpu_platform
self.device_name = torch.cuda.get_device_name()
self.device_capability = torch.cuda.get_device_capability()
def __setitem__(self, cache_key: Tuple, value: Tuple) -> None:
self.cache[cache_key] = value
def __getitem__(self, cache_key: Tuple) -> Tuple:
return self.cache[cache_key]
def __len__(self) -> int:
return len(self.cache)
def clear(self) -> None:
self.cache.clear()
def fallback_entry(self) -> Tuple:
# runner_id = 0, tactic = -1
return 0, -1, float('inf')
def search_cache(
self,
custom_op: str,
runners: List[TunableRunner],
input_shapes: Tuple[torch.Size],
tuning_config: TuningConfig,
apply_map_to_tuning_buckets: bool = True,
) -> Tuple[bool, int, int, Dict[str, Any], OptimizationProfile]:
"""Search for cached profiling results matching the current configuration.
Args:
custom_op (str): The name of the custom operation to be tuned
runners (List[TunableRunner]): List of candidate implementations to profile
profile (OptimizationProfile): Optimization profile
apply_map_to_tuning_buckets: If True, apply map_to_tuning_buckets for runtime cache lookups.
If False, use raw bucket values for tuning cache storage.
Returns:
A tuple containing:
[is_cache_hit, runner_id, tactic, stored_profile]
runner_id is the index in the current runners list
"""
for idx, r in enumerate(runners):
if (cache_key := self.get_cache_key(
custom_op, r, input_shapes, tuning_config,
apply_map_to_tuning_buckets)) in self.cache:
# Return the current index in runners list, not the cached runner_id
cached_runner_id, tactic, min_time = self.cache[cache_key]
return True, idx, tactic, min_time
return False, *self.fallback_entry()
def get_cache_key(
self,
custom_op: str,
runner: TunableRunner,
input_shapes: Tuple[torch.Size],
tuning_config: TuningConfig,
apply_map_to_tuning_buckets: bool = True,
) -> Tuple:
return (
custom_op,
runner.__class__.__name__,
str(runner.unique_id()),
AutoTuner.get()._find_nearest_profile(
input_shapes,
tuning_config.dynamic_tensor_specs,
tuning_config.constraint_specs,
tuning_config.tune_max_num_tokens,
apply_map_to_tuning_buckets,
),
)
def merge_cache_data(self, cache_data: Dict[Tuple, Tuple]):
self.cache.update(cache_data)
def get_specific_custom_op(self, custom_op: str) -> Dict[Tuple, Tuple]:
return {k: v for k, v in self.cache.items() if k[0] == custom_op}
def save_cache(self, file_path: Union[str, Path], rank: int) -> None:
"""Save the profiling cache to disk in JSON format.
Args:
file_path: Path where to save the cache
Raises:
IOError: If file cannot be written
Note:
The cache is saved in JSON format which provides human-readable output.
Some type information may be lost for complex tactic objects.
"""
file_path = Path(file_path)
file_path.parent.mkdir(parents=True, exist_ok=True)
try:
serialized_rank_cache_data = self._serialize_cache_data()
with open(file_path, 'a+') as f:
fcntl.flock(f, fcntl.LOCK_EX)
f.seek(0)
content = f.read()
if content.strip():
current_cache = json.loads(content)
else:
current_cache = {
"metadata": self._serialize_metadata(),
}
f.seek(0)
f.truncate()
current_cache[f"rank_{rank}"] = serialized_rank_cache_data
json.dump(current_cache, f, indent=2, default=str)
logger.info(
f"[AutoTuner] Successfully saved cache to {file_path} using JSON format"
)
except Exception as e:
logger.error(f"[AutoTuner] Failed to save cache with JSON: {e}")
raise
def load_cache(self, file_path: Union[str, Path], rank: int) -> None:
"""Load the profiling cache from disk in JSON format.
Args:
file_path: Path to the cache file
Raises:
FileNotFoundError: If cache file doesn't exist
IOError: If file cannot be read
Note:
Loading will replace the current cache contents. The cache is loaded
from JSON format.
"""
file_path = Path(file_path)
if not file_path.exists():
raise FileNotFoundError(f"Cache file not found: {file_path}")
try:
with open(file_path, 'r') as f:
fcntl.flock(f, fcntl.LOCK_SH)
current_cache_contents = json.load(f)
self._deserialize_metadata(current_cache_contents["metadata"])
assert f"rank_{rank}" in current_cache_contents, f"Rank {rank} cache not found in {file_path}"
self.cache = self._deserialize_cache_data(
current_cache_contents[f'rank_{rank}'])
logger.info(
f"[AutoTuner] Successfully loaded cache from {file_path} using JSON format"
)
except Exception as e:
logger.error(f"[AutoTuner] Failed to load cache with JSON: {e}")
raise
def _serialize_metadata(self) -> Dict[str, Any]:
return {
"lib_version": self.lib_version,
"creation_timestamp": self.creation_timestamp,
"device_name": self.device_name,
"device_capability": self.device_capability,
}
def _deserialize_metadata(self, metadata: Dict[str, Any]) -> None:
self.lib_version = metadata["lib_version"]
self.creation_timestamp = metadata["creation_timestamp"]
self.device_name = metadata["device_name"]
self.device_capability = metadata["device_capability"]
def _serialize_cache_data(self) -> Dict[str, Any]:
"""Convert the profiling cache to a JSON-serializable format.
Returns:
Dictionary that can be serialized to JSON
Note:
This method handles the conversion of complex objects to JSON-compatible
representations. Some type information may be lost in the conversion.
"""
serializable_cache = {}
for key, value in self.cache.items():
# Convert any simple object to string for JSON compatibility
key_str = str(key)
runner_id, tactic, min_time = value
tactic_str = repr(tactic)
try:
assert tactic == ast.literal_eval(
tactic_str
), f"Tactic is not compatible with json.dumps/json.loads"
except Exception as e:
logger.warning_once(
f"[AutoTuner] Could not serialize tactic: {tactic_str} for cache key {key_str} due to {e}. Deserialization may fail.",
key=tactic_str)
serializable_cache[key_str] = {
"runner_id": runner_id,
"tactic": tactic_str,
"min_time": min_time,
}
return serializable_cache
def _deserialize_cache_data(
self, cache_data: Dict[str, Any]) -> Dict[Tuple, Tuple]:
"""Convert JSON-serialized cache back to the original format.
Args:
serializable_cache: Dictionary loaded from JSON
Returns:
Profiling cache in the original format
Note:
This attempts to reconstruct the original data structures but may not
perfectly preserve all type information, especially for complex tactic objects.
"""
cache = {}
for key_str, value in cache_data.items():
# Reconstruct the tuple key safely
try:
key = ast.literal_eval(key_str)
except (ValueError, SyntaxError):
logger.warning(
f"[AutoTuner] Could not reconstruct cache key: {key_str}")
continue
try:
tactic = ast.literal_eval(value["tactic"])
except (ValueError, TypeError):
logger.warning_once(
f"[AutoTuner] Could not deserialize tactic: {value['tactic']} for cache key {key_str}",
key=value["tactic"])
runner_id = value["runner_id"]
min_time = value["min_time"]
cache[key] = (runner_id, tactic, min_time)
return cache
class AutoTuner:
"""AutoTuner for optimizing TensorRT LLM operations.
This class handles automatic performance tuning of tensor operations by profiling
different implementations and caching the best performing configurations.
Args:
warmup (int): Number of warmup iterations before profiling (default: 3)
repeat (int): Number of profiling iterations for averaging (default: 10)
stream_delay_micro_secs (int): Delay on CUDA stream before the profiled kernel runs in microseconds (default: 1000)
"""
_CUDA_GRAPH_DELAY_MICRO_SECS = 100
_instance = None
def __init__(self, warmup=2, repeat=10, stream_delay_micro_secs=1000):
# Increase log level for AutoTuner associated logger`
self._log_level_to_info = os.getenv(
"TLLM_AUTOTUNER_LOG_LEVEL_DEBUG_TO_INFO", '0') == '1'
self._debug_logger = logger.info if self._log_level_to_info else logger.debug
self.repeat = repeat
self.warmup = warmup
self.stream_delay_micro_secs = stream_delay_micro_secs
self.profiling_cache = AutoTunerProfilingCache()
self.is_tuning_mode = False
# Add statistics tracking
self.stats = AutoTunerStatistics()
# Current captured choose_one() contexts
self._active_capture: Optional['AutoTuner.TacticsCapture'] = None
# Last captured choose_one() contexts
self._last_capture: Optional['AutoTuner.TacticsCapture'] = None
# Dsitributed tuning state
self._map_op_to_distributed_strategy: Dict[
str, DistributedTuningStrategy] = {}
self._dist: Optional[Distributed] = None
self._has_received_cache: bool = False
self.mapping: Mapping = Mapping()
@classmethod
def get(cls):
if cls._instance is None:
cls._instance = AutoTuner()
return cls._instance
class TacticsCapture:
"""Object returned by capture() that can be iterated to get all tactic combinations.
This class encapsulates all state related to capturing and replaying tactics:
- Captured execution contexts
- Generated tactic configurations
- Current replay state (which config and call index)
"""
runner_tactic_comb_checkers: List[Callable] = []
def __init__(self, autotuner):
# State for captured contexts
self._captured_contexts: List[Dict[str, Any]] = []
self._context_tactics_lists: Optional[List[List[Tuple[int,
Any]]]] = None
# State for replay mode
self._replay_runner_tactic_list: Optional[List[Tuple[int,
int]]] = None
self._replay_context_idx: int = 0
def __iter__(self):
"""Iterate through all tactic configurations.
For single context: yields (runner, tactic)
For multiple contexts: yields ((runner_ctx0, tactic_ctx0), (runner_ctx1, tactic_ctx1), ...)
"""
if self._context_tactics_lists is None:
self._context_tactics_lists = self._generate_context_tactics_lists(
)
# Generate cartesian product from context and tactics where all_configrations[i][ctx] = (runner, tactic)
# Such that each element in all_configrations is a replay of multiple contexts of all possible replays
for config in itertools.product(*self._context_tactics_lists):
# config is a tuple of (runner_idx, tactic) for each context
# Convert to (runner, tactic) format for user
runner_tactic_pairs = []
for ctx_idx, (runner_idx, tactic) in enumerate(config):
runners = self._captured_contexts[ctx_idx]['runners']
runner = runners[runner_idx]
runner_tactic_pairs.append((runner, tactic))
if not all(
checker(runner_tactic_pairs) for checker in
self.__class__.runner_tactic_comb_checkers):
continue
yield tuple(runner_tactic_pairs)
def _generate_context_tactics_lists(self):
"""Generate all valid tactic combinations."""
if not self._captured_contexts:
raise RuntimeError(
"No context available for testing.\n"
"Use capture() to capture the operation context first:\n"
" with AutoTuner.get().capture() as tactics_capture:\n"
" output = operation.forward(...)\n")
# Collect valid tactics for each context separately
context_tactics_lists = []
for context in self._captured_contexts:
runners = context['runners']
inputs = context['inputs']
kwargs = context.get('kwargs', {})
# Collect all valid (runner, tactic) combinations for this context
tactics_lists = []
for runner_idx, runner in enumerate(runners):
valid_tactics = runner.get_valid_tactics(
inputs, OptimizationProfile(), **kwargs)
for tactic in valid_tactics:
tactics_lists.append((runner_idx, tactic))
context_tactics_lists.append(tactics_lists)
return context_tactics_lists
def is_replaying(self) -> bool:
"""Check if this TacticsCapture is currently in replay mode."""
return self._replay_runner_tactic_list is not None
@classmethod
def register_runner_tactic_comb_checker(cls, checker: Callable):
cls.runner_tactic_comb_checkers.append(checker)
return checker
def choose_one(
self,
custom_op: str,
runners: List[TunableRunner],
tuning_config: TuningConfig,
inputs: List[torch.Tensor],
**kwargs,
) -> Tuple:
"""Choose the best runner and tactic combination through performance profiling.
Args:
custom_op (str): The name of the custom operation to be tuned
runners (List[TunableRunner]): List of candidate implementations to profile
tuning_config (TuningConfig): Configuration for the tuning process
inputs (List[torch.Tensor]): Input tensors for profiling
**kwargs: Arbitrary keyword arguments, will be passed to get_valid_tactics and forward method of each runner
Returns:
Tuple: A tuple containing:
- The selected runner implementation
- The best tactic ID for that runner (-1 if using fallback)
- The best config for that runner (if configs is not empty)
Note:
The method profiles different implementations and tactics to find the
optimal combination based on performance measurements. It caches results
to avoid redundant profiling of the same configuration.
Although runners[0] with tactic=-1 is always treated as the fallback runner.
Runner authors are suggested to provide a fallback implementation for each runner to avoid potential issues.
"""
# Check if we're in replay mode via active TacticsCapture
if self._active_capture is not None and self._active_capture.is_replaying(
):
tactics_capture = self._active_capture
call_idx = tactics_capture._replay_context_idx
assert call_idx < len(tactics_capture._replay_runner_tactic_list
), "call_idx out of range"
assert call_idx < len(
tactics_capture._captured_contexts), "call_idx out of range"
assert len(tactics_capture._replay_runner_tactic_list) == len(
tactics_capture._captured_contexts)
# Check if we have a forced tactic for this call and both custom_op match
captured_custom_op = tactics_capture._captured_contexts[
call_idx].get('custom_op')
if captured_custom_op != custom_op:
raise RuntimeError(
f"Custom op mismatch in kernel testing mode.\n"
f"Expected operation: '{captured_custom_op}'\n"
f"Actual operation: '{custom_op}'\n"
f"Context index: {call_idx}\n"
f"Make sure the forward() call in test mode uses the same operation as captured."
)
runner_idx, tactic = tactics_capture._replay_runner_tactic_list[
call_idx]
# Increment context counter
tactics_capture._replay_context_idx += 1
# Reset counter after all contexts have been used
if tactics_capture._replay_context_idx >= len(
tactics_capture._replay_runner_tactic_list):
tactics_capture._replay_context_idx = 0
return (runners[runner_idx], tactic)
# Capture context for testing all underlying kernels
if self._active_capture is not None and not self._active_capture.is_replaying(
):
self._active_capture._captured_contexts.append({
'custom_op': custom_op,
'runners': runners,
'tuning_config': tuning_config,
'inputs': inputs,
'kwargs': kwargs,
})
input_shapes = tuple(self._get_input_sizes(inputs))
is_cache_hit, best_runner_id, best_tactic, min_time = self.profiling_cache.search_cache(
custom_op,
runners,
input_shapes,
tuning_config,
apply_map_to_tuning_buckets=True)
# Early return if it's not tuning, use cache found one or fallback one
if not self.is_tuning_mode:
best_runner = runners[best_runner_id]
# TODO: check the stored runner and tactic can implement this shape here
# Log the cache miss. Expect no cache miss in inference.
if not is_cache_hit:
logger.warning_once(
f"[AutoTuner] {custom_op} using the fallback tactic, due to cache miss on input shapes={input_shapes}",
key=(custom_op, "warning_autotuning_cache_miss_fallback"))
return (best_runner, best_tactic)
# If it's tuning mode and cache hit, return the best runner and tactic to avoid redundant profiling.
if self.is_tuning_mode and is_cache_hit:
return (runners[best_runner_id], best_tactic)
# PP rank does not have cache hit, so we try to receive the cache from the previous rank
# Notice that only under tuning mode, pp_recv will be called
self.cache_pp_recv()
assert len(runners) > 0, "At least one runner is required"
assert all([isinstance(r, TunableRunner) for r in runners]), \
"All Given runners must be subclass of TunableRunner"
# Record the distributed tuning strategy for the custom_op
self._map_op_to_distributed_strategy[
custom_op] = tuning_config.distributed_tuning_strategy
tuning_start_time = time.perf_counter()
profiles = self._optimization_profiles(tuning_config, inputs)
# Initialize the statistics for the custom_op
if custom_op not in self.stats.tuned_op_profiled_configs:
self.stats.tuned_op_profiled_configs[custom_op] = 0
if custom_op not in self.stats.failed_profiling_count:
self.stats.failed_profiling_count[custom_op] = set()
new_tuning_failure_occurred = False
# Synchronize ranks before profiling
if self._should_current_rank_tune(
tuning_config.distributed_tuning_strategy):
for p in profiles:
tensors = self._prepare_input_tensors(p, inputs)
is_cache_hit, *_ = self.profiling_cache.search_cache(
custom_op,
runners,
p.get_opt_shapes(),
tuning_config,
apply_map_to_tuning_buckets=False,
)
if not is_cache_hit:
# Initialize runner and tactic as None in case of no valid tactic or runners are found
with nvtx_range(f"{custom_op}, shape {p.get_opt_shapes()}"):
best_runner_id, best_tactic, min_time, has_tuning_failure_occurred = self._profile_runners(
custom_op, runners, tensors, p, tuning_config,
**kwargs)
new_tuning_failure_occurred = new_tuning_failure_occurred or has_tuning_failure_occurred
self._maybe_sync_cache_data(tuning_config.distributed_tuning_strategy,
custom_op)
# If failed profiling tactics occurs, log the error.
if new_tuning_failure_occurred:
logger.warning_once(
f"[Autotuner] New tuning error occurs:"
f"Total failed profiling tactics occurs: {len(self.stats.failed_profiling_count[custom_op])} for custom_op={custom_op}. "
f"This will not block the tuning process. "
f"Please set TLLM_LOG_LEVEL=WARNING to find out when the tactic profiling fails. "
f"Set TLLM_LOG_LEVEL=DEBUG to get more details of the failures.",
key=(custom_op, "warning_autotuning_tuning_error_summary"),
)
# Get the best runner and tactic from cache
# If no valid tactic is found, the fallback runner and tactic will be used
_, runner_id, tactic, _ = self.profiling_cache.search_cache(
custom_op, runners, input_shapes, tuning_config)
tuning_end_time = time.perf_counter()
self.stats.tuned_op_time_cost[
custom_op] = self.stats.tuned_op_time_cost.get(
custom_op, 0) + tuning_end_time - tuning_start_time
return (runners[runner_id], tactic)
def _profile_runners(
self,
custom_op: str,
runners: List[TunableRunner],
input_tensors: List[torch.Tensor],
profile: OptimizationProfile,
tuning_config: TuningConfig,
**kwargs,
) -> float:
"""Profile runners and select the best tactic.
For multi-rank profiling, only rank 0 performs the actual profiling
to avoid sync issues when different ranks select different tactics.
The results are then broadcasted to all other ranks.
"""
min_time = float('inf')
has_tuning_failure_occurred = False
best_runner_id, best_tactic = None, None
# If the inputs_pre_hook is provided, it will be called before profiling.
if tuning_config.inputs_pre_hook is not None:
input_tensors = tuning_config.inputs_pre_hook(input_tensors)
for runner_id, runner in enumerate(runners):
# TODO: use FakeTensor here.
runner_arg_names = {
p.name
for p in inspect.signature(runner.forward).parameters.values()
}
all_valid_tactics = runner.get_valid_tactics(
input_tensors, profile, **kwargs)
valid_tactics = self._maybe_parallelize_tactics(
all_valid_tactics, tuning_config.distributed_tuning_strategy)
if "do_preparation" in runner_arg_names and len(valid_tactics) > 0:
runner(
input_tensors,
tactic=-1,
do_preparation=True,
**kwargs,
)
for tac in valid_tactics:
try:
with nvtx_range(f"r{runner_id}, tactic {tac}"):
time_measured = self._profile_single_kernel(
runner=runner,
inputs=input_tensors,
tactic=tac,
tuning_config=tuning_config,
use_cuda_graph=tuning_config.use_cuda_graph,
**kwargs,
)
except Exception as e:
# Handle None tensors for optional inputs
shapes = self._get_input_sizes(input_tensors)
logger.warning_once(
f"[Autotuner] Failed when profiling runner={runner}, tactic={tac}, shapes={shapes}. Error: {e}",
key=(custom_op, "warning_autotuning_profile_failure"),
)
# Record the failed profiling combinations
self.stats.failed_profiling_count[custom_op].add(
self.profiling_cache.get_cache_key(
custom_op,
runner,
profile.get_opt_shapes(),
tuning_config,
apply_map_to_tuning_buckets=False))
# Set time_measured to inf to notify the failure of the tactic. This can happen when `get_valid_tactics` mistakenly return wrong tactics
# or some runtime error occurs during profiling.
time_measured = float('inf')
has_tuning_failure_occurred = True
if time_measured < min_time:
min_time = time_measured
best_runner_id, best_tactic = runner_id, tac
if best_runner_id is not None:
# At least one valid (runner, tactic) pair is found
cache_key = self.profiling_cache.get_cache_key(
custom_op,
runners[best_runner_id],
profile.get_opt_shapes(),
tuning_config,
apply_map_to_tuning_buckets=False)
self._debug_logger(
f"[Autotuner] Profiling runner={runners[best_runner_id]}, tactic={best_tactic} for cache_key={cache_key}."
)
# inspect call stack
# TODO: use named tuple to make it more readable
self.profiling_cache[cache_key] = (best_runner_id, best_tactic,
min_time)
self.stats.tuned_op_profiled_configs[custom_op] += 1