MCPcopy Create free account
hub / github.com/TimSeizinger/Bokehlicious / LayerNormFunction

Class LayerNormFunction

method/nn_util.py:209–234  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

207 return x1 * x2
208
209class LayerNormFunction(Function):
210
211 @staticmethod
212 def forward(ctx, x, weight, bias, eps):
213 ctx.eps = eps
214 N, C, H, W = x.size()
215 mu = x.mean(1, keepdim=True)
216 var = (x - mu).pow(2).mean(1, keepdim=True)
217 y = (x - mu) / (var + eps).sqrt()
218 ctx.save_for_backward(y, var, weight)
219 y = weight.view(1, C, 1, 1) * y + bias.view(1, C, 1, 1)
220 return y
221
222 @staticmethod
223 def backward(ctx, grad_output):
224 eps = ctx.eps
225
226 N, C, H, W = grad_output.size()
227 y, var, weight = ctx.saved_variables
228 g = grad_output * weight.view(1, C, 1, 1)
229 mean_g = g.mean(dim=1, keepdim=True)
230
231 mean_gy = (g * y).mean(dim=1, keepdim=True)
232 gx = 1. / sqrt(var + eps) * (g - y * mean_gy - mean_g)
233 return gx, (grad_output * y).sum(dim=3).sum(dim=2).sum(dim=0), grad_output.sum(dim=3).sum(dim=2).sum(
234 dim=0), None
235
236class LayerNorm2d(nn.Module):
237

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected