| 3 | |
| 4 | |
| 5 | class TileWorker: |
| 6 | def __init__(self): |
| 7 | pass |
| 8 | |
| 9 | |
| 10 | def mask(self, height, width, border_width): |
| 11 | # Create a mask with shape (height, width). |
| 12 | # The centre area is filled with 1, and the border line is filled with values in range (0, 1]. |
| 13 | x = torch.arange(height).repeat(width, 1).T |
| 14 | y = torch.arange(width).repeat(height, 1) |
| 15 | mask = torch.stack([x + 1, height - x, y + 1, width - y]).min(dim=0).values |
| 16 | mask = (mask / border_width).clip(0, 1) |
| 17 | return mask |
| 18 | |
| 19 | |
| 20 | def tile(self, model_input, tile_size, tile_stride, tile_device, tile_dtype): |
| 21 | # Convert a tensor (b, c, h, w) to (b, c, tile_size, tile_size, tile_num) |
| 22 | batch_size, channel, _, _ = model_input.shape |
| 23 | model_input = model_input.to(device=tile_device, dtype=tile_dtype) |
| 24 | unfold_operator = torch.nn.Unfold( |
| 25 | kernel_size=(tile_size, tile_size), |
| 26 | stride=(tile_stride, tile_stride) |
| 27 | ) |
| 28 | model_input = unfold_operator(model_input) |
| 29 | model_input = model_input.view((batch_size, channel, tile_size, tile_size, -1)) |
| 30 | |
| 31 | return model_input |
| 32 | |
| 33 | |
| 34 | def tiled_inference(self, forward_fn, model_input, tile_batch_size, inference_device, inference_dtype, tile_device, tile_dtype): |
| 35 | # Call y=forward_fn(x) for each tile |
| 36 | tile_num = model_input.shape[-1] |
| 37 | model_output_stack = [] |
| 38 | |
| 39 | for tile_id in range(0, tile_num, tile_batch_size): |
| 40 | |
| 41 | # process input |
| 42 | tile_id_ = min(tile_id + tile_batch_size, tile_num) |
| 43 | x = model_input[:, :, :, :, tile_id: tile_id_] |
| 44 | x = x.to(device=inference_device, dtype=inference_dtype) |
| 45 | x = rearrange(x, "b c h w n -> (n b) c h w") |
| 46 | |
| 47 | # process output |
| 48 | y = forward_fn(x) |
| 49 | y = rearrange(y, "(n b) c h w -> b c h w n", n=tile_id_-tile_id) |
| 50 | y = y.to(device=tile_device, dtype=tile_dtype) |
| 51 | model_output_stack.append(y) |
| 52 | |
| 53 | model_output = torch.concat(model_output_stack, dim=-1) |
| 54 | return model_output |
| 55 | |
| 56 | |
| 57 | def io_scale(self, model_output, tile_size): |
| 58 | # Determine the size modification happened in forward_fn |
| 59 | # We only consider the same scale on height and width. |
| 60 | io_scale = model_output.shape[2] / tile_size |
| 61 | return io_scale |
| 62 |
no outgoing calls
no test coverage detected