(self,
freeze_model='crossattn-kv',
cond_stage_trainable=False,
add_token=False,
*args, **kwargs)
| 105 | |
| 106 | class CustomDiffusion(LatentDiffusion): |
| 107 | def __init__(self, |
| 108 | freeze_model='crossattn-kv', |
| 109 | cond_stage_trainable=False, |
| 110 | add_token=False, |
| 111 | *args, **kwargs): |
| 112 | |
| 113 | self.freeze_model = freeze_model |
| 114 | self.add_token = add_token |
| 115 | self.cond_stage_trainable = cond_stage_trainable |
| 116 | super().__init__(cond_stage_trainable=cond_stage_trainable, *args, **kwargs) |
| 117 | |
| 118 | if self.freeze_model == 'crossattn-kv': |
| 119 | for x in self.model.diffusion_model.named_parameters(): |
| 120 | if 'transformer_blocks' not in x[0]: |
| 121 | x[1].requires_grad = False |
| 122 | elif not ('attn2.to_k' in x[0] or 'attn2.to_v' in x[0]): |
| 123 | x[1].requires_grad = False |
| 124 | else: |
| 125 | x[1].requires_grad = True |
| 126 | elif self.freeze_model == 'crossattn': |
| 127 | for x in self.model.diffusion_model.named_parameters(): |
| 128 | if 'transformer_blocks' not in x[0]: |
| 129 | x[1].requires_grad = False |
| 130 | elif not 'attn2' in x[0]: |
| 131 | x[1].requires_grad = False |
| 132 | else: |
| 133 | x[1].requires_grad = True |
| 134 | |
| 135 | def change_checkpoint(model): |
| 136 | for layer in model.children(): |
| 137 | if type(layer) == BasicTransformerBlock: |
| 138 | layer.checkpoint = False |
| 139 | else: |
| 140 | change_checkpoint(layer) |
| 141 | |
| 142 | change_checkpoint(self.model.diffusion_model) |
| 143 | |
| 144 | def new_forward(self, x, context=None, mask=None): |
| 145 | h = self.heads |
| 146 | crossattn = False |
| 147 | if context is not None: |
| 148 | crossattn = True |
| 149 | q = self.to_q(x) |
| 150 | context = default(context, x) |
| 151 | k = self.to_k(context) |
| 152 | v = self.to_v(context) |
| 153 | |
| 154 | if crossattn: |
| 155 | modifier = torch.ones_like(k) |
| 156 | modifier[:, :1, :] = modifier[:, :1, :]*0. |
| 157 | k = modifier*k + (1-modifier)*k.detach() |
| 158 | v = modifier*v + (1-modifier)*v.detach() |
| 159 | |
| 160 | q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) |
| 161 | sim = einsum('b i d, b j d -> b i j', q, k) * self.scale |
| 162 | attn = sim.softmax(dim=-1) |
| 163 | |
| 164 | out = einsum('b i j, b j d -> b i d', attn, v) |
nothing calls this directly
no outgoing calls
no test coverage detected