Apply a sequential model with memblocks to the given input. Args: - model: nn.Sequential of blocks to apply - x: input data, of dimensions NTCHW - parallel: if True, parallelize over timesteps (fast but uses O(T) memory) if False, each timestep will be processed sequenti
(model, x, parallel, show_progress_bar, mem=None)
| 93 | # ---------------------------- |
| 94 | |
| 95 | def apply_model_with_memblocks(model, x, parallel, show_progress_bar, mem=None): |
| 96 | """ |
| 97 | Apply a sequential model with memblocks to the given input. |
| 98 | Args: |
| 99 | - model: nn.Sequential of blocks to apply |
| 100 | - x: input data, of dimensions NTCHW |
| 101 | - parallel: if True, parallelize over timesteps (fast but uses O(T) memory) |
| 102 | if False, each timestep will be processed sequentially (slow but uses O(1) memory) |
| 103 | - show_progress_bar: if True, enables tqdm progressbar display |
| 104 | |
| 105 | Returns NTCHW tensor of output data. |
| 106 | """ |
| 107 | assert x.ndim == 5, f"TAEHV operates on NTCHW tensors, but got {x.ndim}-dim tensor" |
| 108 | N, T, C, H, W = x.shape |
| 109 | if parallel: |
| 110 | x = x.reshape(N*T, C, H, W) |
| 111 | for b in tqdm(model, disable=not show_progress_bar): |
| 112 | if isinstance(b, MemBlock): |
| 113 | NT, C, H, W = x.shape |
| 114 | T = NT // N |
| 115 | _x = x.reshape(N, T, C, H, W) |
| 116 | mem = F.pad(_x, (0,0,0,0,0,0,1,0), value=0)[:,:T].reshape(x.shape) |
| 117 | x = b(x, mem) |
| 118 | else: |
| 119 | x = b(x) |
| 120 | NT, C, H, W = x.shape |
| 121 | T = NT // N |
| 122 | x = x.view(N, T, C, H, W) |
| 123 | else: |
| 124 | out = [] |
| 125 | work_queue = [TWorkItem(xt, 0) for t, xt in enumerate(x.reshape(N, T * C, H, W).chunk(T, dim=1))] |
| 126 | progress_bar = tqdm(range(T), disable=not show_progress_bar) |
| 127 | while work_queue: |
| 128 | xt, i = work_queue.pop(0) |
| 129 | if i == 0: |
| 130 | progress_bar.update(1) |
| 131 | if i == len(model): |
| 132 | out.append(xt) |
| 133 | else: |
| 134 | b = model[i] |
| 135 | if isinstance(b, MemBlock): |
| 136 | if mem[i] is None: |
| 137 | xt_new = b(xt, xt * 0) |
| 138 | mem[i] = xt |
| 139 | else: |
| 140 | xt_new = b(xt, mem[i]) |
| 141 | mem[i].copy_(xt) |
| 142 | work_queue.insert(0, TWorkItem(xt_new, i+1)) |
| 143 | elif isinstance(b, TPool): |
| 144 | if mem[i] is None: |
| 145 | mem[i] = [] |
| 146 | mem[i].append(xt) |
| 147 | if len(mem[i]) > b.stride: |
| 148 | raise ValueError("TPool internal state invalid.") |
| 149 | elif len(mem[i]) == b.stride: |
| 150 | N_, C_, H_, W_ = xt.shape |
| 151 | xt = b(torch.cat(mem[i], 1).view(N_*b.stride, C_, H_, W_)) |
| 152 | mem[i] = [] |