Monkey patch HF_MODULES_CACHE to a temporary directory per process. This is necessary to avoid conflicts when multiple processes try to read/write to the same HF_MODULES_CACHE directory, especially in multi-GPU setups. modified from: https://github.com/InternLM/xtuner/blob/main/xtuner/v
()
| 147 | |
| 148 | |
| 149 | def monkey_patch_hf_modules_cache(): |
| 150 | """Monkey patch HF_MODULES_CACHE to a temporary directory per process. This |
| 151 | is necessary to avoid conflicts when multiple processes try to read/write |
| 152 | to the same HF_MODULES_CACHE directory, especially in multi-GPU setups. |
| 153 | |
| 154 | modified from: https://github.com/InternLM/xtuner/blob/main/xtuner/v1/utils/misc.py |
| 155 | """ |
| 156 | import os |
| 157 | |
| 158 | import transformers |
| 159 | from huggingface_hub import constants |
| 160 | |
| 161 | # When using `remote_code` in HF components like tokenizer or config |
| 162 | # (e.g., `AutoConfig.from_pretrained(hf_model_path, trust_remote_code=True)`), |
| 163 | # the hf_model_path is copied to HF_MODULES_CACHE. |
| 164 | # On multi-GPU machines (e.g., 8 GPUs), simultaneous read/write operations |
| 165 | # by multiple processes on this shared directory can cause conflicts. |
| 166 | # Therefore, we set HF_MODULES_CACHE to a temporary directory per process. |
| 167 | |
| 168 | HF_PATCH_MODULES_CACHE_PREFIX = 'modules_pid_' |
| 169 | modules_cache = os.path.join(constants.HF_HOME, f'{HF_PATCH_MODULES_CACHE_PREFIX}{os.getpid()}') |
| 170 | os.environ['HF_MODULES_CACHE'] = modules_cache |
| 171 | |
| 172 | transformers.utils.hub.HF_MODULES_CACHE = modules_cache |
| 173 | |
| 174 | # During import, Python creates a new name HF_MODULES_CACHE in the namespace |
| 175 | # of the dynamic_module_utils module, binding it to the object referenced by |
| 176 | # transformers.utils.HF_MODULES_CACHE at that moment. |
| 177 | # Hence, we also need to set transformers.dynamic_module_utils.HF_MODULES_CACHE |
| 178 | # to the new modules_cache. |
| 179 | |
| 180 | transformers.dynamic_module_utils.HF_MODULES_CACHE = modules_cache |
| 181 | transformers.utils.HF_MODULES_CACHE = modules_cache |
| 182 | |
| 183 | logger.info(f'Set HF_MODULES_CACHE to {modules_cache} for current process {os.getpid()}') |
| 184 | |
| 185 | |
| 186 | async def wait_for_async_tasks(tasks: Sequence[asyncio.Task], |