Download architecture.py from thomasdekerf/implicitstainer-hemit: direct link, hf CLI and curl.
- Browser
- Download file 2.43 kB
-
https://huggingface.co/thomasdekerf/implicitstainer-hemit/resolve/main/architecture.py
- Command line
-
hf download hf://thomasdekerf/implicitstainer-hemit/architecture.py
-
curl -L -o architecture.py https://huggingface.co/thomasdekerf/implicitstainer-hemit/resolve/main/architecture.py
2.43 kB
| """CNN variant of the released ImplicitStainer coordinate regressor. | |
| See IMPLICITSTAINER_NOTICE.md. The released query_rgb uses nearest feature | |
| sampling plus learned absolute coordinates; it does not execute LIIF's four-way | |
| local ensemble despite retaining that constructor flag. | |
| """ | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| class ResidualBlock(nn.Module): | |
| def __init__(self, width, scale=1.): | |
| super().__init__() | |
| self.body = nn.Sequential(nn.Conv2d(width,width,3,padding=1),nn.ReLU(), | |
| nn.Conv2d(width,width,3,padding=1)) | |
| self.scale = scale | |
| def forward(self,x): | |
| return x+self.scale*self.body(x) | |
| class CoordinateMLP(nn.Module): | |
| def __init__(self, inputs, outputs, hidden): | |
| super().__init__() | |
| layers = [] | |
| for width in hidden: | |
| layers.extend([nn.Linear(inputs,width),nn.PReLU()]) | |
| inputs = width | |
| layers.append(nn.Linear(inputs,outputs)) | |
| self.layers = nn.Sequential(*layers) | |
| def forward(self,x): | |
| return self.layers(x) | |
| class ImplicitStainer(nn.Module): | |
| def __init__(self,in_channels=17,width=64,blocks=16,hidden=(256,256,256,256),query_chunk=4096): | |
| super().__init__() | |
| self.head = nn.Conv2d(in_channels,width,3,padding=1) | |
| self.body = nn.Sequential(*[ResidualBlock(width) for _ in range(blocks)],nn.Conv2d(width,width,3,padding=1)) | |
| self.imnet = CoordinateMLP(width*2,3,hidden) | |
| self.imnet1 = CoordinateMLP(2,width,hidden) | |
| self.query_chunk = query_chunk | |
| def forward(self, x): | |
| b,_,h,w = x.shape | |
| head = self.head(x*2-1) | |
| feature = self.body(head)+head | |
| ys = (torch.arange(h,device=x.device,dtype=x.dtype)+.5)*2/h-1 | |
| xs = (torch.arange(w,device=x.device,dtype=x.dtype)+.5)*2/w-1 | |
| coordinates = torch.stack(torch.meshgrid(ys,xs,indexing='ij'),dim=-1).reshape(-1,2) | |
| chunks = [] | |
| for coords in coordinates.split(self.query_chunk): | |
| coords = coords[None].expand(b,-1,-1) | |
| values = F.grid_sample(feature,coords.flip(-1).unsqueeze(1),mode='nearest',align_corners=False) | |
| values = values[:,:,0,:].transpose(1,2) | |
| position = self.imnet1(coords) | |
| chunks.append(self.imnet(torch.cat((values,position),dim=-1))) | |
| return (torch.cat(chunks,dim=1).transpose(1,2).reshape(b,3,h,w)+1)/2 | |