MCPcopy
hub / github.com/huggingface/diffusers / offload_models

Function offload_models

src/diffusers/training_utils.py:422–450  ·  view source on GitHub ↗

Context manager that, if offload=True, moves each module to `device` on enter, then moves it back to its original device on exit. Args: device (`str` or `torch.Device`): Device to move the `modules` to. offload (`bool`): Flag to enable offloading.

(*modules: torch.nn.Module | DiffusionPipeline, device: str | torch.device, offload: bool = True)

Source from the content-addressed store, hash-verified

420
421@contextmanager
422def offload_models(*modules: torch.nn.Module | DiffusionPipeline, device: str | torch.device, offload: bool = True):
423 """
424 Context manager that, if offload=True, moves each module to `device` on enter, then moves it back to its original
425 device on exit.
426
427 Args:
428 device (`str` or `torch.Device`): Device to move the `modules` to.
429 offload (`bool`): Flag to enable offloading.
430 """
431 if offload:
432 is_model = not any(isinstance(m, DiffusionPipeline) for m in modules)
433 # record where each module was
434 if is_model:
435 original_devices = [next(m.parameters()).device for m in modules]
436 else:
437 assert len(modules) == 1
438 # For DiffusionPipeline, wrap the device in a list to make it iterable
439 original_devices = [modules[0].device]
440 # move to target device
441 for m in modules:
442 m.to(device)
443
444 try:
445 yield
446 finally:
447 if offload:
448 # move back to original devices
449 for m, orig_dev in zip(modules, original_devices):
450 m.to(orig_dev)
451
452
453def parse_buckets_string(buckets_str):

Callers 7

mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90

Calls 2

parametersMethod · 0.80
toMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…