MCPcopy Create free account
hub / github.com/TencentARC/BrushNet / set_attention_slice

Method set_attention_slice

src/diffusers/models/controlnet.py:594–657  ·  view source on GitHub ↗

r""" Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor in slices to compute attention in several steps. This is useful for saving some memory in exchange for a small decrease in speed. Args: sl

(self, slice_size: Union[str, int, List[int]])

Source from the content-addressed store, hash-verified

592
593 # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
594 def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
595 r"""
596 Enable sliced attention computation.
597
598 When this option is enabled, the attention module splits the input tensor in slices to compute attention in
599 several steps. This is useful for saving some memory in exchange for a small decrease in speed.
600
601 Args:
602 slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
603 When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
604 `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
605 provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
606 must be a multiple of `slice_size`.
607 """
608 sliceable_head_dims = []
609
610 def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
611 if hasattr(module, "set_attention_slice"):
612 sliceable_head_dims.append(module.sliceable_head_dim)
613
614 for child in module.children():
615 fn_recursive_retrieve_sliceable_dims(child)
616
617 # retrieve number of attention layers
618 for module in self.children():
619 fn_recursive_retrieve_sliceable_dims(module)
620
621 num_sliceable_layers = len(sliceable_head_dims)
622
623 if slice_size == "auto":
624 # half the attention head size is usually a good trade-off between
625 # speed and memory
626 slice_size = [dim // 2 for dim in sliceable_head_dims]
627 elif slice_size == "max":
628 # make smallest slice possible
629 slice_size = num_sliceable_layers * [1]
630
631 slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
632
633 if len(slice_size) != len(sliceable_head_dims):
634 raise ValueError(
635 f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
636 f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
637 )
638
639 for i in range(len(slice_size)):
640 size = slice_size[i]
641 dim = sliceable_head_dims[i]
642 if size is not None and size > dim:
643 raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
644
645 # Recursively walk through all the children.
646 # Any children which exposes the set_attention_slice method
647 # gets the message
648 def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
649 if hasattr(module, "set_attention_slice"):
650 module.set_attention_slice(slice_size.pop())
651

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected