- 
                Notifications
    You must be signed in to change notification settings 
- Fork 6.5k
[core] parallel loading of shards #12028
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
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            23 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      af72ece
              
                checking.
              
              
                sayakpaul d4e2976
              
                checking
              
              
                sayakpaul c9b680d
              
                checking
              
              
                sayakpaul ab84d5a
              
                up
              
              
                sayakpaul 536df5a
              
                up
              
              
                sayakpaul 04cd5cc
              
                up
              
              
                sayakpaul cb0b3ed
              
                up
              
              
                sayakpaul 2fdc091
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 6d15594
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul d34f426
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 35e859b
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 2cc83b8
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 9844c10
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 73fb972
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 04bff1c
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul cd13977
              
                Apply suggestions from code review
              
              
                sayakpaul 8968e2f
              
                up
              
              
                sayakpaul dca6388
              
                up
              
              
                sayakpaul e276f08
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul ad2dd62
              
                fix
              
              
                sayakpaul 36c86d2
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul ae2561b
              
                review feedback.
              
              
                sayakpaul f0eec0d
              
                Merge branch 'main' into parallel-shards-loading
              
              
                sayakpaul 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
    
  
  
    
              
  
    
      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 | 
|---|---|---|
|  | @@ -14,12 +14,14 @@ | |
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|  | ||
| import functools | ||
| import importlib | ||
| import inspect | ||
| import math | ||
| import os | ||
| from array import array | ||
| from collections import OrderedDict, defaultdict | ||
| from concurrent.futures import ThreadPoolExecutor, as_completed | ||
| from pathlib import Path | ||
| from typing import Dict, List, Optional, Union | ||
| from zipfile import is_zipfile | ||
|  | @@ -31,6 +33,7 @@ | |
|  | ||
| from ..quantizers import DiffusersQuantizer | ||
| from ..utils import ( | ||
| DEFAULT_HF_PARALLEL_LOADING_WORKERS, | ||
| GGUF_FILE_EXTENSION, | ||
| SAFE_WEIGHTS_INDEX_NAME, | ||
| SAFETENSORS_FILE_EXTENSION, | ||
|  | @@ -310,6 +313,161 @@ def load_model_dict_into_meta( | |
| return offload_index, state_dict_index | ||
|  | ||
|  | ||
| def check_support_param_buffer_assignment(model_to_load, state_dict, start_prefix=""): | ||
| """ | ||
| Checks if `model_to_load` supports param buffer assignment (such as when loading in empty weights) by first | ||
| checking if the model explicitly disables it, then by ensuring that the state dict keys are a subset of the model's | ||
| parameters. | ||
|  | ||
| """ | ||
| if model_to_load.device.type == "meta": | ||
| return False | ||
|  | ||
| if len([key for key in state_dict if key.startswith(start_prefix)]) == 0: | ||
| return False | ||
|  | ||
| # Some models explicitly do not support param buffer assignment | ||
| if not getattr(model_to_load, "_supports_param_buffer_assignment", True): | ||
| logger.debug( | ||
| f"{model_to_load.__class__.__name__} does not support param buffer assignment, loading will be slower" | ||
| ) | ||
| return False | ||
|  | ||
| # If the model does, the incoming `state_dict` and the `model_to_load` must be the same dtype | ||
| first_key = next(iter(model_to_load.state_dict().keys())) | ||
| if start_prefix + first_key in state_dict: | ||
| return state_dict[start_prefix + first_key].dtype == model_to_load.state_dict()[first_key].dtype | ||
|  | ||
| return False | ||
|  | ||
|  | ||
| def _load_shard_file( | ||
| shard_file, | ||
| model, | ||
| model_state_dict, | ||
| device_map=None, | ||
| dtype=None, | ||
| hf_quantizer=None, | ||
| keep_in_fp32_modules=None, | ||
| dduf_entries=None, | ||
| loaded_keys=None, | ||
| unexpected_keys=None, | ||
| offload_index=None, | ||
| offload_folder=None, | ||
| state_dict_index=None, | ||
| state_dict_folder=None, | ||
| ignore_mismatched_sizes=False, | ||
| low_cpu_mem_usage=False, | ||
| ): | ||
| state_dict = load_state_dict(shard_file, dduf_entries=dduf_entries) | ||
| mismatched_keys = _find_mismatched_keys( | ||
| state_dict, | ||
| model_state_dict, | ||
| loaded_keys, | ||
| ignore_mismatched_sizes, | ||
| ) | ||
| error_msgs = [] | ||
| if low_cpu_mem_usage: | ||
| offload_index, state_dict_index = load_model_dict_into_meta( | ||
| model, | ||
| state_dict, | ||
| device_map=device_map, | ||
| dtype=dtype, | ||
| hf_quantizer=hf_quantizer, | ||
| keep_in_fp32_modules=keep_in_fp32_modules, | ||
| unexpected_keys=unexpected_keys, | ||
| offload_folder=offload_folder, | ||
| offload_index=offload_index, | ||
| state_dict_index=state_dict_index, | ||
| state_dict_folder=state_dict_folder, | ||
| ) | ||
| else: | ||
| assign_to_params_buffers = check_support_param_buffer_assignment(model, state_dict) | ||
|  | ||
| error_msgs += _load_state_dict_into_model(model, state_dict, assign_to_params_buffers) | ||
| return offload_index, state_dict_index, mismatched_keys, error_msgs | ||
|  | ||
|  | ||
| def _load_shard_files_with_threadpool( | ||
| shard_files, | ||
| model, | ||
| model_state_dict, | ||
| device_map=None, | ||
| dtype=None, | ||
| hf_quantizer=None, | ||
| keep_in_fp32_modules=None, | ||
| dduf_entries=None, | ||
| loaded_keys=None, | ||
| unexpected_keys=None, | ||
| offload_index=None, | ||
| offload_folder=None, | ||
| state_dict_index=None, | ||
| state_dict_folder=None, | ||
| ignore_mismatched_sizes=False, | ||
| low_cpu_mem_usage=False, | ||
| ): | ||
| # Do not spawn anymore workers than you need | ||
| num_workers = min(len(shard_files), DEFAULT_HF_PARALLEL_LOADING_WORKERS) | ||
|  | ||
| logger.info(f"Loading model weights in parallel with {num_workers} workers...") | ||
|  | ||
| error_msgs = [] | ||
| mismatched_keys = [] | ||
|  | ||
| load_one = functools.partial( | ||
| _load_shard_file, | ||
| model=model, | ||
| model_state_dict=model_state_dict, | ||
| device_map=device_map, | ||
| dtype=dtype, | ||
| hf_quantizer=hf_quantizer, | ||
| keep_in_fp32_modules=keep_in_fp32_modules, | ||
| dduf_entries=dduf_entries, | ||
| loaded_keys=loaded_keys, | ||
| unexpected_keys=unexpected_keys, | ||
| offload_index=offload_index, | ||
| offload_folder=offload_folder, | ||
| state_dict_index=state_dict_index, | ||
| state_dict_folder=state_dict_folder, | ||
| ignore_mismatched_sizes=ignore_mismatched_sizes, | ||
| low_cpu_mem_usage=low_cpu_mem_usage, | ||
| ) | ||
|  | ||
| with ThreadPoolExecutor(max_workers=num_workers) as executor: | ||
| with logging.tqdm(total=len(shard_files), desc="Loading checkpoint shards") as pbar: | ||
| futures = [executor.submit(load_one, shard_file) for shard_file in shard_files] | ||
| for future in as_completed(futures): | ||
| result = future.result() | ||
| offload_index, state_dict_index, _mismatched_keys, _error_msgs = result | ||
| error_msgs += _error_msgs | ||
| mismatched_keys += _mismatched_keys | ||
| pbar.update(1) | ||
|  | ||
| return offload_index, state_dict_index, mismatched_keys, error_msgs | ||
|  | ||
|  | ||
| def _find_mismatched_keys( | ||
| 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. Same. Moved it out of  | ||
| state_dict, | ||
| model_state_dict, | ||
| loaded_keys, | ||
| ignore_mismatched_sizes, | ||
| ): | ||
| mismatched_keys = [] | ||
| if ignore_mismatched_sizes: | ||
| for checkpoint_key in loaded_keys: | ||
| model_key = checkpoint_key | ||
| # If the checkpoint is sharded, we may not have the key here. | ||
| if checkpoint_key not in state_dict: | ||
| continue | ||
|  | ||
| if model_key in model_state_dict and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape: | ||
| mismatched_keys.append( | ||
| (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape) | ||
| ) | ||
| del state_dict[checkpoint_key] | ||
| return mismatched_keys | ||
|  | ||
|  | ||
| def _load_state_dict_into_model( | ||
| model_to_load, state_dict: OrderedDict, assign_to_params_buffers: bool = False | ||
| ) -> List[str]: | ||
|  | ||
      
      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.
Moved it here from
modeling_utils.py.