| 152 | |
| 153 | @torch.no_grad() |
| 154 | def find_flat_region(mask): |
| 155 | device = mask.device |
| 156 | kernel_x = torch.Tensor([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]).unsqueeze(0).unsqueeze(0).to(device) |
| 157 | kernel_y = torch.Tensor([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]).unsqueeze(0).unsqueeze(0).to(device) |
| 158 | mask_ = F.pad(mask.unsqueeze(0), (1, 1, 1, 1), mode="replicate") |
| 159 | |
| 160 | grad_x = torch.nn.functional.conv2d(mask_, kernel_x) |
| 161 | grad_y = torch.nn.functional.conv2d(mask_, kernel_y) |
| 162 | return ((abs(grad_x) + abs(grad_y)) == 0).float()[0] |
| 163 | |
| 164 | |
| 165 | class AttnState: |