-
Notifications
You must be signed in to change notification settings - Fork 372
feat: improve engine caching and fix bugs #3932
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zewenli98
wants to merge
3
commits into
main
Choose a base branch
from
improve_engine_caching
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,19 +4,24 @@ | |
| import logging | ||
| from typing import Any, List, NamedTuple, Optional, Sequence | ||
|
|
||
| import tensorrt as trt | ||
| import torch | ||
| from torch_tensorrt._enums import dtype | ||
| from torch_tensorrt._features import ENABLED_FEATURES | ||
| from torch_tensorrt._Input import Input | ||
| from torch_tensorrt.dynamo._engine_cache import BaseEngineCache | ||
| from torch_tensorrt.dynamo._settings import CompilationSettings | ||
| from torch_tensorrt.dynamo.conversion._TRTInterpreter import TRTInterpreter | ||
| from torch_tensorrt.dynamo._settings import CompilationSettings, settings_are_compatible | ||
| from torch_tensorrt.dynamo.conversion._TRTInterpreter import ( | ||
| TRTInterpreter, | ||
| TRTInterpreterResult, | ||
| ) | ||
| from torch_tensorrt.dynamo.runtime import PythonTorchTensorRTModule, TorchTensorRTModule | ||
| from torch_tensorrt.dynamo.utils import ( | ||
| get_cpu_memory_usage, | ||
| get_output_dtypes, | ||
| release_host_and_device_memory, | ||
| ) | ||
| from torch_tensorrt.logging import TRT_LOGGER | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
@@ -63,6 +68,143 @@ def interpret_module_to_result( | |
| SerializedInterpreterResult | ||
| """ | ||
|
|
||
| def _insert_engine_to_cache( | ||
| hash_val: str, interpreter_result: TRTInterpreterResult | ||
| ) -> bool: | ||
| if not ENABLED_FEATURES.refit: | ||
| logger.info("Refit feature is not available, so the engine is not cached") | ||
| return False | ||
|
|
||
| # Cache the weight-stripped engine regardless of the `strip_engine_weights` setting | ||
| if engine_cache.check(hash_val) is not None: # type: ignore[union-attr] | ||
| logger.info(f"The engine already exists in cache for hash: {hash_val}") | ||
| return False | ||
|
|
||
| if not settings.strip_engine_weights: | ||
| # set EXCLUDE_WEIGHTS flag to strip weights | ||
| serialization_config = ( | ||
| interpreter_result.engine.create_serialization_config() | ||
| ) | ||
| serialization_config.set_flag(trt.SerializationFlag.EXCLUDE_WEIGHTS) | ||
| weight_stripped_serialized_engine = ( | ||
| interpreter_result.engine.serialize_with_config(serialization_config) | ||
| ) | ||
| else: | ||
| weight_stripped_serialized_engine = interpreter_result.engine.serialize() | ||
|
|
||
| # Insert weight-stripped engine to cache | ||
| engine_cache.insert( # type: ignore[union-attr] | ||
| hash_val, | ||
| ( | ||
| weight_stripped_serialized_engine, | ||
| interpreter_result.input_names, | ||
| interpreter_result.output_names, | ||
| inputs, | ||
| settings, | ||
| interpreter_result.weight_name_map, | ||
| interpreter_result.requires_output_allocator, | ||
| ), | ||
| ) | ||
| logger.info(f"Engine was successfully inserted into cache for hash: {hash_val}") | ||
| return True | ||
|
|
||
| def _pull_cached_engine(hash_val: str) -> Optional[SerializedInterpreterResult]: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
| if not ENABLED_FEATURES.refit: | ||
| logger.info( | ||
| "Refit feature is not available, so the engine is not loaded from cache" | ||
| ) | ||
| return None | ||
|
|
||
| # query the cached TRT engine | ||
| cached_data = engine_cache.check(hash_val) # type: ignore[union-attr] | ||
| if cached_data is not None: # hit the cache | ||
| ( | ||
| serialized_engine, # weight-stripped engine | ||
| input_names, | ||
| output_names, | ||
| cached_engine_inputs, | ||
| cached_engine_compilation_settings, | ||
| weight_name_map, | ||
| requires_output_allocator, | ||
| ) = cached_data | ||
|
|
||
| setting_compatiblity, incompattible_settings = settings_are_compatible( | ||
| settings, cached_engine_compilation_settings | ||
| ) | ||
| assert ( | ||
| setting_compatiblity | ||
| ), f"Attempted to refit a cached engine with incompatible settings: {incompattible_settings}, (old_settings: {cached_engine_compilation_settings}, new_settings: {settings})" | ||
|
|
||
| for i, e in enumerate( | ||
| [ | ||
| Input.equivalent_spec(c, i) | ||
| for c, i in zip(cached_engine_inputs, inputs) | ||
| ] | ||
| ): | ||
| assert ( | ||
| e | ||
| ), f"Attempted to refit a cached engine built for a different input size (input: {i}, cached size: {cached_engine_inputs[i]}, new size: {inputs[i]}" | ||
|
|
||
| logger.info( | ||
| "Found the cached engine that corresponds to this graph. It is directly loaded." | ||
| ) | ||
|
|
||
| # refit the cached engine with the new graph module | ||
| if not settings.strip_engine_weights: | ||
| runtime = trt.Runtime(TRT_LOGGER) | ||
| engine = runtime.deserialize_cuda_engine( | ||
| serialized_engine | ||
| ) # weight-stripped engine | ||
|
|
||
| from torch_tensorrt.dynamo._refit import ( | ||
| _refit_single_trt_engine_with_gm, | ||
| ) | ||
|
|
||
| # weight-stripped engine --in place--> weight-included engine | ||
| _refit_single_trt_engine_with_gm( | ||
| new_gm=module, | ||
| old_engine=engine, | ||
| input_list=inputs, | ||
| settings=settings, | ||
| weight_name_map=weight_name_map, | ||
| ) | ||
|
|
||
| # EXCLUDE_WEIGHTS flag must be cleared and INCLUDE_REFIT flag must be set | ||
| serialization_config = engine.create_serialization_config() | ||
| serialization_config.clear_flag(trt.SerializationFlag.EXCLUDE_WEIGHTS) | ||
| serialization_config.set_flag(trt.SerializationFlag.INCLUDE_REFIT) | ||
| serialized_engine = engine.serialize_with_config(serialization_config) | ||
| # Start from here, the engine is weight-included and refittable | ||
|
|
||
| with io.BytesIO() as engine_bytes: | ||
| engine_bytes.write(serialized_engine) | ||
| serialized_engine = engine_bytes.getvalue() | ||
|
|
||
| return SerializedInterpreterResult( | ||
| serialized_engine=serialized_engine, | ||
| input_names=input_names, | ||
| output_names=output_names, | ||
| weight_name_map=weight_name_map, | ||
| requires_output_allocator=requires_output_allocator, | ||
| ) | ||
| return None | ||
|
|
||
| # engine_cache could be None if: | ||
| # 1) engine_cache is not passed in when calling this function like convert_exported_program_to_serialized_trt_engine etc., or | ||
| # 2) both cache_built_engines and reuse_cached_engines are False | ||
| if ( | ||
| ENABLED_FEATURES.refit | ||
| and engine_cache is not None | ||
| and not settings.immutable_weights | ||
| ): | ||
| if settings.cache_built_engines or settings.reuse_cached_engines: | ||
| hash_val = engine_cache.get_hash(module, inputs, settings) | ||
|
|
||
| if settings.reuse_cached_engines: | ||
| serialized_interpreter_result = _pull_cached_engine(hash_val) | ||
| if serialized_interpreter_result is not None: # hit the cache | ||
| return serialized_interpreter_result | ||
|
|
||
| output_dtypes = infer_module_output_dtypes( | ||
| module, truncate_double=settings.truncate_double | ||
| ) | ||
|
|
@@ -86,6 +228,15 @@ def interpret_module_to_result( | |
| f"CPU memory usage after clearing frozen parameters and building memory in conversion: {get_cpu_memory_usage()} MB" | ||
| ) | ||
|
|
||
| # Engine caching only for refittable engines | ||
| if ( | ||
| ENABLED_FEATURES.refit | ||
| and not settings.immutable_weights | ||
| and settings.cache_built_engines | ||
| and engine_cache is not None | ||
| ): | ||
| _ = _insert_engine_to_cache(hash_val, interpreter_result) | ||
|
|
||
| serialized_engine = interpreter_result.engine.serialize() | ||
| with io.BytesIO() as engine_bytes: | ||
| engine_bytes.write(serialized_engine) | ||
|
|
@@ -94,26 +245,6 @@ def interpret_module_to_result( | |
| f"CPU memory usage after serializing engine: {get_cpu_memory_usage()} MB" | ||
| ) | ||
|
|
||
| # Engine caching only for refittable engines | ||
| if ( | ||
| not settings.immutable_weights | ||
| and settings.cache_built_engines | ||
| and engine_cache is not None | ||
| ): | ||
| hash_val = engine_cache.get_hash(module, inputs, settings) | ||
| engine_cache.insert( | ||
| hash_val, | ||
| ( | ||
| serialized_engine, | ||
| interpreter_result.input_names, | ||
| interpreter_result.output_names, | ||
| inputs, | ||
| settings, | ||
| interpreter_result.weight_name_map, | ||
| interpreter_result.requires_output_allocator, | ||
| ), | ||
| ) | ||
|
|
||
| serialized_interpreter_result = SerializedInterpreterResult( | ||
| serialized_engine=serialized_engine, | ||
| input_names=interpreter_result.input_names, | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, I like this
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a reason that the function needs to be in the interpret functions scope?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not a specific reason, but I just don't know when the engine_cache will be used other than in the function
interpret_module_to_result(). To make it safe and self-contained, I picked the smallest scope. Is there any other cases that might use engine_cache?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well it will get redefined each time interpret is called if its in scope, not sure its necessary unless there was some reason like it uses context from interpret module