(
inputs: SampleState,
model: ModelState,
prediction_mode: Literal["parallel", "autoregressive"],
flow_resolution: int = 256,
ar_downsampling_factor: int = 8,
enable_profiling: bool = False,
)
| 80 | |
| 81 | @torch.no_grad() |
| 82 | def predict_flow( |
| 83 | inputs: SampleState, |
| 84 | model: ModelState, |
| 85 | prediction_mode: Literal["parallel", "autoregressive"], |
| 86 | flow_resolution: int = 256, |
| 87 | ar_downsampling_factor: int = 8, |
| 88 | enable_profiling: bool = False, |
| 89 | ) -> UInt8[torch.Tensor, "h w c"]: |
| 90 | assert inputs.query is None, "Query point should not be specified for flow prediction." |
| 91 | |
| 92 | # Prepare inputs |
| 93 | if len(inputs.pokes) > 0: |
| 94 | pokes: Float[torch.Tensor, "b l t c"] = torch.tensor(inputs.pokes, device=model.device)[None] |
| 95 | else: |
| 96 | pokes = torch.empty((1, 0, 2, 2), dtype=torch.float32, device=model.device) |
| 97 | poke_pos: Float[torch.Tensor, "b l c"] = pokes[:, :, 0, :] |
| 98 | poke_flow: Float[torch.Tensor, "b l c"] = pokes[:, :, 1, :] - pokes[:, :, 0, :] |
| 99 | query_pos: Float[torch.Tensor, "b l c"] = make_axial_pos_2d(flow_resolution, flow_resolution, device=model.device)[ |
| 100 | None |
| 101 | ] |
| 102 | |
| 103 | with torch.autocast(device_type=model.device.type, dtype=torch.bfloat16): |
| 104 | if prediction_mode == "parallel": |
| 105 | start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) |
| 106 | start.record() |
| 107 | pred: MixtureSameFamily = model.model.predict_parallel( |
| 108 | poke_pos=poke_pos, poke_flow=poke_flow, query_pos=query_pos, camera_static=True, d_img=inputs.d_img |
| 109 | ) |
| 110 | end.record() |
| 111 | torch.cuda.synchronize() |
| 112 | gr.Info( |
| 113 | f"Delay: {start.elapsed_time(end):,.1f} ms ({math.prod(query_pos.shape[:-1]) / (start.elapsed_time(end) / 1e3):,.0f} queries / second)", |
| 114 | duration=2, |
| 115 | ) |
| 116 | flow: Float[torch.Tensor, "b h w c"] = rearrange( |
| 117 | pred.mean, "b (h w) c -> b c h w", h=flow_resolution, w=flow_resolution |
| 118 | ) |
| 119 | elif prediction_mode == "autoregressive": |
| 120 | if ar_downsampling_factor != 1: |
| 121 | ar_flow_resolution = flow_resolution // ar_downsampling_factor |
| 122 | query_pos_ar = make_axial_pos_2d( |
| 123 | ar_flow_resolution, |
| 124 | ar_flow_resolution, |
| 125 | device=model.device, |
| 126 | )[None] |
| 127 | else: |
| 128 | query_pos_ar = query_pos |
| 129 | flow: Float[torch.Tensor, "b h w c"] = rearrange( |
| 130 | model.model.predict_autoregressive( |
| 131 | poke_pos=poke_pos, |
| 132 | poke_flow=poke_flow, |
| 133 | query_pos=query_pos_ar, |
| 134 | camera_static=True, |
| 135 | d_img=inputs.d_img, |
| 136 | randomize_order=True, |
| 137 | ), |
| 138 | "b (h w) c -> b c h w", |
| 139 | h=ar_flow_resolution, |
no test coverage detected