MCPcopy Create free account
hub / github.com/CompVis/diff2flow / LoRAAdapterConv

Class LoRAAdapterConv

diff2flow/lora.py:121–171  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

119
120
121class LoRAAdapterConv(nn.Module):
122 def __init__(
123 self,
124 in_channels: int,
125 out_channels: int,
126 kernel_size: Union[int, Tuple[int, int]],
127 stride: Union[int, Tuple[int, int]],
128 padding: Union[int, Tuple[int, int]],
129 data_provider: DataProvider,
130 c_dim: int,
131 rank: int = None,
132 lora_scale: float = 1.0,
133 ):
134 super().__init__()
135
136 # self.lora_scale = alpha / rank
137 self.lora_scale = lora_scale
138 self.c_dim = c_dim
139
140 self.data_provider = data_provider
141
142 self.W = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
143 for p in self.W.parameters():
144 p.requires_grad_(False)
145
146 self.A = nn.Conv2d(in_channels, rank, kernel_size, stride, padding, bias=False)
147 self.B = nn.Conv2d(rank, out_channels, kernel_size=1, stride=1, padding=0, bias=False)
148
149 nn.init.zeros_(self.B.weight)
150 nn.init.kaiming_normal_(self.A.weight, a=1)
151
152 self.beta = nn.Conv2d(c_dim, rank, kernel_size=1, bias=False)
153 self.gamma = nn.Conv2d(c_dim, rank, kernel_size=1, bias=False)
154
155 def forward(self, x):
156 """
157 Args:
158 x (torch.Tensor): In shape of (B, C, H, W)
159 """
160 w_out = self.W(x)
161 a_out = self.A(x)
162
163 # inject conditioning into LoRA
164 c = self.data_provider.get_batch(a_out)
165 element_shift = self.beta(c)
166 element_scale = self.gamma(c) + 1
167 a_cond = a_out * element_scale + element_shift
168
169 b_out = self.B(a_cond)
170
171 return w_out + b_out * self.lora_scale

Callers 1

add_lora_to_unetMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected