partitioned_param_coordinator.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. from dataclasses import dataclass
  5. import collections
  6. from collections import UserDict
  7. from typing import Deque, Set
  8. from deepspeed import comm as dist
  9. from deepspeed.utils.logging import logger
  10. from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum
  11. from deepspeed.runtime.zero.partition_parameters import *
  12. from deepspeed.runtime.zero.partitioned_param_profiler import PartitionedParameterProfiler
  13. from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus
  14. from deepspeed.utils.debug import debug_module2name_id, debug_param2name_id
  15. from deepspeed.accelerator import get_accelerator
  16. import logging
  17. ENABLE_PROFILER = False
  18. def debug_rank0(message: str) -> None:
  19. if dist.get_rank() == 0:
  20. logger.debug(message)
  21. @instrument_w_nvtx
  22. def get_all_parameters(sub_module, recurse=False):
  23. return itertools.chain(sub_module.named_parameters(recurse=recurse), sub_module.ds_external_parameters())
  24. def iter_params(module: Module, recurse=False) -> Iterable[Parameter]:
  25. return map(lambda pair: pair[1], get_all_parameters(module, recurse))
  26. class ZeRoTraceMode(Enum):
  27. # Record trace of the network during a single forward+backward (for training) or forward (for inference)
  28. RECORD = 1
  29. # Use recorded network trace to optimize current forward+backward or forward
  30. COMPLETE = 2
  31. # Recorded trace does not match current forward+backward or forward pass.
  32. INVALID = 3
  33. class InflightParamRegistry(UserDict):
  34. """registry for parameters in flight"""
  35. def __setitem__(self, param: Parameter, handle: AllGatherCoalescedHandle) -> None:
  36. if param in self.data:
  37. raise RuntimeError(f"{param.ds_summary()} already in registry")
  38. if param.ds_status != ZeroParamStatus.INFLIGHT:
  39. raise RuntimeError(f"attempted to add non-inflight parameter to registry {param.ds_summary()}")
  40. self.data[param] = handle
  41. class PartitionedParameterCoordinator:
  42. FORWARD_FETCH_SUBMIT = 'forward_fetch_submit'
  43. FORWARD_FETCH_WAIT = 'forward_fetch_wait'
  44. FORWARD_PREFETCH_SUBMIT = 'forward_prefetch_submit'
  45. BACKWARD_FETCH_SUBMIT = 'backward_fetch_submit'
  46. BACKWARD_FETCH_WAIT = 'backward_fetch_wait'
  47. BACKWARD_PREFETCH_SUBMIT = 'backward_prefetch_wait'
  48. FORWARD_ALL_GATHER = 'forward_all_gather'
  49. BACKWARD_ALL_GATHER = 'backward_all_gather'
  50. """Handles partitioning and gathering of parameters."""
  51. @dataclass
  52. class __ParamInTrace:
  53. param: Parameter
  54. step_id_last_used_at: int
  55. def __init__(
  56. self,
  57. prefetch_bucket_sz: int,
  58. max_reuse_distance_in_numel: int,
  59. max_available_parameters_in_numel: int,
  60. allgather_stream: get_accelerator().Stream,
  61. inflight_param_registry: InflightParamRegistry,
  62. prefetch_nvme: bool = False,
  63. timers=None,
  64. ) -> None:
  65. # mapping of param -> handle for each param that is currently in flight
  66. self.__inflight_param_registry = inflight_param_registry
  67. # keeps track of the number of submodules invoked so far.
  68. self.__step_id: int = 0
  69. # network tracing mode
  70. self.__trace_mode: ZeRoTraceMode = ZeRoTraceMode.RECORD
  71. # sequence of submodules/parameters in forward pass + backward pass
  72. self.__submodule_order: Iterable[Module] = []
  73. self.__param_order: Iterable[__class__.__ParamInTrace] = []
  74. self.__most_recent_step_id_param_fetched_for = collections.defaultdict(lambda: int(-1e10))
  75. self.__step_id_module_fetched_for = collections.defaultdict(lambda: collections.deque())
  76. # number of available params, and max number of available params
  77. self.__n_available_params: int = 0
  78. self.__max_n_available_params: int = max_available_parameters_in_numel
  79. # max distance between two use of the module beyond which module is released
  80. self.__max_reuse_dist_in_numel: int = max_reuse_distance_in_numel
  81. # queue for parameters to fetch. parameters will be popped off the left
  82. # side of the dequeue as they are fetched
  83. self.__param_queue: Deque[__class__.__ParamInTrace] = None
  84. self.__prefetch_bucket_sz: int = prefetch_bucket_sz
  85. self.__prefetch_nvme: bool = prefetch_nvme
  86. self.hierarchy: int = 0
  87. # stream that will be used for allgather operations
  88. self.__allgather_stream: get_accelerator().Stream = allgather_stream
  89. # limit the number of fetch events that can be queued at once
  90. # otherwise, what happens is memory is allocated by the host thread at the
  91. # time of the call, but not used until later by the asynchronous cuda stream.
  92. # allowing an infinite number of these to queue up causes a lot of memory
  93. # pressure that then becomes detrimental to performance.
  94. # this is a much less elegant way of fixing this vs something like using
  95. # cudaMallocAsync/cudaFreeAsync. Choosing to not expose this to the user now
  96. # because ideally in the future its replaced by an async allocation
  97. # mechanism which doesn't require any configuration by the user.
  98. self.__ongoing_fetch_events: Deque[get_accelerator().Event] = collections.deque()
  99. # TODO. make this configurable via JSON
  100. self.__max_ongoing_fetch_events: int = 2
  101. self.__profiler = PartitionedParameterProfiler(timers if ENABLE_PROFILER else None)
  102. """Tracing and Tracking
  103. TODO. consider performing trace before initializing PartitionedParameterCoordinator
  104. and passing trace results into constructor. This way all the code in here can
  105. just assume that the trace is complete and the results can be entirely
  106. immutable.
  107. Bookkeeping operations used to track where we are in the forward/backward pass
  108. """
  109. def _clear_trace_structures(self) -> None:
  110. self.__submodule_order = []
  111. self.__param_order = []
  112. self.__most_recent_step_id_param_fetched_for = collections.defaultdict(lambda: int(-1e10))
  113. self.__param_queue = None
  114. def is_complete_trace(self) -> bool:
  115. return self.__trace_mode == ZeRoTraceMode.COMPLETE
  116. def is_invalid_trace(self) -> bool:
  117. return self.__trace_mode == ZeRoTraceMode.INVALID
  118. def is_record_trace(self) -> bool:
  119. return self.__trace_mode == ZeRoTraceMode.RECORD
  120. def _invalidate_trace(self) -> None:
  121. if self.is_invalid_trace():
  122. raise RuntimeError("attempted to invalidate already invalid trace")
  123. self.__trace_mode = ZeRoTraceMode.INVALID
  124. self._clear_trace_structures()
  125. def trace_prologue(self, sub_module: Module) -> None:
  126. if self.is_complete_trace():
  127. # sub_module must match expectation else invalidate trace cache
  128. if len(self.__submodule_order) <= self.__step_id:
  129. print_rank_0(
  130. f"Invalidate trace cache @ step {self.__step_id} and module {sub_module.id}: "
  131. f"cache has only {len(self.__submodule_order)} modules",
  132. force=True)
  133. self._invalidate_trace()
  134. return
  135. if sub_module != self.__submodule_order[self.__step_id]:
  136. expected_module_id = self.__submodule_order[self.__step_id].id
  137. print_rank_0(
  138. f"Invalidate trace cache @ step {self.__step_id}: "
  139. f"expected module {expected_module_id}, but got module {sub_module.id}",
  140. force=True)
  141. self._invalidate_trace()
  142. def record_module(self, sub_module: Module) -> None:
  143. """adds sub module to trace"""
  144. if not self.is_record_trace():
  145. raise RuntimeError(f"attempted to record trace when status = {self.__trace_mode}")
  146. self.__submodule_order.append(sub_module)
  147. self.__step_id_module_fetched_for[sub_module.id].append(self.__step_id)
  148. def record_parameters(self, sub_module: Module) -> None:
  149. """adds sub module to trace"""
  150. if not self.is_record_trace():
  151. raise RuntimeError(f"attempted to record trace when status = {self.__trace_mode}")
  152. step_id = self.__step_id_module_fetched_for[sub_module.id].popleft()
  153. for param in sorted(set(iter_params(sub_module)), key=lambda p: p.ds_id):
  154. self.__param_order.append(__class__.__ParamInTrace(param=param, step_id_last_used_at=step_id))
  155. def construct_parameter_trace_from_module_trace(self):
  156. """use module trace to construct parameter trace"""
  157. self.__param_order = []
  158. for sub_module in self.__submodule_order:
  159. self.record_parameters(sub_module)
  160. def reset_step(self) -> None:
  161. """indicate that we have completed one fwd+bwd for the model"""
  162. if self.__inflight_param_registry:
  163. raise RuntimeError(f"still have inflight params "
  164. f"{[p.ds_summary() for p in self.__inflight_param_registry.keys()]}")
  165. if not self.is_complete_trace(): # not self.trace_complete:
  166. # Make sure that recorded submodule orders are identical across ranks
  167. assert_ints_same_as_other_ranks([m.id for m in self.__submodule_order])
  168. if self.is_record_trace():
  169. # Successfully recorded a trace
  170. self.construct_parameter_trace_from_module_trace()
  171. # Make sure that recorded parameter orders are identical across ranks
  172. assert_ints_same_as_other_ranks([p.param.ds_id for p in self.__param_order])
  173. assert_ints_same_as_other_ranks([p.step_id_last_used_at for p in self.__param_order])
  174. self.__submodule_order = tuple(self.__submodule_order) # freeze
  175. self.__param_order = tuple(self.__param_order) # freeze
  176. self.__trace_mode = ZeRoTraceMode.COMPLETE
  177. print_rank_0(
  178. f"completed record trace of {len(self.__submodule_order)} sub modules: {[m.id for m in self.__submodule_order]}",
  179. force=False)
  180. else:
  181. # Enable trace recording for next forward/backward pass
  182. self.__trace_mode = ZeRoTraceMode.RECORD
  183. else:
  184. if self.__profiler is not None:
  185. self.__profiler.log_events()
  186. self.__param_queue = collections.deque(self.__param_order) # reset fetch queue
  187. self.__most_recent_step_id_param_fetched_for = collections.defaultdict(lambda: int(-1e10))
  188. self.__step_id_module_fetched_for = collections.defaultdict(lambda: collections.deque())
  189. self.__step_id = 0
  190. self.__n_available_params = 0
  191. self.__profiler.reset_events()
  192. def _dump_params(self, tag, sub_module, params, step_id=None):
  193. if step_id is None:
  194. step_id = self.__step_id
  195. param_names = [debug_param2name_id(p) for p in params]
  196. print_rank_0(f'{tag} step = {step_id} mod = {debug_module2name_id(sub_module)} p_names = {param_names}',
  197. force=False)
  198. def _dump_param_ids(self, tag, mod_id, p_ids, step_id=None):
  199. if step_id is None:
  200. step_id = self.__step_id
  201. print_rank_0(f'{tag} mod = {mod_id}, step = {step_id}, p_ids = {p_ids}', force=False)
  202. """Fetch and Release
  203. Fetching, prefetching, and releasing parameters
  204. """
  205. @instrument_w_nvtx
  206. @torch.no_grad()
  207. def fetch_sub_module(self, current_submodule: Module, forward: bool) -> None:
  208. """This method does the following (in order):
  209. 1. kick off fetch for parameters in immediately required sub module
  210. 2. kick off fetch for next few parameters we will need later (prefetch)
  211. 3. block on parameters in immediately required sub module
  212. """
  213. if logger.isEnabledFor(logging.DEBUG):
  214. debug_rank0(
  215. f"{self.__step_id}: M{current_submodule.id}({type(current_submodule).__name__}) P{[p.ds_id for p in iter_params(current_submodule)]} "
  216. + str({
  217. "avail": f"{self.__n_available_params:.1e}",
  218. "queue_sz": f"{len(self.__param_queue or [])}",
  219. "inflight": [p.ds_id for p in self.__inflight_param_registry],
  220. }))
  221. params_to_fetch = frozenset(iter_params(current_submodule))
  222. fetch_numel = sum(
  223. [p.partition_numel() for p in params_to_fetch if p.ds_status == ZeroParamStatus.NOT_AVAILABLE])
  224. if fetch_numel > 0:
  225. event_name = __class__.FORWARD_FETCH_SUBMIT if forward else __class__.BACKWARD_FETCH_SUBMIT
  226. self._dump_param_ids(event_name, current_submodule.id,
  227. [p.ds_id for p in params_to_fetch if p.ds_status == ZeroParamStatus.NOT_AVAILABLE])
  228. self.__profiler.start_event(event_name)
  229. # kick off all gather for params in the immediately required submodule
  230. #for param in params_to_fetch:
  231. if logger.isEnabledFor(logging.DEBUG):
  232. for param in params_to_fetch:
  233. debug_rank0(f"-fetch: {param.ds_summary()}")
  234. self.__all_gather_params(params_to_fetch, forward)
  235. self.__profiler.stop_event(event_name, fetch_numel)
  236. wait_numel = 0
  237. wait_event_name = __class__.FORWARD_FETCH_WAIT if forward else __class__.BACKWARD_FETCH_WAIT
  238. self.__profiler.start_event(wait_event_name)
  239. # wait for parameters in the immediately needed submodule to become available
  240. for param in params_to_fetch:
  241. param.ds_active_sub_modules.add(current_submodule.id)
  242. if logger.isEnabledFor(logging.DEBUG):
  243. debug_rank0(f"-wait: {param.ds_summary()}")
  244. if param in self.__inflight_param_registry:
  245. wait_numel += param.partition_numel()
  246. with get_accelerator().stream(self.__allgather_stream):
  247. while self.__ongoing_fetch_events and self.__ongoing_fetch_events[0].query():
  248. self.__ongoing_fetch_events.popleft()
  249. if len(self.__ongoing_fetch_events) > self.__max_ongoing_fetch_events:
  250. self.__ongoing_fetch_events.popleft().synchronize()
  251. self.__inflight_param_registry.pop(param).wait()
  252. if not get_accelerator().is_synchronized_device():
  253. event = get_accelerator().Event()
  254. event.record()
  255. self.__ongoing_fetch_events.append(event)
  256. assert param.ds_status == ZeroParamStatus.AVAILABLE, param.ds_summary()
  257. if not get_accelerator().is_synchronized_device():
  258. get_accelerator().current_stream().wait_stream(self.__allgather_stream)
  259. self.__profiler.stop_event(wait_event_name, wait_numel)
  260. # kick off parameter prefetches for upcoming modules
  261. # don't prefetch if we dont have a completed model trace
  262. if self.is_complete_trace():
  263. # go through the parameters we need for the current module and pop them
  264. # off the fetch queue so that they aren't prefetched later.
  265. # if params have already been popped off the fetch queue by earlier
  266. # prefetches we won't look for them here
  267. discarded_from_prefetch_queue = set()
  268. params_not_already_fetched = set(
  269. filter(lambda p: self.__most_recent_step_id_param_fetched_for[p] < self.__step_id, params_to_fetch))
  270. while self.__param_queue and len(discarded_from_prefetch_queue) < len(params_not_already_fetched):
  271. param_in_trace = self.__param_queue.popleft()
  272. self.__most_recent_step_id_param_fetched_for[
  273. param_in_trace.param] = param_in_trace.step_id_last_used_at
  274. discarded_from_prefetch_queue.add(param_in_trace.param)
  275. if discarded_from_prefetch_queue != params_not_already_fetched:
  276. raise RuntimeError(
  277. f"tracing error at step {self.__step_id}: \n"
  278. f"module id: {current_submodule.id}, training: {current_submodule.training}\n"
  279. f"expected the next {len(params_not_already_fetched)} parameters in the "
  280. f"parameter fetch queue to be {tuple(p.ds_summary(use_debug_name=True) for p in params_not_already_fetched)} \n"
  281. f"but got \n {tuple(p.ds_summary(use_debug_name=True) for p in discarded_from_prefetch_queue)}.")
  282. def _is_currently_on_nvme(param):
  283. if param.nvme_swapper is None:
  284. return False
  285. return param.ds_tensor.final_location == OffloadDeviceEnum.nvme \
  286. and param.ds_tensor.status == PartitionedParamStatus.NOT_AVAILABLE
  287. # kick off all gather for params in the next few submodules (prefetch)
  288. if self.__prefetch_bucket_sz > 0:
  289. max_params_to_prefetch = min(self.__max_n_available_params - self.__n_available_params,
  290. self.__prefetch_bucket_sz)
  291. params_to_prefetch = set()
  292. numel_prefetching = 0
  293. while self.__param_queue and numel_prefetching < max_params_to_prefetch:
  294. param_in_trace: __class__.__ParamInTrace = self.__param_queue.popleft()
  295. if _is_currently_on_nvme(param_in_trace.param):
  296. # nvme prefetch is handled elsewhere. Need to break here to preserve fetch order
  297. self.__param_queue.appendleft(param_in_trace)
  298. break
  299. do_prefetch = param_in_trace.param.ds_status == ZeroParamStatus.NOT_AVAILABLE
  300. if param_in_trace.param in params_to_prefetch:
  301. # Avoid duplicates
  302. do_prefetch = False
  303. self.__most_recent_step_id_param_fetched_for[param_in_trace.param] = \
  304. max(self.__most_recent_step_id_param_fetched_for[param_in_trace.param],
  305. param_in_trace.step_id_last_used_at)
  306. if do_prefetch:
  307. params_to_prefetch.add(param_in_trace.param)
  308. numel_prefetching += param_in_trace.param.ds_numel
  309. if numel_prefetching > 0:
  310. event_name = __class__.FORWARD_PREFETCH_SUBMIT if forward else __class__.BACKWARD_PREFETCH_SUBMIT
  311. self.__profiler.start_event(event_name)
  312. if logger.isEnabledFor(logging.DEBUG):
  313. for param in params_to_prefetch:
  314. debug_rank0(f"-prefetch: {param.ds_summary()}")
  315. self.__all_gather_params(params_to_prefetch, forward)
  316. self.__profiler.stop_event(event_name, numel_prefetching)
  317. if self.__prefetch_nvme:
  318. self.__prefetch_nvme_param_partitions()
  319. self.__step_id += 1
  320. @instrument_w_nvtx
  321. @torch.no_grad()
  322. def release_sub_module(self, submodule: Module, backward: bool) -> None:
  323. """release the parameters of a sub module, assuming they meet conditions to
  324. be released."""
  325. params_to_release = (self.__params_to_release(submodule, self.__step_id) if self.is_complete_trace() else set(
  326. p.ds_id for p in iter_params(submodule)))
  327. for param in iter_params(submodule):
  328. param.ds_active_sub_modules.discard(submodule.id)
  329. if param.ds_id in params_to_release and not param.is_external_param:
  330. self.__release_param(param, backward)
  331. @instrument_w_nvtx
  332. @torch.no_grad()
  333. def release_and_reset_all(self, module: Module) -> None:
  334. """release all module parameters"""
  335. for param in iter_params(module, recurse=True):
  336. if param in self.__inflight_param_registry:
  337. raise RuntimeError(f"param {param.ds_summary()} still in flight")
  338. # TODO. make this throw if if there are still active submodules. currently
  339. # there's a hook execution issue
  340. param.ds_active_sub_modules.clear()
  341. self.__release_param(param, backward=False)
  342. for param in iter_params(module, recurse=True):
  343. if param.ds_status != ZeroParamStatus.NOT_AVAILABLE:
  344. raise RuntimeError(f"{param.ds_summary()} expected to be released")
  345. @instrument_w_nvtx
  346. def __all_gather_params(self, params: Set[Parameter], forward: bool) -> None:
  347. """for each partitioned parameter, kick off an async allgather and store
  348. the work handle for the in flight parameters."""
  349. partitioned_params = []
  350. all_gather_numel = 0
  351. for param in params:
  352. if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
  353. partitioned_params.append(param)
  354. all_gather_numel += param.ds_numel
  355. if partitioned_params:
  356. self.__n_available_params += all_gather_numel
  357. with get_accelerator().stream(self.__allgather_stream):
  358. event_name = __class__.FORWARD_ALL_GATHER if forward else __class__.BACKWARD_ALL_GATHER
  359. self.__profiler.start_event(event_name)
  360. handle = partitioned_params[0].all_gather_coalesced(partitioned_params, forward)
  361. self.__profiler.stop_event(event_name, all_gather_numel)
  362. for param in partitioned_params:
  363. assert param.ds_status == ZeroParamStatus.INFLIGHT, param.ds_summary()
  364. self.__inflight_param_registry[param] = handle
  365. # Release swap buffers for persisted params on nvme since they will never be partitioned or evicted from GPU
  366. swap_persisted_params = [
  367. p for p in partitioned_params if p.ds_persist and p.ds_tensor.final_location == OffloadDeviceEnum.nvme
  368. ]
  369. if swap_persisted_params:
  370. swap_persisted_params[0].nvme_swapper.remove_partition_and_release_buffers(swap_persisted_params)
  371. @instrument_w_nvtx
  372. def __release_param(self, param: Parameter, backward: bool) -> None:
  373. if param.ds_status == ZeroParamStatus.AVAILABLE and not param.ds_active_sub_modules:
  374. if logger.isEnabledFor(logging.DEBUG):
  375. debug_rank0(f"-release: {param.ds_summary()}")
  376. param.partition(backward=backward)
  377. self.__n_available_params -= param.ds_numel
  378. @instrument_w_nvtx
  379. @functools.lru_cache(maxsize=None)
  380. def __params_to_release(self, submodule_to_release: Module, step_id: int) -> Set[int]:
  381. if not self.is_complete_trace():
  382. raise RuntimeError("expected trace to be complete")
  383. params_to_release = set(p.ds_id for p in iter_params(submodule_to_release) if not p.ds_persist)
  384. # Problem: When prefetcher scans the param trace, it skips AVAILABLE params.
  385. # This creates issues if those params are released before the skipped uses:
  386. # 1) It hurts performance as the skipped uses are never prefetched.
  387. # 2) For nvme params, we run out of swap buffers because the prefetch order
  388. # diverges from the trace.
  389. # Solution: Don't release params whose reuse was skipped by prefetch. This is
  390. # possible because we detect such skips during prefetch and mark those params.
  391. for param in iter_params(submodule_to_release):
  392. if self.__most_recent_step_id_param_fetched_for[param] > step_id:
  393. params_to_release.discard(param.ds_id)
  394. # examine all modules within `max_reuse_dist_in_numel` of the current step,
  395. # if we see any of the candidate parameters to be released reoccur while
  396. # doing this, remove them from the set of parameters to release.
  397. params_traversed = 0
  398. for module in self.__submodule_order[step_id:]:
  399. if params_traversed >= self.__max_reuse_dist_in_numel:
  400. break
  401. for param in iter_params(module):
  402. params_to_release.discard(param.ds_id)
  403. params_traversed += param.ds_numel
  404. return params_to_release
  405. @instrument_w_nvtx
  406. def __prefetch_nvme_param_partitions(self) -> None:
  407. """swap in parameter partitions from nvme for those parameters that will be used
  408. after the ones that are already being prefetched into full parameters
  409. """
  410. if not self.is_complete_trace():
  411. return
  412. numel_in_flight = sum(param.ds_numel for param in self.__inflight_param_registry)
  413. numel_considered = 0
  414. swap_in_params = []
  415. for param_in_trace in self.__param_queue:
  416. param = param_in_trace.param
  417. if param.nvme_swapper is None:
  418. continue
  419. if (numel_considered > 2 * numel_in_flight
  420. or len(swap_in_params) >= param.nvme_swapper.available_swap_in_buffers()):
  421. break
  422. if param.ds_tensor.status == PartitionedParamStatus.NOT_AVAILABLE:
  423. swap_in_params.append(param)
  424. numel_considered += param.ds_numel
  425. if swap_in_params:
  426. swap_in_params[0].nvme_swapper.swap_in(swap_in_params, async_op=True)