CoolFace
Apppublic

ysharma/style-aligned-controlnet

sourceHugging Facemitupdated 3y agoView on Hugging Face
21likes
sa_handler.py270 linesDownload Raw Back to root
1# Copyright 2023 Google LLC2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#      http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15 16from __future__ import annotations17 18from dataclasses import dataclass19from diffusers import StableDiffusionXLPipeline20import torch21import torch.nn as nn22from torch.nn import functional as nnf23from diffusers.models import attention_processor24import einops25 26T = torch.Tensor27 28 29@dataclass(frozen=True)30class StyleAlignedArgs:31    share_group_norm: bool = True32    share_layer_norm: bool = True,33    share_attention: bool = True34    adain_queries: bool = True35    adain_keys: bool = True36    adain_values: bool = False37    full_attention_share: bool = False38    keys_scale: float = 1.39    only_self_level: float = 0.40 41 42def expand_first(feat: T, scale=1., ) -> T:43    b = feat.shape[0]44    feat_style = torch.stack((feat[0], feat[b // 2])).unsqueeze(1)45    if scale == 1:46        feat_style = feat_style.expand(2, b // 2, *feat.shape[1:])47    else:48        feat_style = feat_style.repeat(1, b // 2, 1, 1, 1)49        feat_style = torch.cat([feat_style[:, :1], scale * feat_style[:, 1:]], dim=1)50    return feat_style.reshape(*feat.shape)51 52 53def concat_first(feat: T, dim=2, scale=1.) -> T:54    feat_style = expand_first(feat, scale=scale)55    return torch.cat((feat, feat_style), dim=dim)56 57 58def calc_mean_std(feat, eps: float = 1e-5) -> tuple[T, T]:59    feat_std = (feat.var(dim=-2, keepdims=True) + eps).sqrt()60    feat_mean = feat.mean(dim=-2, keepdims=True)61    return feat_mean, feat_std62 63 64def adain(feat: T) -> T:65    feat_mean, feat_std = calc_mean_std(feat)66    feat_style_mean = expand_first(feat_mean)67    feat_style_std = expand_first(feat_std)68    feat = (feat - feat_mean) / feat_std69    feat = feat * feat_style_std + feat_style_mean70    return feat71 72 73class DefaultAttentionProcessor(nn.Module):74 75    def __init__(self):76        super().__init__()77        self.processor = attention_processor.AttnProcessor2_0()78 79    def __call__(self, attn: attention_processor.Attention, hidden_states, encoder_hidden_states=None,80                 attention_mask=None, **kwargs):81        return self.processor(attn, hidden_states, encoder_hidden_states, attention_mask)82 83 84class SharedAttentionProcessor(DefaultAttentionProcessor):85 86    def shared_call(87            self,88            attn: attention_processor.Attention,89            hidden_states,90            encoder_hidden_states=None,91            attention_mask=None,92            **kwargs93    ):94 95        residual = hidden_states96        input_ndim = hidden_states.ndim97        if input_ndim == 4:98            batch_size, channel, height, width = hidden_states.shape99            hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)100        batch_size, sequence_length, _ = (101            hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape102        )103 104        if attention_mask is not None:105            attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)106            # scaled_dot_product_attention expects attention_mask shape to be107            # (batch, heads, source_length, target_length)108            attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])109 110        if attn.group_norm is not None:111            hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)112 113        query = attn.to_q(hidden_states)114        key = attn.to_k(hidden_states)115        value = attn.to_v(hidden_states)116        inner_dim = key.shape[-1]117        head_dim = inner_dim // attn.heads118 119        query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)120        key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)121        value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)122        # if self.step >= self.start_inject:123        if self.adain_queries:124            query = adain(query)125        if self.adain_keys:126            key = adain(key)127        if self.adain_values:128            value = adain(value)129        if self.share_attention:130            key = concat_first(key, -2, scale=self.keys_scale)131            value = concat_first(value, -2)132            hidden_states = nnf.scaled_dot_product_attention(133                query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False134            )135        else:136            hidden_states = nnf.scaled_dot_product_attention(137                query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False138            )139        # hidden_states = adain(hidden_states)140        hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)141        hidden_states = hidden_states.to(query.dtype)142 143        # linear proj144        hidden_states = attn.to_out[0](hidden_states)145        # dropout146        hidden_states = attn.to_out[1](hidden_states)147 148        if input_ndim == 4:149            hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)150 151        if attn.residual_connection:152            hidden_states = hidden_states + residual153 154        hidden_states = hidden_states / attn.rescale_output_factor155        return hidden_states156 157    def __call__(self, attn: attention_processor.Attention, hidden_states, encoder_hidden_states=None,158                 attention_mask=None, **kwargs):159        if self.full_attention_share:160            b, n, d = hidden_states.shape161            hidden_states = einops.rearrange(hidden_states, '(k b) n d -> k (b n) d', k=2)162            hidden_states = super().__call__(attn, hidden_states, encoder_hidden_states=encoder_hidden_states,163                                             attention_mask=attention_mask, **kwargs)164            hidden_states = einops.rearrange(hidden_states, 'k (b n) d -> (k b) n d', n=n)165        else:166            hidden_states = self.shared_call(attn, hidden_states, hidden_states, attention_mask, **kwargs)167 168        return hidden_states169 170    def __init__(self, style_aligned_args: StyleAlignedArgs):171        super().__init__()172        self.share_attention = style_aligned_args.share_attention173        self.adain_queries = style_aligned_args.adain_queries174        self.adain_keys = style_aligned_args.adain_keys175        self.adain_values = style_aligned_args.adain_values176        self.full_attention_share = style_aligned_args.full_attention_share177        self.keys_scale = style_aligned_args.keys_scale178 179 180def _get_switch_vec(total_num_layers, level):181    if level == 0:182        return torch.zeros(total_num_layers, dtype=torch.bool)183    if level == 1:184        return torch.ones(total_num_layers, dtype=torch.bool)185    to_flip = level > .5186    if to_flip:187        level = 1 - level188    num_switch = int(level * total_num_layers)189    vec = torch.arange(total_num_layers)190    vec = vec % (total_num_layers // num_switch)191    vec = vec == 0192    if to_flip:193        vec = ~vec194    return vec195 196 197def init_attention_processors(pipeline: StableDiffusionXLPipeline, style_aligned_args: StyleAlignedArgs | None = None):198    attn_procs = {}199    unet = pipeline.unet200    number_of_self, number_of_cross = 0, 0201    num_self_layers = len([name for name in unet.attn_processors.keys() if 'attn1' in name])202    if style_aligned_args is None:203        only_self_vec = _get_switch_vec(num_self_layers, 1)204    else:205        only_self_vec = _get_switch_vec(num_self_layers, style_aligned_args.only_self_level)206    for i, name in enumerate(unet.attn_processors.keys()):207        is_self_attention = 'attn1' in name208        if is_self_attention:209            number_of_self += 1210            if style_aligned_args is None or only_self_vec[i // 2]:211                attn_procs[name] = DefaultAttentionProcessor()212            else:213                attn_procs[name] = SharedAttentionProcessor(style_aligned_args)214 215        else:216            number_of_cross += 1217            attn_procs[name] = DefaultAttentionProcessor()218 219    unet.set_attn_processor(attn_procs)220 221 222def register_shared_norm(pipeline: StableDiffusionXLPipeline,223                         share_group_norm: bool = True,224                         share_layer_norm: bool = True, ):225    def register_norm_forward(norm_layer: nn.GroupNorm | nn.LayerNorm) -> nn.GroupNorm | nn.LayerNorm:226        if not hasattr(norm_layer, 'orig_forward'):227            setattr(norm_layer, 'orig_forward', norm_layer.forward)228        orig_forward = norm_layer.orig_forward229 230        def forward_(hidden_states: T) -> T:231            n = hidden_states.shape[-2]232            hidden_states = concat_first(hidden_states, dim=-2)233            hidden_states = orig_forward(hidden_states)234            return hidden_states[..., :n, :]235 236        norm_layer.forward = forward_237        return norm_layer238 239    def get_norm_layers(pipeline_, norm_layers_: dict[str, list[nn.GroupNorm | nn.LayerNorm]]):240        if isinstance(pipeline_, nn.LayerNorm) and share_layer_norm:241            norm_layers_['layer'].append(pipeline_)242        if isinstance(pipeline_, nn.GroupNorm) and share_group_norm:243            norm_layers_['group'].append(pipeline_)244        else:245            for layer in pipeline_.children():246                get_norm_layers(layer, norm_layers_)247 248    norm_layers = {'group': [], 'layer': []}249    get_norm_layers(pipeline.unet, norm_layers)250    return [register_norm_forward(layer) for layer in norm_layers['group']] + [register_norm_forward(layer) for layer in251                                                                               norm_layers['layer']]252 253 254class Handler:255 256    def register(self, style_aligned_args: StyleAlignedArgs, ):257        self.norm_layers = register_shared_norm(self.pipeline, style_aligned_args.share_group_norm,258                                                style_aligned_args.share_layer_norm)259        init_attention_processors(self.pipeline, style_aligned_args)260 261    def remove(self):262        for layer in self.norm_layers:263            layer.forward = layer.orig_forward264        self.norm_layers = []265        init_attention_processors(self.pipeline, None)266 267    def __init__(self, pipeline: StableDiffusionXLPipeline):268        self.pipeline = pipeline269        self.norm_layers = []270