|
| 1 | +import math |
1 | 2 | import torch |
| 3 | +import diffusers |
2 | 4 |
|
3 | 5 |
|
4 | 6 | if torch.backends.mps.is_available(): |
@@ -61,3 +63,150 @@ def new_torch_interpolate(input, size=None, scale_factor=None, mode='nearest', a |
61 | 63 | return _torch_interpolate(input, size, scale_factor, mode, align_corners, recompute_scale_factor, antialias) |
62 | 64 |
|
63 | 65 | torch.nn.functional.interpolate = new_torch_interpolate |
| 66 | + |
| 67 | +# TODO: refactor it |
| 68 | +_SlicedAttnProcessor = diffusers.models.attention_processor.SlicedAttnProcessor |
| 69 | +class ChunkedSlicedAttnProcessor: |
| 70 | + r""" |
| 71 | + Processor for implementing sliced attention. |
| 72 | +
|
| 73 | + Args: |
| 74 | + slice_size (`int`, *optional*): |
| 75 | + The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and |
| 76 | + `attention_head_dim` must be a multiple of the `slice_size`. |
| 77 | + """ |
| 78 | + |
| 79 | + def __init__(self, slice_size): |
| 80 | + assert isinstance(slice_size, int) |
| 81 | + slice_size = 1 # TODO: maybe implement chunking in batches too when enough memory |
| 82 | + self.slice_size = slice_size |
| 83 | + self._sliced_attn_processor = _SlicedAttnProcessor(slice_size) |
| 84 | + |
| 85 | + def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None): |
| 86 | + if self.slice_size != 1: |
| 87 | + return self._sliced_attn_processor(attn, hidden_states, encoder_hidden_states, attention_mask) |
| 88 | + |
| 89 | + residual = hidden_states |
| 90 | + |
| 91 | + input_ndim = hidden_states.ndim |
| 92 | + |
| 93 | + if input_ndim == 4: |
| 94 | + batch_size, channel, height, width = hidden_states.shape |
| 95 | + hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) |
| 96 | + |
| 97 | + batch_size, sequence_length, _ = ( |
| 98 | + hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape |
| 99 | + ) |
| 100 | + attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) |
| 101 | + |
| 102 | + if attn.group_norm is not None: |
| 103 | + hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) |
| 104 | + |
| 105 | + query = attn.to_q(hidden_states) |
| 106 | + dim = query.shape[-1] |
| 107 | + query = attn.head_to_batch_dim(query) |
| 108 | + |
| 109 | + if encoder_hidden_states is None: |
| 110 | + encoder_hidden_states = hidden_states |
| 111 | + elif attn.norm_cross: |
| 112 | + encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) |
| 113 | + |
| 114 | + key = attn.to_k(encoder_hidden_states) |
| 115 | + value = attn.to_v(encoder_hidden_states) |
| 116 | + key = attn.head_to_batch_dim(key) |
| 117 | + value = attn.head_to_batch_dim(value) |
| 118 | + |
| 119 | + batch_size_attention, query_tokens, _ = query.shape |
| 120 | + hidden_states = torch.zeros( |
| 121 | + (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype |
| 122 | + ) |
| 123 | + |
| 124 | + chunk_tmp_tensor = torch.empty(self.slice_size, query.shape[1], key.shape[1], dtype=query.dtype, device=query.device) |
| 125 | + |
| 126 | + for i in range(batch_size_attention // self.slice_size): |
| 127 | + start_idx = i * self.slice_size |
| 128 | + end_idx = (i + 1) * self.slice_size |
| 129 | + |
| 130 | + query_slice = query[start_idx:end_idx] |
| 131 | + key_slice = key[start_idx:end_idx] |
| 132 | + attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None |
| 133 | + |
| 134 | + self.get_attention_scores_chunked(attn, query_slice, key_slice, attn_mask_slice, hidden_states[start_idx:end_idx], value[start_idx:end_idx], chunk_tmp_tensor) |
| 135 | + |
| 136 | + hidden_states = attn.batch_to_head_dim(hidden_states) |
| 137 | + |
| 138 | + # linear proj |
| 139 | + hidden_states = attn.to_out[0](hidden_states) |
| 140 | + # dropout |
| 141 | + hidden_states = attn.to_out[1](hidden_states) |
| 142 | + |
| 143 | + if input_ndim == 4: |
| 144 | + hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) |
| 145 | + |
| 146 | + if attn.residual_connection: |
| 147 | + hidden_states = hidden_states + residual |
| 148 | + |
| 149 | + hidden_states = hidden_states / attn.rescale_output_factor |
| 150 | + |
| 151 | + return hidden_states |
| 152 | + |
| 153 | + |
| 154 | + def get_attention_scores_chunked(self, attn, query, key, attention_mask, hidden_states, value, chunk): |
| 155 | + # batch size = 1 |
| 156 | + assert query.shape[0] == 1 |
| 157 | + assert key.shape[0] == 1 |
| 158 | + assert value.shape[0] == 1 |
| 159 | + assert hidden_states.shape[0] == 1 |
| 160 | + |
| 161 | + dtype = query.dtype |
| 162 | + if attn.upcast_attention: |
| 163 | + query = query.float() |
| 164 | + key = key.float() |
| 165 | + |
| 166 | + #out_item_size = query.dtype.itemsize |
| 167 | + #if attn.upcast_attention: |
| 168 | + # out_item_size = torch.float32.itemsize |
| 169 | + out_item_size = query.element_size() |
| 170 | + if attn.upcast_attention: |
| 171 | + out_item_size = 4 |
| 172 | + |
| 173 | + chunk_size = 2 ** 29 |
| 174 | + |
| 175 | + out_size = query.shape[1] * key.shape[1] * out_item_size |
| 176 | + chunks_count = min(query.shape[1], math.ceil((out_size - 1) / chunk_size)) |
| 177 | + chunk_step = max(1, int(query.shape[1] / chunks_count)) |
| 178 | + |
| 179 | + key = key.transpose(-1, -2) |
| 180 | + |
| 181 | + def _get_chunk_view(tensor, start, length): |
| 182 | + if start + length > tensor.shape[1]: |
| 183 | + length = tensor.shape[1] - start |
| 184 | + #print(f"view: [{tensor.shape[0]},{tensor.shape[1]},{tensor.shape[2]}] - start: {start}, length: {length}") |
| 185 | + return tensor[:,start:start+length] |
| 186 | + |
| 187 | + for chunk_pos in range(0, query.shape[1], chunk_step): |
| 188 | + if attention_mask is not None: |
| 189 | + torch.baddbmm( |
| 190 | + _get_chunk_view(attention_mask, chunk_pos, chunk_step), |
| 191 | + _get_chunk_view(query, chunk_pos, chunk_step), |
| 192 | + key, |
| 193 | + beta=1, |
| 194 | + alpha=attn.scale, |
| 195 | + out=chunk, |
| 196 | + ) |
| 197 | + else: |
| 198 | + torch.baddbmm( |
| 199 | + torch.zeros((1,1,1), device=query.device, dtype=query.dtype), |
| 200 | + _get_chunk_view(query, chunk_pos, chunk_step), |
| 201 | + key, |
| 202 | + beta=0, |
| 203 | + alpha=attn.scale, |
| 204 | + out=chunk, |
| 205 | + ) |
| 206 | + chunk = chunk.softmax(dim=-1) |
| 207 | + torch.bmm(chunk, value, out=_get_chunk_view(hidden_states, chunk_pos, chunk_step)) |
| 208 | + |
| 209 | + #del chunk |
| 210 | + |
| 211 | + |
| 212 | +diffusers.models.attention_processor.SlicedAttnProcessor = ChunkedSlicedAttnProcessor |
0 commit comments