# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. # # 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. import ast import concurrent.futures import contextlib import copy import enum import errno import fcntl import inspect import itertools import json import os import time import zlib from abc import ABC, abstractmethod from collections import Counter 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 import _jit_share as jit_share from tensorrt_llm._torch.distributed import Distributed from tensorrt_llm._torch.modules.multi_stream_utils import no_eager_forks from tensorrt_llm._torch.nccl_window_graph import ( abandon_nccl_window_graph_owner, nccl_window_allocation_suppressed, nccl_window_graph_capture, release_nccl_window_graph_owner) from tensorrt_llm._torch.nccl_window_tensor_scope import \ nccl_window_tensor_scope from tensorrt_llm._utils import (confidential_compute_enabled, local_mpi_size, mpi_disabled, nvtx_range) from tensorrt_llm.bindings.internal.runtime import (delay_kernel, record_global_timer) 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. A negative result indicates the input is outside the supported tuning range. Such inputs miss the cache. In skip-sweep mode, a negative mapping for any required dimension suppresses profiling of the entire operation. """ 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. exclude_from_cache (bool): Skip disk persistence of tuning results for this op. Use for JIT-driven ops where caching the tactic across processes would skip the JIT warmup. In-process cache still works. parallel_jit_warmup (int): Before profiling, run every not-yet-tuned profile once on this many threads. For runners whose first call per shape JIT-compiles a kernel and releases the GIL while compiling (DeepGEMM), those compiles then overlap, and the profiling loop that follows finds them built. Opted-in runners must be thread-safe and must not use NCCL windows. 0 disables; -1 uses the CPUs this rank may run on, divided by the ranks on the node unless the rank is pinned to a subset, up to 32: neighbouring sweep points often select the same kernel and compile it twice, so more threads keep paying off. TLLM_AUTOTUNER_PARALLEL_JIT_WARMUP overrides the thread count. share_jit_builds (bool): For runners whose kernels are DeepGEMM builds or CuTe DSL kernels kept in their class's ``kernel_cache``. When the processes of the launch share their JIT builds (TLLM_JIT_SHARE_DIR, see tensorrt_llm._jit_share), each kernel is built by one process and loaded by the others. They split the profiles not yet tuned through claims in that directory: for a single tactic, each rank runs the profiles it claims first, setting aside one whose kernel another rank is building, then the profiles other ranks claimed once those have run; for several tactics under INDEPENDENT tuning, a build pass first runs each (profile, runner, tactic) once on the rank that claims it, and the profiling that follows finds the kernels built. The claims then take the place of the ``parallel_jit_warmup`` thread pool, which does not run. cold_l2_flush_bytes (int): When > 0, every timed repeat first reads a buffer of this many bytes (evicting the operands, weights included, from L2) and each repeat is timed alone with %globaltimer stamps inside one CUDA graph; the median repeat is the tactic's time. For decode-sized GEMMs whose weights never stay in L2 between uses. """ 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 exclude_from_cache: bool = False parallel_jit_warmup: int = 0 share_jit_builds: bool = False cold_l2_flush_bytes: int = 0 @dataclass(frozen=True) class NvMMHConfig: """nvMatmulHeuristics (nvMMH) guidance for CuTe DSL GEMM/BMM runners. When installed on the AutoTuner, nvMMH-aware runners build their tactic list from the top ``max_tactics`` kernel configurations nvMMH ranks for the problem instead of enumerating their full tactic space. Every field nvMMH models (CTA tile, cluster shape, split-K, rasterization order, swizzle) is taken as returned; only knobs nvMMH does not model are swept. """ max_tactics: int = 5 def __post_init__(self): if (isinstance(self.max_tactics, bool) or not isinstance(self.max_tactics, int) or self.max_tactics < 1): raise ValueError( f"NvMMHConfig.max_tactics must be a positive integer, got " f"{self.max_tactics!r}") @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 its 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()) def tactic_space_key(self) -> Optional[Tuple]: """Discriminates cache entries profiled over a non-default tactic space. Runners whose candidate tactics depend on a process-wide search policy (e.g. nvMatmulHeuristics guidance) return a literal tuple describing that policy, so entries tuned under one policy are not reused under another. None keeps the default cache key. """ return None @contextlib.contextmanager def autotune(tune_mode: bool = True, cache_path: str = None, skip_dynamic_tuning_buckets: bool = False, post_tune_merge_dist: Optional[Distributed] = None): """Context manager for autotuning with distributed support. Args: tune_mode: Whether to enable tuning mode cache_path: Path to save/load cache files skip_dynamic_tuning_buckets: When True, suppress bucket generation in _optimization_profiles() and profile the encountered shapes and their mapped buckets, subject to tune_max_num_tokens. Inputs with no mapped bucket use the fallback without profiling. Useful for workloads (e.g. diffusion) where the LLM-oriented M-bucket sweep is unnecessary. post_tune_merge_dist: Optional ``Distributed``. When set, tactics are tuned per-rank independently and merged across ranks in one collective at context exit (before the cache is saved) — for pipelines whose warmup is not SPMD and so cannot use the per-op distributed strategies. """ autotuner = AutoTuner.get() if post_tune_merge_dist is not None: # Save the singleton's prior state: the full-world dist attached for the # merge is temporary and must not leak into later sessions. Attach the # real (world-sized) mapping now for a correct rank, but with no dist # yet: _is_distributed() stays False so per-op sync is skipped while a # non-SPMD pipeline tunes; the dist is attached at exit to merge. prev_mapping, prev_dist = autotuner.mapping, autotuner._dist autotuner.setup_distributed_state(post_tune_merge_dist.mapping, None) 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 old_skip = autotuner.skip_dynamic_tuning_buckets autotuner.is_tuning_mode = tune_required autotuner.skip_dynamic_tuning_buckets = skip_dynamic_tuning_buckets # Avoid making compiled AllReduce paths initialize or inspect AutoTuner. from tensorrt_llm._torch.distributed.ops import \ set_allreduce_autotuner_tuning_mode set_allreduce_autotuner_tuning_mode(tune_required) autotune_enabled = tune_required and not old_mode if autotune_enabled: logger.info("[Autotuner] Autotuning process starts ...") # Fine-grained sync kernels deadlock when profiled, so force them off for the duration via the # C++ override rather than mutating os.environ. TODO: remove once autotuning handles them. if autotune_enabled: torch.ops.trtllm.set_fine_grained_sync_disabled_override(True) # While tuning, CuTe DSL kernels in shared runner caches go through the # directory of TLLM_JIT_SHARE_DIR (see tensorrt_llm._jit_share). kernel_sharing = (jit_share.sharing_kernels() if tune_required and jit_share.enabled() else contextlib.nullcontext()) eager_forks_context = (no_eager_forks() if tune_required else contextlib.nullcontext()) try: with kernel_sharing, eager_forks_context: yield finally: autotuner.is_tuning_mode = old_mode autotuner.skip_dynamic_tuning_buckets = old_skip set_allreduce_autotuner_tuning_mode(old_mode) if autotune_enabled: AutoTuner.L2_FLUSH_BUFFERS.clear() torch.ops.trtllm.set_fine_grained_sync_disabled_override(False) logger.info("[Autotuner] Autotuning process ends") try: # Merge tactics across ranks in one collective before the cache is # saved, so non-SPMD pipelines can tune independently and still agree. if post_tune_merge_dist is not None: autotuner.setup_distributed_state(post_tune_merge_dist.mapping, post_tune_merge_dist) autotuner.post_tune_merge_tactics() # 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) finally: # Restore the singleton's prior distributed state (see enter) so the # temporary full-world state does not persist past this context. if post_tune_merge_dist is not None: autotuner.mapping = prev_mapping autotuner._dist = prev_dist @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 # POSIX ESTALE and the Linux NFS client's EBADHANDLE (521). _STALE_HANDLE_ERRNOS = (errno.ESTALE, 521) def _read_cache_text(file_path: Path, attempts: int = 5) -> str: """Read the cache file, retrying reads that hit a stale NFS handle.""" for attempt in range(attempts): try: with open(file_path, "r") as f: return f.read() except OSError as e: if e.errno not in _STALE_HANDLE_ERRNOS or attempt == attempts - 1: raise logger.warning( f"[AutoTuner] Retrying cache read of {file_path} after {e!r}") time.sleep(0.2 * (attempt + 1)) raise AssertionError("unreachable") def _fastest_entries(per_rank: List[Dict[Tuple, Tuple]]) -> Dict[Tuple, Tuple]: """Per cache key, the fastest of the ranks' entries (ties: the lowest rank's).""" merged = {} for entries in per_rank: for key, value in entries.items(): if value[-1] < merged.get(key, (float('inf'), ))[-1]: merged[key] = value return merged def _majority_entries(per_rank: List[Dict[Tuple, Tuple]]) -> Dict[Tuple, Tuple]: """Per cache key, the entry whose tactic most ranks hold (ties: the lowest rank's).""" merged = {} for key in {key for entries in per_rank for key in entries}: held = [entries[key] for entries in per_rank if key in entries] votes = Counter(repr(value[1]) for value in held) top = max(votes.values()) merged[key] = next(value for value in held if votes[repr(value[1])] == top) return merged @contextlib.contextmanager def _exclusive_cache_lock(lock_path: Path): """Cross-node-correct exclusive lock used by save_cache/load_cache. POSIX byte-range lock (`fcntl.lockf`) held on a SEPARATE lockfile (not the data file), which avoids the truncate / rename complications of locking the file you're also rewriting. The lockfile is persistent; the kernel releases the lock when the holding fd is closed — including on process death, so there is no stale-lock cleanup path to maintain. Both readers and writers use LOCK_EX: read/write frequencies on the autotuner cache are similar and the simpler "always exclusive" model avoids reader/writer-priority pitfalls on networked filesystems. """ lock_path.parent.mkdir(parents=True, exist_ok=True) fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o644) try: fcntl.lockf(fd, fcntl.LOCK_EX) yield finally: try: fcntl.lockf(fd, fcntl.LOCK_UN) finally: os.close(fd) 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 Cache organization: - Ops with INDEPENDENT strategy are stored per-rank (rank_0, rank_1, ...) - Ops with non-INDEPENDENT strategy (BROADCAST, MERGE, PARALLEL) are stored in a shared dict since all ranks share the same tuning results """ # Key for shared cache entries (non-INDEPENDENT ops) SHARED_CACHE_KEY = "shared" def __init__(self): self.cache: Dict[Tuple, Tuple] = dict() # Track which ops use which distributed strategy # Maps custom_op name -> DistributedTuningStrategy self.independent_op: Set[str] = set() # Ops whose tuning results must NOT be persisted to disk (see the # `exclude_from_cache` field on TuningConfig). Populated lazily # from choose_one when an excluded op is first seen. self.excluded_op: Set[str] = set() # 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() self.independent_op.clear() self.excluded_op.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 """ # Under PARALLEL each rank of the tuning group times a share of the # (runner, tactic) pairs and records its own fastest, so after the # merge a shape can hold one entry per runner: the winner is the # fastest of them, not the first runner in the list. parallel = (tuning_config.distributed_tuning_strategy == DistributedTuningStrategy.PARALLEL) found = None 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] if not parallel: return True, idx, tactic, min_time if found is None or min_time < found[3]: found = (True, idx, tactic, min_time) if found is not None: return found 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: cache_key = ( 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, ), ) tactic_space_key = runner.tactic_space_key() if tactic_space_key is not None: cache_key += (tactic_space_key, ) return cache_key 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 add_independent_op(self, custom_op: str, strategy: DistributedTuningStrategy) -> None: if strategy != DistributedTuningStrategy.INDEPENDENT: self.independent_op.add(custom_op) def add_excluded_op(self, custom_op: str) -> None: """Mark `custom_op` as excluded from disk persistence. Entries for excluded ops still live in the in-memory cache (so within one process the lookup-and-reuse path works normally), but `_partition_cache_by_strategy` will drop them at `save_cache` time so they are never written to disk. Combined with the force-retune branch in `AutoTuner.choose_one`, this guarantees the tuning process (and any JIT warmup it triggers as a side effect) re-runs on every process startup. """ self.excluded_op.add(custom_op) def _partition_cache_by_strategy( self) -> Tuple[Dict[Tuple, Tuple], Dict[Tuple, Tuple]]: """Partition cache entries into shared and rank-specific caches. Returns: A tuple of (shared_cache, rank_cache) where: - shared_cache: entries for non-INDEPENDENT ops (BROADCAST, MERGE, PARALLEL) - rank_cache: entries for INDEPENDENT ops Entries belonging to `self.excluded_op` are dropped from both partitions so they never reach disk. """ shared_cache = {} rank_cache = {} for key, value in self.cache.items(): custom_op = key[0] # First element of cache key is custom_op name if custom_op in self.excluded_op: continue if custom_op not in self.independent_op: rank_cache[key] = value else: shared_cache[key] = value return shared_cache, rank_cache def save_cache(self, file_path: Union[str, Path], rank: int) -> None: """Save the profiling cache to disk in JSON format. Cache entries are organized based on distributed strategy: - INDEPENDENT ops are saved per-rank (rank_0, rank_1, ...) - Non-INDEPENDENT ops (BROADCAST, MERGE, PARALLEL) are saved in a shared dict - Ops marked `exclude_from_cache=True` are dropped entirely. Args: file_path: Path where to save the cache rank: The rank of the current process 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. Concurrency model: * Cross-process mutual exclusion uses POSIX byte-range locks (`fcntl.lockf`) on a SEPARATE lockfile next to the data file. The lockfile is persistent (never unlinked); the kernel auto-releases the lock when the holding fd is closed, including on crash, so no stale-lock cleanup is needed. Both readers and writers take LOCK_EX — read/write frequencies are similar here and the simpler logic is worth more than read parallelism. * The data file itself is replaced atomically via (write-to-tmp + fsync + rename). A writer killed at any point leaves a discardable .tmp file; `file_path` is never partially written, so concurrent readers always see a fully-formed JSON document. * The on-disk rank-specific dict is MERGED (not replaced) with this writer's contribution so a concurrent writer that loaded earlier does not get its entries clobbered. """ file_path = Path(file_path) file_path.parent.mkdir(parents=True, exist_ok=True) lock_path = self._lock_path_for(file_path) try: # Partition cache into shared (non-INDEPENDENT) and rank-specific (INDEPENDENT) shared_cache, rank_cache = self._partition_cache_by_strategy() serialized_shared_cache = self._serialize_cache_data(shared_cache) serialized_rank_cache = self._serialize_cache_data(rank_cache) with _exclusive_cache_lock(lock_path): current_cache = self._read_existing_cache(file_path) # Merge shared cache entries (non-INDEPENDENT ops) if self.SHARED_CACHE_KEY not in current_cache: current_cache[self.SHARED_CACHE_KEY] = {} current_cache[self.SHARED_CACHE_KEY].update( serialized_shared_cache) # Merge rank-specific cache entries (INDEPENDENT ops). # MUST be a merge (not assignment): a concurrent writer # that committed its rank_{rank} contribution between # this writer's load_cache and save_cache would otherwise # be silently dropped by an `=` assignment that re-writes # the slot with only this writer's in-memory cache. rank_key = f"rank_{rank}" if rank_key not in current_cache: current_cache[rank_key] = {} current_cache[rank_key].update(serialized_rank_cache) self._atomic_write_json(file_path, current_cache) 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 @staticmethod def _lock_path_for(file_path: Path) -> Path: """Return the lockfile path that pairs with `file_path`.""" return file_path.with_name(file_path.name + ".lock") def _read_existing_cache(self, file_path: Path) -> Dict[str, Any]: """Read the data file (best-effort) under the caller's lock.""" if not file_path.exists(): return {"metadata": self._serialize_metadata()} try: content = _read_cache_text(file_path) if not content.strip(): return {"metadata": self._serialize_metadata()} return json.loads(content) except (FileNotFoundError, json.JSONDecodeError) as e: # An earlier writer from a pre-fix version may have left a # corrupted file behind. Don't fail the current save — start # from a fresh dict and overwrite atomically. logger.warning(f"[AutoTuner] Could not parse existing cache at " f"{file_path}: {e!r}; starting from a fresh dict.") return {"metadata": self._serialize_metadata()} @staticmethod def _atomic_write_json(file_path: Path, payload: Dict[str, Any]) -> None: """Write `payload` to `file_path` atomically (tmp + fsync + rename).""" tmp_path = file_path.with_name( f".{file_path.name}.tmp.{os.getpid()}.{time.time_ns()}") with open(tmp_path, "w") as f: json.dump(payload, f, indent=2, default=str) f.flush() os.fsync(f.fileno()) os.rename(tmp_path, file_path) def load_cache(self, file_path: Union[str, Path], rank: int) -> None: """Load the profiling cache from disk in JSON format. Loads both shared cache entries (non-INDEPENDENT ops) and rank-specific entries (INDEPENDENT ops) and merges them into the current cache. Args: file_path: Path to the cache file rank: The rank of the current process 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}") lock_path = self._lock_path_for(file_path) try: with _exclusive_cache_lock(lock_path): current_cache_contents = json.loads(_read_cache_text(file_path)) self._deserialize_metadata( current_cache_contents.get("metadata", {})) # Start with empty cache and independent ops set self.cache = {} self.independent_op = set() # Load shared cache entries (non-INDEPENDENT ops) if self.SHARED_CACHE_KEY in current_cache_contents: shared_cache = self._deserialize_cache_data( current_cache_contents[self.SHARED_CACHE_KEY]) self.cache.update(shared_cache) # add custom op in shared cache to independent ops set for key in shared_cache.keys(): self.independent_op.add(key[0]) logger.debug( f"[AutoTuner] Loaded {len(shared_cache)} shared cache entries" ) # Load rank-specific cache entries (INDEPENDENT ops) rank_key = f"rank_{rank}" if rank_key in current_cache_contents: rank_cache = self._deserialize_cache_data( current_cache_contents[rank_key]) self.cache.update(rank_cache) logger.debug( f"[AutoTuner] Loaded {len(rank_cache)} rank-specific cache entries for rank {rank}" ) logger.info( f"[AutoTuner] Successfully loaded cache from {file_path} using JSON format (total {len(self.cache)} entries)" ) logger.info( f"[AutoTuner] independent_op: {type(self.independent_op) if hasattr(self, 'independent_op') else 'not found'}" ) 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, cache: Optional[Dict[Tuple, Tuple]] = None ) -> Dict[str, Any]: """Convert the profiling cache to a JSON-serializable format. Args: cache: Optional cache dict to serialize. If None, uses self.cache. 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. """ if cache is None: cache = self.cache serializable_cache = {} for key, value in cache.items(): # Convert any simple object to string for JSON compatibility key_str = str(key) runner_id, tactic, min_time = value # Enum tactics (e.g. Fp4QuantTactic) repr as "", # which ast.literal_eval can't parse back -> load_cache crash. Serialize # the underlying value (reload yields that value; an IntEnum compares # equal to it and kernels take the int). is_enum = isinstance(tactic, enum.Enum) tactic_check = tactic.value if is_enum else tactic tactic_str = repr(tactic_check) try: # Verify the serialized value round-trips (compare against the # value we store, not the enum member — else non-IntEnum fails). assert tactic_check == 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, SyntaxError): # Skip any tactic whose repr is not a Python literal so one bad # entry can't crash the whole load; the op just re-profiles. # (#16782 removes the current enum trigger at the serialize side.) # SyntaxError is caught too; `continue` is required, else the # entry reuses the previous tactic. logger.warning_once( f"[AutoTuner] Could not deserialize tactic: {value['tactic']} for cache key {key_str}; skipping entry.", key=value["tactic"]) continue runner_id = value["runner_id"] min_time = value["min_time"] cache[key] = (runner_id, tactic, min_time) return cache def _spec_in_bounds(spec, shapes_list) -> bool: """Validate that spec.input_idx and spec.dim_idx are in range for shapes_list. On out-of-bounds access, log a warning and return False. Otherwise return True. Pass the SHAPE LIST (list-of-lists or equivalent indexable), not the wrapping object. Both ``OptimizationProfile.shapes`` and the raw list-of-lists ``base_profile`` used inside :meth:`AutoTuner._find_nearest_profile` are valid inputs because the helper only uses ``len(...)`` and indexing. Args: spec: A ``DynamicTensorSpec`` or ``ConstraintSpec`` with ``input_idx`` and ``dim_idx`` attributes. The spec's class name is used in the warning message. shapes_list: An indexable container of per-input shape lists. """ spec_kind = type(spec).__name__ if spec.input_idx < 0 or spec.input_idx >= len(shapes_list): logger.warning( f"[Autotuner] Skipping {spec_kind} with input_idx={spec.input_idx}: " f"only {len(shapes_list)} inputs available.") return False if spec.dim_idx < 0 or spec.dim_idx >= len(shapes_list[spec.input_idx]): logger.warning( f"[Autotuner] Skipping {spec_kind} with dim_idx={spec.dim_idx} for " f"input {spec.input_idx}: shape has only " f"{len(shapes_list[spec.input_idx])} dims.") return False return True def _default_parallel_jit_warmup_threads() -> int: """Threads for ``parallel_jit_warmup=-1``: this rank's CPUs, up to 32. The compilers the warmup starts inherit this process's CPU affinity. A rank pinned to a subset of the host's CPUs has that subset to itself; unpinned ranks share all of them, so each takes its share by the ranks on the node. """ try: cpus = len(os.sched_getaffinity(0)) except AttributeError: # no affinity API (non-Linux) cpus = os.cpu_count() or 1 if cpus >= (os.cpu_count() or cpus): local_ranks = int(os.environ.get("LOCAL_WORLD_SIZE", "1")) if not mpi_disabled(): try: local_ranks = local_mpi_size() except Exception: # noqa: BLE001 - MPI cannot split by node here pass cpus //= max(1, local_ranks) return min(32, cpus) 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._primed_cached_tactics: set[tuple[str, str, str, str]] = set() # Cache keys whose runner ran in this process (so any JIT it drives # has happened here), as opposed to keys loaded from disk or peers. self._keys_profiled_in_process: set[Tuple] = set() self.is_tuning_mode = False self.skip_dynamic_tuning_buckets = False # nvMatmulHeuristics guidance for CuTe DSL GEMM/BMM runners; None # profiles their full tactic space. self.nvmmh_config: Optional[NvMMHConfig] = None # Timing backend: globaltimer kernel vs cuda events. # TLLM_PROFILING_TIMER env var overrides auto-detection: # "globaltimer" -> force globaltimer # "cuda_event" -> force cuda events # unset/default -> auto-detect via confidential_compute_enabled() timer_env = os.getenv("TLLM_PROFILING_TIMER", "").lower() if timer_env == "globaltimer": self._use_global_timer = True elif timer_env == "cuda_event": self._use_global_timer = False else: self._use_global_timer = confidential_compute_enabled() logger.debug(f"[Autotuner] use_global_timer: {self._use_global_timer}") # 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 # CUDA graph memory pool shared by the profiling captures of one # choose_one() tuning pass (see _shared_profile_graph_pool). self._profile_graph_pool: Optional[torch.cuda.MemPool] = None self._profile_graph_pool_depth = 0 # Dsitributed tuning state self._dist: Optional[Distributed] = None self._has_received_cache: bool = False self.mapping: Mapping = Mapping() # Depth of this rank's _profile_runners_impl calls, which may run on this rank alone. self._profiling_depth = 0 @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)) # For ops opted out of the persistent cache (e.g. JIT-driven # kernels whose "tuning" triggers compilation as a side effect), # mark them in the cache so save_cache filters them out, and # — in tuning mode — force the full profile path so the JIT # warmup actually runs even if a stale on-disk entry was loaded. # In inference mode we still consult the in-process cache, which # was populated by this process's own warmup. if tuning_config.exclude_from_cache: self.profiling_cache.add_excluded_op(custom_op) 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)) if (tuning_config.exclude_from_cache and self.is_tuning_mode and is_cache_hit and self.profiling_cache.get_cache_key( custom_op, runners[best_runner_id], input_shapes, tuning_config, apply_map_to_tuning_buckets=True) not in self._keys_profiled_in_process): # Only an entry this process profiled proves its JIT side # effects already ran here; re-profile anything else. is_cache_hit = False best_runner_id, best_tactic, min_time = ( self.profiling_cache.fallback_entry()) # 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")) if logger.level == 'debug': fine_grained_on = os.environ.get("TLLM_USE_FINE_GRAINED_SYNC", "0") == "1" logger.debug_once( f"[Autotuner] Inference dispatch: custom_op={custom_op}, runner={best_runner}, " f"tactic={best_tactic}, fine_grained={'ON' if fine_grained_on else 'OFF'}", key=(custom_op, "inference_dispatch_fine_grained")) return (best_runner, best_tactic) # Collective strategies tune in lockstep, but ranks can load different # caches from a shared file: tune unless every rank has the entry. if self._needs_rank_agreement( tuning_config.distributed_tuning_strategy): is_cache_hit = self._hit_on_all_ranks(is_cache_hit) # 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: self._prime_cached_tactics(custom_op, runners, tuning_config, inputs, **kwargs) 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.profiling_cache.add_independent_op( custom_op, strategy=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 strategy = tuning_config.distributed_tuning_strategy if self._should_current_rank_tune(strategy): def is_cached(p: OptimizationProfile) -> bool: return self.profiling_cache.search_cache( custom_op, runners, p.get_opt_shapes(), tuning_config, apply_map_to_tuning_buckets=False, )[0] # Every rank profiles under MERGE / PARALLEL, so they agree on the profiles to tune. agreed_hits = None if (self._needs_rank_agreement(strategy) and strategy != DistributedTuningStrategy.BROADCAST): agreed_hits = dict( zip([p.get_opt_shapes() for p in profiles], self._profile_hits_on_all_ranks( profiles, [is_cached(p) for p in profiles]))) def is_pending(p: OptimizationProfile) -> bool: if agreed_hits is not None: return not agreed_hits[p.get_opt_shapes()] return not is_cached(p) def profile_one(p: OptimizationProfile) -> None: nonlocal new_tuning_failure_occurred if is_pending(p): tensors = self._prepare_input_tensors(p, inputs) # 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()}"): *_, 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 share_builds = (tuning_config.share_jit_builds and jit_share.enabled()) one_pair = share_builds and self._one_pair_per_profile( runners, profiles, inputs, tuning_config, is_pending, **kwargs) if share_builds: jit_share.share_kernel_caches(runners) if (not one_pair and tuning_config.distributed_tuning_strategy == DistributedTuningStrategy.INDEPENDENT): self._build_across_ranks(custom_op, runners, profiles, inputs, tuning_config, is_pending, **kwargs) else: self._parallel_jit_warmup(custom_op, runners, profiles, inputs, tuning_config, **kwargs) with self._shared_profile_graph_pool(): if one_pair: self._profile_sharing_jit_builds(custom_op, profiles, profile_one, is_pending) else: # Profiling waits for the kernels other processes still build in # the build pass, all of them together for one wait at most. with (jit_share.wait_until(time.time() + jit_share.wait_seconds()) if share_builds else contextlib.nullcontext()): for p in profiles: profile_one(p) self._maybe_sync_cache_data(tuning_config.distributed_tuning_strategy, custom_op) self._prime_cached_tactics(custom_op, runners, tuning_config, inputs, **kwargs) # 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 _tuning_tensors(self, profile: OptimizationProfile, inputs: List[torch.Tensor], tuning_config: TuningConfig) -> List[torch.Tensor]: tensors = self._prepare_input_tensors(profile, inputs) if tuning_config.inputs_pre_hook is not None: tensors = tuning_config.inputs_pre_hook(tensors) return tensors def _one_pair_per_profile(self, runners: List[TunableRunner], profiles: List[OptimizationProfile], inputs: List[torch.Tensor], tuning_config: TuningConfig, is_pending: Callable[[OptimizationProfile], bool], **kwargs) -> bool: """Whether the op profiles one (runner, tactic) per profile, judged on its first profile not yet tuned: the single-pair shortcut, where profiling a profile is the call that builds its kernel.""" if tuning_config.distributed_tuning_strategy in ( DistributedTuningStrategy.MERGE, DistributedTuningStrategy.PARALLEL): return False first = next((p for p in profiles if is_pending(p)), None) if first is None: return True tensors = self._tuning_tensors(first, inputs, tuning_config) return sum( len(r.get_valid_tactics(tensors, first, **kwargs)) for r in runners) == 1 def _build_across_ranks(self, custom_op: str, runners: List[TunableRunner], profiles: List[OptimizationProfile], inputs: List[torch.Tensor], tuning_config: TuningConfig, is_pending: Callable[[OptimizationProfile], bool], **kwargs) -> None: """Build the kernels that profiling the pending profiles needs, split across the processes that share JIT builds. Each (profile, runner, tactic) runs once, on the process that claims it, so its kernels are built there and published for the others; one whose kernel another process is still building is skipped. Results are discarded and failures are left to the profiling that follows, which loads each kernel built here or elsewhere, or waits for one still being built. """ pending = [p for p in profiles if is_pending(p)] items = [] for i, p in enumerate(pending): tensors = self._tuning_tensors(p, inputs, tuning_config) for r, runner in enumerate(runners): items.extend((i, r, tactic) for tactic in runner.get_valid_tactics( tensors, p, **kwargs)) if not items: return sweep = jit_share.SharedSweep( repr((custom_op, [p.get_opt_shapes() for p in pending], items))) start = int(jit_share.start_fraction() * len(items)) ran = busy = 0 current, tensors, prepared = None, None, set() begin = time.perf_counter() with jit_share.defer_busy_builds(): for k in list(range(start, len(items))) + list(range(start)): if not sweep.claim(k): continue i, r, tactic = items[k] if i != current: current, prepared = i, set() tensors = self._tuning_tensors(pending[i], inputs, tuning_config) runner = runners[r] try: if r not in prepared and "do_preparation" in inspect.signature( runner.forward).parameters: runner(tensors, tactic=-1, do_preparation=True, **kwargs) prepared.add(r) runner(tensors, tactic=tactic, **kwargs) torch.cuda.current_stream().synchronize() ran += 1 except Exception as e: # noqa: BLE001 - profiling reports failures busy += jit_share.is_busy(e) finally: sweep.done(k) self._debug_logger( f"[Autotuner] {custom_op}: shared JIT builds over {len(items)} (profile, " f"runner, tactic) items of {len(pending)} profiles: ran {ran} claimed here and " f"skipped {busy} whose kernel another process was building, in " f"{time.perf_counter() - begin:.1f}s") def _profile_sharing_jit_builds( self, custom_op: str, profiles: List[OptimizationProfile], profile_one: Callable[[OptimizationProfile], None], is_pending: Callable[[OptimizationProfile], bool]) -> None: """Run ``profile_one`` over ``profiles`` while the processes share DeepGEMM's builds. The processes split the not yet tuned profiles: each claims profiles from an offset of its own (claims in the shared directory) and runs them first. It sets aside a claimed profile whose kernel another process is building, so that it goes on to kernels nobody has claimed, and runs the set-aside profiles after the others. Last, it runs the profiles other processes claimed, each once that process has run it, when the profile's kernel is in DeepGEMM's shared cache. The set-aside and other processes' profiles wait for other processes at most one wait in total (:func:`jit_share.wait_seconds`); past it, this process runs each profile left and builds its kernel itself. """ profiles = list(profiles) pending = [i for i, p in enumerate(profiles) if is_pending(p)] if not pending: for p in profiles: profile_one(p) return sweep = jit_share.SharedSweep( repr((custom_op, [profiles[i].get_opt_shapes() for i in pending]))) start = int(jit_share.start_fraction() * len(pending)) claimed, set_aside, others = [], [], [] begin = time.perf_counter() with jit_share.defer_busy_builds(): for i in pending[start:] + pending[:start]: if not sweep.claim(i): others.append(i) continue try: profile_one(profiles[i]) except Exception as e: if not jit_share.is_busy(e): sweep.done(i) raise set_aside.append(i) continue claimed.append(i) sweep.done(i) aside_begin = time.perf_counter() late = 0 with jit_share.wait_until(time.time() + jit_share.wait_seconds()): for i in set_aside: try: profile_one(profiles[i]) finally: sweep.done(i) others_begin = time.perf_counter() for i in others: late += not sweep.wait_done(i) profile_one(profiles[i]) pending_set = set(pending) for i, p in enumerate(profiles): if i not in pending_set: profile_one(p) self._debug_logger( f"[Autotuner] {custom_op}: shared JIT builds over {len(pending)} profiles: " f"ran {len(claimed) + len(set_aside)} claimed in {others_begin - begin:.1f}s " f"({len(set_aside)} set aside while another process built their kernel, " f"{others_begin - aside_begin:.1f}s), then {len(others)} claimed elsewhere in " f"{time.perf_counter() - others_begin:.1f}s ({late} not run there in time)" ) def _prime_cached_tactics( self, custom_op: str, runners: List[TunableRunner], tuning_config: TuningConfig, inputs: List[torch.Tensor], **kwargs, ) -> None: """Compile cached winners in this process during tuning, not inference.""" if os.environ.get("TLLM_AUTOTUNER_PRIME_CACHED_TACTICS", "1") != "1": return # Cache hits may differ across ranks; collective runners must stay # inside lockstep profiling, including profiling scratch allocation. if tuning_config.distributed_tuning_strategy == DistributedTuningStrategy.MERGE: return jit_classes = { type(r) for r in runners if isinstance(getattr(type(r), "kernel_cache", None), dict) } if not jit_classes: return for profile in self._optimization_profiles(tuning_config, inputs): hit, runner_id, tactic, _ = self.profiling_cache.search_cache( custom_op, runners, profile.get_opt_shapes(), tuning_config, apply_map_to_tuning_buckets=False, ) if not hit: continue runner = runners[runner_id] if type(runner) not in jit_classes: continue key = (custom_op, type(runner).__name__, str(runner.unique_id()), str(tactic)) if key in self._primed_cached_tactics: continue tensors = self._prepare_input_tensors(profile, inputs) if tuning_config.inputs_pre_hook is not None: tensors = tuning_config.inputs_pre_hook(tensors) try: with nvtx_range(f"{custom_op} prime tactic {tactic}"): if "do_preparation" in inspect.signature( runner.forward).parameters: runner(tensors, tactic=-1, do_preparation=True, **kwargs) runner(tensors, tactic=tactic, **kwargs) self._primed_cached_tactics.add(key) except Exception as e: try: torch.cuda.synchronize() except RuntimeError: pass logger.warning( f"[Autotuner] Priming cached tactic failed for custom_op={custom_op}, " f"runner={type(runner).__name__}, tactic={tactic}, " f"shapes={profile.get_opt_shapes()}. Error: {e}") def _profile_runners( self, custom_op: str, runners: List[TunableRunner], input_tensors: List[torch.Tensor], profile: OptimizationProfile, tuning_config: TuningConfig, **kwargs, ) -> float: # PARALLEL ranks profile different tactics, so window requests here would diverge the # per-rank pools and let a later request register a window collectively on some ranks only. window_guard = (nccl_window_allocation_suppressed() if tuning_config.distributed_tuning_strategy == DistributedTuningStrategy.PARALLEL and self._is_distributed() else contextlib.nullcontext()) with window_guard, nccl_window_tensor_scope(input_tensors) as scope: scope.escape(input_tensors) if tuning_config.inputs_pre_hook is not None: input_tensors = tuning_config.inputs_pre_hook(input_tensors) self._profiling_depth += 1 try: return self._profile_runners_impl(custom_op, runners, input_tensors, profile, tuning_config, **kwargs) finally: self._profiling_depth -= 1 def _profile_runners_impl( 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 # (runner, tactic) pairs this rank profiles: all of them, or under # PARALLEL its share of the deal, which can be empty. local_pairs = 0 # Pre-walk the runners so we know the total candidate (runner, tactic) # pair count before deciding whether to short-circuit profiling. The # count is taken BEFORE distributed-strategy splitting; the PARALLEL # strategy can leave a rank with one tactic locally even though the # full set has several, and that case must still go through the # timed profile path so the merge picks a real winner. candidates = [] total_pairs = 0 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) total_pairs += len(all_valid_tactics) candidates.append( (runner_id, runner, runner_arg_names, all_valid_tactics)) # MERGE/PARALLEL strategies rely on comparing per-rank timings to # pick the winning tactic across ranks. If a rank's local set of # tactics has only one entry we must still time it — the shortcut # would record min_time=0.0, which collides with peer ranks' 0.0 # in the tie-break and silently drops slower tactics on the floor. if total_pairs == 1 and tuning_config.distributed_tuning_strategy not in ( DistributedTuningStrategy.MERGE, DistributedTuningStrategy.PARALLEL): # Single-pair shortcut. There is nothing to compare against, so # the timed warmup + profile-repeat loop is pure overhead. We # fire one forward call on every rank to drive any JIT side # effects (e.g. DeepGEMM cubin compile for fp8_swap_ab_gemm), # then record the pair in the cache directly. `do_preparation` # still runs for runners that opt into it. runner_id, runner, runner_arg_names, valid_tactics = next( c for c in candidates if len(c[3]) == 1) tac = valid_tactics[0] local_pairs = 1 if "do_preparation" in runner_arg_names: runner(input_tensors, tactic=-1, do_preparation=True, **kwargs) try: with nvtx_range(f"r{runner_id}, tactic {tac} (single-pair)"): self._run_profile_runner(runner, input_tensors, tac, **kwargs) best_runner_id, best_tactic = runner_id, tac # No comparable measurement exists; min_time stays 0.0 to # distinguish "recorded without profiling" from a real # timing. min_time = 0.0 except Exception as e: if jit_share.is_busy(e): raise # Not a failure: the caller runs this profile later. shapes = self._get_input_sizes(input_tensors) logger.warning_once( f"[Autotuner] Single-pair run failed for custom_op={custom_op}, runner={runner}, tactic={tac}, shapes={shapes}. Error: {e}", key=(custom_op, "warning_autotuning_single_pair_failure"), ) 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)) has_tuning_failure_occurred = True # The shortcut's candidate is recorded like the timed path's, so a # run's log lists every pair either way: 0.000 is the documented # recorded-without-profiling marker, a failure shows as inf. Same # placement rationale as the timed path: after the handler, so a # formatting error is never recorded as a tactic failure. self._debug_logger( f"[Autotuner] Candidate: custom_op={custom_op}, " f"runner={runner}, tactic={tac}, " f"shapes={profile.get_opt_shapes()}, " f"time={(0.0 if best_runner_id is not None else float('inf')):.3f}ms" ) else: # PARALLEL deals the (runner, tactic) pairs of all runners round # robin, so every rank of the group gets an even share even when # one runner has many tactics and the others few. The deal starts # at a rank taken from the op and the shape, the same on every # rank, so a runner's costly tactics do not fall on the same ranks # at every shape. pair_offset = self._parallel_deal_start( custom_op, profile, tuning_config.distributed_tuning_strategy) for runner_id, runner, runner_arg_names, all_valid_tactics in candidates: valid_tactics = self._maybe_parallelize_tactics( all_valid_tactics, tuning_config.distributed_tuning_strategy, offset=pair_offset) pair_offset += len(all_valid_tactics) local_pairs += len(valid_tactics) 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: # Synchronize to clear any pending CUDA errors left by the # failed tactic. Without this, the stale error propagates # to subsequent CUDA/cuBLAS calls in the forward pass # (observed as CUBLAS_STATUS_EXECUTION_FAILED on SM103). try: torch.cuda.synchronize() except Exception: pass if jit_share.is_busy(e): raise # Not a failure: the caller runs this profile later. # 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 self._debug_logger( f"[Autotuner] Candidate: custom_op={custom_op}, " f"runner={runner}, tactic={tac}, " f"shapes={profile.get_opt_shapes()}, " f"time={time_measured:.3f}ms") 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}." ) self._debug_logger( f"[Autotuner] Selected: custom_op={custom_op}, runner={runners[best_runner_id]}, " f"tactic={best_tactic}, time={min_time:.3f}ms, fine_grained=OFF (disabled during tuning)" ) # 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._keys_profiled_in_process.add(cache_key) self.stats.tuned_op_profiled_configs[custom_op] += 1 elif local_pairs == 0 and total_pairs > 0: # The PARALLEL deal left this rank no pair to profile; the merge # brings in the winner the other ranks of the group find. self._debug_logger( f"[Autotuner] No (runner, tactic) pair dealt to this rank for custom_op={custom_op}, " f"input_shapes={profile.get_opt_shapes()}.") else: logger.warning_once( f"[Autotuner] No valid runner/tactic was found for custom_op={custom_op}, input_shapes={profile.get_opt_shapes()}. " f"At least one valid (runner, tactic) pair is required. " f"If get_valid_tactics is intended to return empty list, please ensure that this profile is not valid for the custom_op " f"and should not occurs during the inference stage, or fallback tactic is implemented. Otherwise, the the tuning process will crash.", key=(custom_op, "warning_autotuning_no_valid_tactic"), ) return best_runner_id, best_tactic, min_time, has_tuning_failure_occurred def _parallel_jit_warmup(self, custom_op: str, runners: List[TunableRunner], profiles: List[OptimizationProfile], inputs: List[torch.Tensor], tuning_config: TuningConfig, **kwargs) -> None: """Run each not-yet-tuned profile once on a thread pool to drive its JIT. See ``TuningConfig.parallel_jit_warmup``. Purely a warmup: results are discarded, and a failure here is left to the profiling loop, which runs every profile again and handles errors as usual. """ num_threads = int( os.environ.get("TLLM_AUTOTUNER_PARALLEL_JIT_WARMUP", tuning_config.parallel_jit_warmup)) if num_threads < 0: num_threads = _default_parallel_jit_warmup_threads() if num_threads < 2: return pending = [ p for p in profiles if not self.profiling_cache.search_cache( custom_op, runners, p.get_opt_shapes(), tuning_config, apply_map_to_tuning_buckets=False, )[0] ] num_threads = min(num_threads, len(pending)) if num_threads < 2: return # Interleave contiguous blocks of the sweep, so the calls in flight # come from far-apart shapes and mostly select different kernels # rather than several threads compiling the same one. size = -(-len(pending) // num_threads) blocks = [pending[i * size:(i + 1) * size] for i in range(num_threads)] order = [b[j] for j in range(size) for b in blocks if j < len(b)] device = torch.cuda.current_device() # One stream for all workers: the allocator caches their blocks where # the profiling loop below allocates, and GPU time is not the cost here. stream = torch.cuda.current_stream() failures = [] def warm(profile: OptimizationProfile) -> None: torch.cuda.set_device(device) try: with torch.cuda.stream(stream): tensors = self._prepare_input_tensors(profile, inputs) if tuning_config.inputs_pre_hook is not None: tensors = tuning_config.inputs_pre_hook(tensors) for runner in runners: for tactic in runner.get_valid_tactics( tensors, profile, **kwargs): runner(tensors, tactic=tactic, **kwargs) stream.synchronize() except Exception as e: # noqa: BLE001 - the profiling loop reports it failures.append(e) start = time.perf_counter() with concurrent.futures.ThreadPoolExecutor( max_workers=num_threads, thread_name_prefix="autotuner_jit_warmup") as pool: list(pool.map(warm, order)) logger.info(f"[Autotuner] {custom_op}: ran {len(order)} profiles on " f"{num_threads} threads to drive their JIT in " f"{time.perf_counter() - start:.1f}s" + (f"; {len(failures)} failed and are left to profiling " f"({type(failures[0]).__name__}: {failures[0]})" if failures else "")) @staticmethod def _run_profile_runner(runner: TunableRunner, inputs: List[torch.Tensor], tactic: Any, **kwargs) -> None: with nccl_window_tensor_scope(inputs) as scope: try: runner(inputs, tactic=tactic, **kwargs) finally: # Profiling inputs outlive each candidate run; everything newly # allocated by the runner is an internal, discarded result. scope.escape(inputs) def _get_input_sizes(self, inputs: List[torch.Tensor]) -> List[torch.Size]: # Handle None tensors for optional inputs and non-Tensor scalar values sizes = [ input.size() if isinstance(input, torch.Tensor) else torch.Size( (0, )) for input in inputs ] return sizes @contextlib.contextmanager def _shared_profile_graph_pool(self): """Let the profiling captures in this scope share one CUDA graph memory pool. Every profiling capture is reset before the next one starts. With a pool per capture, each reset drops that pool and the next capture maps its memory again, which under expandable segments costs milliseconds per capture. A shared pool keeps the freed blocks cached for the next capture. The pool is dropped when the outermost scope exits, so its memory is not held across forward passes. """ self._profile_graph_pool_depth += 1 try: yield finally: self._profile_graph_pool_depth -= 1 if self._profile_graph_pool_depth == 0: self._profile_graph_pool = None def _profile_graph_pool_handle(self) -> Tuple[int, int]: """Pool handle for one profiling capture: the shared pool inside _shared_profile_graph_pool, otherwise a new pool.""" if self._profile_graph_pool_depth == 0: return torch.cuda.graph_pool_handle() if self._profile_graph_pool is None: self._profile_graph_pool = torch.cuda.MemPool() return self._profile_graph_pool.id def _profile_single_kernel( self, runner: TunableRunner, inputs: List[torch.Tensor], tactic: Any, tuning_config: TuningConfig, use_cuda_graph: bool = False, **kwargs, ) -> float: """Profile a single kernel implementation for performance measurement. Args: runner (TunableRunner): The runner implementation to profile inputs (List[torch.Tensor]): Input tensors for the kernel tactic (Any): Tactic to use for this profiling run Returns: Average execution time in milliseconds Note: The method performs warmup runs, then measures multiple iterations to get an average execution time. Stream synchronization and delays are used to ensure accurate timing. """ input_tensor_batches = self._prepare_input_tensors_with_batches( inputs, tuning_config) if tuning_config.cold_l2_flush_bytes > 0: avg_time = self._profile_cold_l2(runner, input_tensor_batches, tactic, tuning_config, **kwargs) self._debug_logger( f"[Autotuner] Profiled (cold L2) runner={runner}, tactic={tactic}, " f"shapes={self._get_input_sizes(inputs)}: {avg_time:.6f}ms.") return avg_time stream = torch.cuda.current_stream() # If the warm up time is longer than 0.5ms, we will profile the kernel with fewer repeats. profile_fewer_repeat = 2 short_profile_threshold_ms = 1 avg_time = float('inf') def pure_profile(stream: torch.cuda.Stream, repeat: int): graph = torch.cuda.CUDAGraph() @contextlib.contextmanager def graph_pool_lifetime(): if not use_cuda_graph: yield None return graph_pool = self._profile_graph_pool_handle() completed = False try: yield graph_pool completed = True finally: graph.reset() # The NCCL-window owner stays per capture even when the # memory pool is shared: a later capture of the same pool # gets a new owner. if completed: release_nccl_window_graph_owner(graph_pool) else: # Local profiling failures need not occur on every rank. abandon_nccl_window_graph_owner(graph_pool) # Do not capture into a pool a failed capture used. self._profile_graph_pool = None if self._use_global_timer: start_ts = torch.empty(1, dtype=torch.int64, device='cuda') end_ts = torch.empty(1, dtype=torch.int64, device='cuda') def record_start(): record_global_timer(start_ts.data_ptr(), stream) def record_end(): record_global_timer(end_ts.data_ptr(), stream) def elapsed_time(): # GPU %globaltimer counts in ns; convert to ms to match the # units of Torch.cuda.Event.elapsed_time() return (end_ts.item() - start_ts.item()) / 1e6 else: start_evt = torch.cuda.Event(enable_timing=True) end_evt = torch.cuda.Event(enable_timing=True) def record_start(): start_evt.record() def record_end(): end_evt.record() def elapsed_time(): return start_evt.elapsed_time(end_evt) with graph_pool_lifetime() as graph_pool, torch.cuda.stream(stream): if use_cuda_graph: with nccl_window_graph_capture(graph, graph_pool): for r in range(repeat): self._run_profile_runner( runner, input_tensor_batches[r % len(input_tensor_batches)], tactic, **kwargs, ) stream.synchronize() if tuning_config.distributed_tuning_strategy == DistributedTuningStrategy.MERGE: # Currently only AllReduce will use this strategy, and only MPI parallel will enable tuning. self._dist.tp_barrier() # Delay the profiled kernel launch to eliminate affects of host time overhead in profiling. if use_cuda_graph: delay_kernel(self._CUDA_GRAPH_DELAY_MICRO_SECS, stream) else: delay_kernel(self.stream_delay_micro_secs, stream) record_start() if use_cuda_graph: graph.replay() else: for r in range(repeat): self._run_profile_runner( runner, input_tensor_batches[r % len(input_tensor_batches)], tactic, **kwargs, ) record_end() stream.synchronize() return elapsed_time() / repeat # warm up, no timing for _ in range(self.warmup): self._run_profile_runner(runner, input_tensor_batches[-1], tactic, **kwargs) fewer_repeat_avg_time = pure_profile(stream, profile_fewer_repeat) disable_short_profile = os.environ.get( "TLLM_AUTOTUNER_DISABLE_SHORT_PROFILE", "0") == "1" # Disable this feature for merged tuning strategy to avoid potential hang due to asymmetric tuning. if fewer_repeat_avg_time > short_profile_threshold_ms and not disable_short_profile \ and tuning_config.distributed_tuning_strategy != DistributedTuningStrategy.MERGE: # directly use the few repeat estimated time to avoid redundant profiling avg_time = fewer_repeat_avg_time else: # profile the kernel with the full repeat to get precise time avg_time = pure_profile(stream, self.repeat) shapes = self._get_input_sizes(inputs) self._debug_logger( f"[Autotuner] Profiled runner={runner}, tactic={tactic}, shapes={shapes}: {avg_time:.6f}ms." ) return avg_time # Flush buffers of cold-L2 profiling, by (device, bytes); released when the ``autotune()`` that # turned tuning on exits. L2_FLUSH_BUFFERS: Dict[Tuple[int, int], torch.Tensor] = {} def _profile_cold_l2(self, runner: TunableRunner, input_tensor_batches: List[List[torch.Tensor]], tactic: Any, tuning_config: TuningConfig, **kwargs) -> float: """Median per-repeat time (ms) of ``runner`` with L2 flushed before every repeat. One CUDA graph holds ``repeat`` x (read the flush buffer, stamp, runner, stamp); a repeat's time is its stamp difference, so neither the flush nor host launches are timed. """ key = (torch.cuda.current_device(), tuning_config.cold_l2_flush_bytes) flush = self.L2_FLUSH_BUFFERS.get(key) if flush is None: flush = torch.ones(tuning_config.cold_l2_flush_bytes // 2, dtype=torch.bfloat16, device="cuda") self.L2_FLUSH_BUFFERS[key] = flush for _ in range(self.warmup): runner(input_tensor_batches[-1], tactic=tactic, **kwargs) repeat = max(self.repeat, 3) stamps = torch.zeros(2 * repeat, dtype=torch.int64, device="cuda") base = stamps.data_ptr() graph = torch.cuda.CUDAGraph() graph_pool = torch.cuda.graph_pool_handle() torch.cuda.synchronize() completed = False try: # Like every capture here: NCCL-window ownership, and no automatic GC until it ends. with nccl_window_graph_capture(graph, graph_pool): capture_stream = torch.cuda.current_stream() for r in range(repeat): torch.amax(flush) record_global_timer(base + 16 * r, capture_stream) runner(input_tensor_batches[r % len(input_tensor_batches)], tactic=tactic, **kwargs) record_global_timer(base + 16 * r + 8, capture_stream) for _ in range(2): graph.replay() torch.cuda.synchronize() completed = True finally: graph.reset() if completed: release_nccl_window_graph_owner(graph_pool) else: abandon_nccl_window_graph_owner(graph_pool) times = (stamps[1::2] - stamps[0::2]).double() / 1e6 return float(times.median().item()) def _optimization_profiles( self, tuning_config: TuningConfig, inputs: List[torch.Tensor]) -> List[OptimizationProfile]: """Generate optimization profiles for autotuning. Args: tuning_config (TuningConfig): Tuning configuration inputs (List[torch.Tensor]): List of input tensors Returns: List of OptimizationProfile objects representing different configurations Note: This method performs a cartesian product of all possible dimension combinations specified in dynamic_tensor_specs. """ # every dimension created from the concrete input tensor shape # generate some dynamic dimension description based on the dynamic_tensors # Zero handles the case where a TRTLLM op has optional or scalar inputs. base_profile = OptimizationProfile( [[StaticDim(x) for x in t.size()] if isinstance(t, torch.Tensor) else [StaticDim(0)] for t in inputs]) generated_profiles: List[OptimizationProfile] = [] dynamic_dims = [] for spec in tuning_config.dynamic_tensor_specs: assert callable(spec.gen_tuning_buckets) or isinstance(spec.gen_tuning_buckets, (list, tuple)), \ "The given dynamic dimension must provide a opt value generation function or a list of opt values" if not _spec_in_bounds(spec, base_profile.shapes): continue if self.skip_dynamic_tuning_buckets: if spec.map_to_tuning_buckets is not None: # Still include the bucketed value of the actual shape so the # cache key used during profiling (raw) aligns with the key # used during inference (bucketed via map_to_tuning_buckets). actual_val = base_profile.shapes[spec.input_idx][ spec.dim_idx].val mapped_val = spec.map_to_tuning_buckets(actual_val) if mapped_val < 0: # Lookup cannot use a measured winner for this input. # Leave it as a cache miss so choose_one uses fallback. return [] opt_shapes = (mapped_val, ) else: opt_shapes = () elif callable(spec.gen_tuning_buckets): if tuning_config.tune_max_num_tokens is None: # Use the current input size as the opt value opt_shapes = spec.gen_tuning_buckets( base_profile.shapes[spec.input_idx][spec.dim_idx].val) else: # Use the tune_max_num_tokens as the opt value opt_shapes = spec.gen_tuning_buckets( tuning_config.tune_max_num_tokens) else: # Default values is an empty tuple, means that user does not want to tune this dimension. opt_shapes = spec.gen_tuning_buckets # Add the current input value as one of the opt values opt_shapes = set(opt_shapes) if tuning_config.tune_max_num_tokens is not None: opt_shapes.add( min( tuning_config.tune_max_num_tokens, base_profile.shapes[spec.input_idx][spec.dim_idx].val, )) else: opt_shapes.add( base_profile.shapes[spec.input_idx][spec.dim_idx].val) opt_shapes = sorted(list(opt_shapes)) opt_shapes_max = tuple(opt_shapes[1:]) + (float('inf'), ) opt_shapes_max = { v1: v2 for v1, v2 in zip(opt_shapes, opt_shapes_max) } dynamic_dims.append( (spec.input_idx, spec.dim_idx, opt_shapes_max, opt_shapes)) # grid search, do cartesian product for all the dynamic axis dim_grids = itertools.product(*[d[-1] for d in dynamic_dims]) for opt_point in dim_grids: p = copy.deepcopy(base_profile) for pos, (input_idx, dim_idx, opt_shapes_max, opt_shapes) in enumerate(dynamic_dims): opt_value = opt_point[pos] #TODO: fix me, how to set the min and max? min_value = opt_value max_value = opt_shapes_max[opt_value] p.shapes[input_idx][dim_idx] = DynamicDim( min_value, opt_value, max_value) # Adjust the profile to satisfy the constraints for spec in tuning_config.constraint_specs: if not _spec_in_bounds(spec, p.shapes): continue if p.shapes[spec.input_idx] == [StaticDim(0)]: continue min_value = opt_value = max_value = spec.infer_shape( p.get_opt_shapes()) p.shapes[spec.input_idx][spec.dim_idx] = DynamicDim( min_value, opt_value, max_value) generated_profiles.append(p) self._debug_logger(f"[Autotuner] Generated profile: {p}") return generated_profiles @classmethod @lru_cache(maxsize=None) def _find_nearest_profile( cls, shapes: Tuple[torch.Size], dynamic_tensor_specs: Tuple[DynamicTensorSpec, ...], constraint_specs: Tuple[ConstraintSpec, ...], tune_max_num_tokens: int = None, apply_map_to_tuning_buckets: bool = True, ) -> Tuple: """Find the nearest optimization profile for given inputs User can define their own nearest profile generation method to reduce the host overhead. Args: shapes: Tuple of input tensor shapes tuning_config: Tuning configuration 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. Return: Tuple: A tuple containing: - attributes: Tuple of runner attributes, sorted. - profile: Tuple of input tensor shapes """ base_profile = list(list(shape) for shape in shapes) for spec in dynamic_tensor_specs: # Bounds check: skip specs that reference inputs or dimensions not present in the # current shapes tuple. This can happen on hardware (e.g. SM121 / DGX Spark) where # ops produce fewer or differently-shaped tensors than the specs were authored for. if not _spec_in_bounds(spec, base_profile): continue # During runtime: apply map_to_tuning_buckets to map input to bucket # During tuning: no mapper, use raw bucket value if apply_map_to_tuning_buckets: base_profile[spec.input_idx][ spec.dim_idx] = spec.map_to_tuning_buckets( base_profile[spec.input_idx][spec.dim_idx]) if tune_max_num_tokens is not None: base_profile[spec.input_idx][spec.dim_idx] = min( base_profile[spec.input_idx][spec.dim_idx], tune_max_num_tokens) # associated dimensions dependent on other free dynamic dimensions, so assign -1 in the profile for spec in constraint_specs: # Bounds check: same defensive guard as above for constraint specs. if not _spec_in_bounds(spec, base_profile): continue if base_profile[spec.input_idx] == [0]: continue base_profile[spec.input_idx][spec.dim_idx] = -1 return tuple(tuple(shape) for shape in base_profile) def _create_tensor_like(self, origin_tensor: torch.Tensor, dims: List[Dim]) -> torch.Tensor: """Create a new tensor matching the properties of the original tensor. Args: origin_tensor (torch.Tensor): Template tensor to match dims (List[Dim]): List of dimensions for the new tensor Returns: New tensor with specified dimensions and matching properties Note: Creates a zero tensor with the same dtype and device as the original, but with dimensions specified by the dims parameter. """ dtype = origin_tensor.dtype device = origin_tensor.device shapes = [] for i, d in enumerate(dims): if isinstance(d, StaticDim): assert d.val == origin_tensor.shape[i] shapes.append(d.val) else: # TODO: how to make sure the created Tensor has the min/max info assert isinstance(d, DynamicDim) shapes.append(d.opt) if len(dims) == 2 and isinstance(dims[0], DynamicDim) and isinstance( dims[1], StaticDim) and (dtype == torch.int32 or dtype == torch.int64): # We should be carefully about int values, since they might be index like topk_index. # We want to keep them legal, so just repeating input tensor. repeat_times = (shapes[0] + origin_tensor.shape[0] - 1) // origin_tensor.shape[0] dup_tensor = origin_tensor.repeat(repeat_times, 1)[:shapes[0]] return dup_tensor # TODO: FIXME, sometimes the content of the tensor can affect the performance, like MOE # One solution is to manituplate the tensor content to make it more like the real data # during the tuning process. This can by controlled in the preparation phase by the runner. # It must not use all zero tensors. Otherwise the timing results become unreliable. if dtype == torch.float4_e2m1fn_x2: return (torch.rand(shapes, device=device) * 10 - 5).to( torch.uint8).view(dtype) return (torch.rand(shapes, device=device) * 10 - 5).to(dtype) def _prepare_input_tensors( self, profile: OptimizationProfile, inputs: List[torch.Tensor]) -> List[torch.Tensor]: tensors = [] for i, p in enumerate(profile.shapes): if any(isinstance(d, DynamicDim) for d in p): tensor = self._create_tensor_like(inputs[i], p) else: tensor = inputs[i] tensors.append(tensor) return tensors def _prepare_input_tensors_with_batches( self, inputs: List[torch.Tensor], tuning_config: TuningConfig, ) -> List[List[torch.Tensor]]: if not tuning_config.use_cold_l2_cache: return [inputs] one_buffer_bytes = sum( input.numel() * input.element_size() if isinstance(input, torch.Tensor) else 0 for input in inputs) if one_buffer_bytes <= 0: self._debug_logger( "[Autotuner] No tensor inputs or zero-sized tensors; falling back to single-batch profiling." ) return [inputs] num_buffers = self._get_l2_cache_size_in_bytes( ) * 3 // one_buffer_bytes + 1 num_buffers = min(num_buffers, self.repeat + 1) inputs_list = [inputs] for _ in range(num_buffers - 1): inputs_list.append( list(t.clone() if isinstance(t, torch.Tensor) else t for t in inputs)) self._debug_logger( f"[Autotuner] use_cold_l2_cache={tuning_config.use_cold_l2_cache}, use {num_buffers} different tensors for profiling" ) return inputs_list def clear_cache(self) -> None: """Clear the profiling cache.""" self.profiling_cache.clear() self._keys_profiled_in_process.clear() if hasattr(torch.ops.trtllm, "clear_allreduce_tactic_cache"): torch.ops.trtllm.clear_allreduce_tactic_cache() def reset_statistics(self) -> None: """Reset all statistics counters.""" self.stats = AutoTunerStatistics() def print_profiling_cache(self): self._debug_logger(f"[Autotuner] The profiling_cache entries:") self._debug_logger( f"[Autotuner] Cache contents: (custom_op, runner, hash(attributes), shape_profiles) -> (runner_id, tactic, shape_profile(ignored))" ) for key, value in self.profiling_cache.cache.items(): runner_id, tactic, min_time = value self._debug_logger( f"[Autotuner] {key}: (runner_id={runner_id}, tactic={tactic}, min_time={min_time})" ) self.print_statistics() def print_statistics(self): self._debug_logger(f"[Autotuner] The statistics:") for line in self.stats.__str__().split("\n"): self._debug_logger(line) @contextlib.contextmanager def capture(self): """Context manager for capturing execution contexts for testing. Returns a TacticsCapture object that can be iterated to get all valid (runner, tactic) combinations. Example: >>> # Single context case >>> with AutoTuner.get().capture() as tactics_capture: ... y = custom_op.forward(x) >>> >>> for runner, tactic in tactics_capture: ... with AutoTuner.get().replay(runner, tactic): ... y = custom_op.forward(x) >>> # Multiple contexts case >>> with AutoTuner.get().capture() as tactics_capture: ... y = custom_op1.forward(x) ... z = custom_op2.forward(y) >>> >>> for config in tactics_capture: ... with AutoTuner.get().replay(config): ... y = custom_op1.forward(x) ... z = custom_op2.forward(y) """ tactics_capture = self.TacticsCapture(self) self._active_capture = tactics_capture try: yield tactics_capture finally: self._active_capture = None self._last_capture = tactics_capture @contextlib.contextmanager def replay(self, *config: Tuple[Tuple[TunableRunner, int], ...]): """Context manager for replaying with specific runner/tactic configuration. Args: config: - A tuple of (runner, tactic) pairs. The tuple size matches the number of captured choose_one() contexts. """ # Parse config argument if len(config) == 1: if isinstance(config[0], tuple): # Multiple contexts: replay(((r0,t0), (r1,t1), ...)) runner_tactic_pairs = list(config[0]) else: # Also handle single context passed as replay((runner, tactic)) runner_tactic_pairs = [config[0]] else: raise ValueError( f"Invalid config for replay: {config}\n" "Expected replay(((runner, tactic), (runner, tactic), ...))") # Find the TacticsCapture to use tactics_capture = self._active_capture or self._last_capture if tactics_capture is None: raise RuntimeError( "No TacticsCapture available for replay. " "Make sure you've called capture() before replay().") # Temporarily set as active capture during replay prev_active = self._active_capture self._active_capture = tactics_capture runner_tactic_list = [] for ctx_idx, (runner, tactic) in enumerate(runner_tactic_pairs): runners = tactics_capture._captured_contexts[ctx_idx]['runners'] runner_idx = runners.index(runner) runner_tactic_list.append((runner_idx, tactic)) self._debug_logger( f"[Autotuner][replay]: Testing configuration: {runner_tactic_list}") # Replay the contexts with given (runner, tactic) pairs tactics_capture._replay_runner_tactic_list = runner_tactic_list tactics_capture._replay_context_idx = 0 try: yield finally: tactics_capture._replay_runner_tactic_list = None tactics_capture._replay_context_idx = 0 # Restore previous active capture state self._active_capture = prev_active def _get_l2_cache_size_in_bytes(self, device_id: int = 0) -> int: device = self._checkCudaErrors(driver.cuDeviceGet(device_id)) return self._checkCudaErrors( driver.cuDeviceGetAttribute( driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, device, )) def _checkCudaErrors(self, result) -> Any: status = result[0] if status != driver.CUresult.CUDA_SUCCESS: code = getattr(status, "value", status) raise RuntimeError( f"CUDA error code={code}({self._cudaGetErrorEnum(status)})") # CUDA APIs always return the status as the first element of the result tuple if len(result) == 1: return None elif len(result) == 2: return result[1] else: return result[1:] def _cudaGetErrorEnum(self, error) -> str: from cuda.bindings import nvrtc if isinstance(error, driver.CUresult): err, name = driver.cuGetErrorName(error) return name if err == driver.CUresult.CUDA_SUCCESS else "" elif isinstance(error, nvrtc.nvrtcResult): return nvrtc.nvrtcGetErrorString(error)[1] else: raise RuntimeError("Unknown error type: {}".format(error)) def setup_distributed_state(self, mapping: Mapping, dist: Optional[Distributed] = ...): """Setup distributed communication state for autotuning.""" self.mapping = mapping # Create dist only when dist is not provided. # Use the provided dist even if it is None. This is useful for testing. self._dist = Distributed.get(mapping) if dist is ... else dist self._debug_logger( f"[AutoTuner] Whether using distributed tuning: {self._is_distributed()}" ) def _tuning_group(self) -> Tuple[int, int]: """Return ``(size, index)`` of this rank's tuning group. The group is the TP group. Helix CP ranks run the same SPMD forward on the same token batch, so Helix adds the CP ranks too. Otherwise a Helix generation worker with ``tp_size == 1`` would profile every tactic on every CP rank. The index matches the TP-major, CP-minor order of ``Distributed.tp_cp_allgather``, which merges the results. """ if self.mapping is None: return 1, 0 size = self.mapping.tp_size index = self.mapping.tp_rank if self.mapping.has_cp_helix(): size *= self.mapping.cp_size index = index * self.mapping.cp_size + self.mapping.cp_rank return size, index def _is_distributed(self) -> bool: """Check if we're in a distributed environment.""" return self._dist is not None and self._tuning_group()[0] > 1 def _needs_rank_agreement(self, strategy: DistributedTuningStrategy) -> bool: """Whether ranks must agree on cache hits under ``strategy``. Never for a choose_one() reached from a runner this rank is profiling: under BROADCAST rank 0 profiles alone, so a collective there never completes. """ return (strategy != DistributedTuningStrategy.INDEPENDENT and self._is_distributed() and not self._profiling_depth) def _hit_on_all_ranks(self, is_cache_hit: bool) -> bool: """Whether ``is_cache_hit`` holds on every rank (host all-gather).""" return all(self._dist.tp_cp_allgather(obj=bool(is_cache_hit))) def _profile_hits_on_all_ranks(self, profiles: List[OptimizationProfile], hits: List[bool]) -> List[bool]: """Per profile, whether every rank that builds it has it cached (one host all-gather). Ranks build their profiles from their own input shapes (attention DP), so the lists may differ. """ keys = [p.get_opt_shapes() for p in profiles] missed = set() for rank_keys, rank_hits in self._dist.tp_cp_allgather( obj=(keys, [bool(hit) for hit in hits])): missed.update(key for key, hit in zip(rank_keys, rank_hits) if not hit) return [key not in missed for key in keys] def _parallel_deal_start(self, custom_op: str, profile: OptimizationProfile, strategy: DistributedTuningStrategy) -> int: """Where a PARALLEL deal of ``profile``'s (runner, tactic) pairs starts. Derived from the op and the shapes with a stable hash (not ``hash``, which differs between processes), so every rank deals the same way. """ if strategy != DistributedTuningStrategy.PARALLEL or not self._is_distributed( ): return 0 key = repr((custom_op, profile.get_opt_shapes())).encode() return zlib.crc32(key) % self._tuning_group()[0] def _maybe_parallelize_tactics(self, all_valid_tactics: List[Any], strategy: DistributedTuningStrategy, offset: int = 0) -> List[Any]: """Split tactics across the tuning group if strategy is PARALLEL. ``offset`` is where this runner's pairs start in the profile's deal: the deal's start plus the pairs of the runners before this one. """ if strategy == DistributedTuningStrategy.PARALLEL and self._is_distributed( ): # Each rank of the tuning group only tunes its share of tactics; # _merge_cache_data then keeps the fastest across the group. group_size, group_index = self._tuning_group() return [ tactic for idx, tactic in enumerate(all_valid_tactics) if (offset + idx) % group_size == group_index ] else: return all_valid_tactics def _maybe_sync_cache_data(self, strategy: DistributedTuningStrategy, custom_op: str): """Synchronize cache data across all ranks.""" if not self._is_distributed(): return if strategy == DistributedTuningStrategy.BROADCAST: self._broadcast_cache_data(custom_op) elif strategy == DistributedTuningStrategy.INDEPENDENT: return elif strategy == DistributedTuningStrategy.MERGE: self._merge_cache_data(custom_op) elif strategy == DistributedTuningStrategy.PARALLEL: self._merge_cache_data(custom_op) else: logger.error( f"[AutoTuner] Unknown distributed tuning strategy: {strategy}, falling back to independent" ) return def _merge_cache_data(self, custom_op: str): cache_data = self.profiling_cache.get_specific_custom_op(custom_op) self.profiling_cache.merge_cache_data( _fastest_entries(self._dist.tp_cp_allgather(obj=cache_data))) def post_tune_merge_tactics(self, custom_ops: Optional[Set[str]] = None, majority: bool = False) -> int: """After tuning, keep per cache key (of ``custom_ops`` when given) the ranks' fastest tactic, or with ``majority`` the one most ranks chose. Collective — all ranks must call it. Returns how many of this rank's tactics changed.""" if not self._is_distributed(): return 0 mine = { key: value for key, value in self.profiling_cache.cache.items() if custom_ops is None or key[0] in custom_ops } per_rank = self._dist.tp_cp_allgather(obj=mine) merged = (_majority_entries(per_rank) if majority else _fastest_entries(per_rank)) changed = sum(1 for key, value in merged.items() if key not in mine or mine[key][1] != value[1]) self.profiling_cache.merge_cache_data(merged) return changed def _broadcast_cache_data( self, custom_op: str, ) -> None: """Broadcast tactics from root rank to all other ranks.""" cache_data = self.profiling_cache.get_specific_custom_op(custom_op) root = 0 cache_data = self._dist.tp_cp_broadcast(obj=cache_data, root=root) self.profiling_cache.merge_cache_data(cache_data) def _should_current_rank_tune(self, strategy: DistributedTuningStrategy) -> bool: """Determine if this rank should perform tuning based on strategy.""" if not self._is_distributed(): return True if strategy == DistributedTuningStrategy.BROADCAST: # Only the tuning group's root (the broadcast root) tunes return self._tuning_group()[1] == 0 elif strategy in { DistributedTuningStrategy.INDEPENDENT, DistributedTuningStrategy.MERGE, DistributedTuningStrategy.PARALLEL, }: # All ranks tune independently return True else: logger.error( f"[AutoTuner] Unknown distributed tuning strategy: {strategy}, falling back to independent" ) return True def cache_pp_recv(self): if self.mapping.has_pp() and not self.mapping.is_first_pp_rank( ) and not self._has_received_cache: self._debug_logger( f"[AutoTuner] Receiving cache data from previous pp rank {self.mapping.prev_pp_rank()}" ) profiling_cache = self._dist.recv_object( src=self.mapping.prev_pp_rank(), tag=PP_COMM_TAG_AUTOTUNING, ) # Guarantee that only receive cache once during a single warm-up run # Notice that this flag should be reset after each warm-up run because isend is always called self._has_received_cache = True self.profiling_cache.merge_cache_data(profiling_cache) def cache_pp_send(self): if self.mapping.has_pp() and not self.mapping.is_last_pp_rank(): self._debug_logger( f"[AutoTuner] Sending cache data to next pp rank {self.mapping.next_pp_rank()}" ) self._dist.isend_object( self.profiling_cache.cache, dest=self.mapping.next_pp_rank(), tag=PP_COMM_TAG_AUTOTUNING, ).wait() def clean_pp_flag(self): self._has_received_cache = False