(fn: Callable, chunk_size: int, *args, **kwargs)
| 21 | |
| 22 | |
| 23 | def split_batch_fwd(fn: Callable, chunk_size: int, *args, **kwargs): |
| 24 | batch_size = next(x for x in (*args, *kwargs.values()) if isinstance(x, torch.Tensor)).shape[0] |
| 25 | n_chunks = batch_size // chunk_size + (batch_size % chunk_size > 0) |
| 26 | splited_args = tuple(arg.split(chunk_size, dim=0) if isinstance(arg, torch.Tensor) else [arg] * n_chunks for arg in args) |
| 27 | splited_kwargs = {k: [v.split(chunk_size, dim=0) if isinstance(v, torch.Tensor) else [v] * n_chunks] for k, v in kwargs.items()} |
| 28 | results = [] |
| 29 | for i in range(n_chunks): |
| 30 | chunk_args = tuple(arg[i] for arg in splited_args) |
| 31 | chunk_kwargs = {k: v[i] for k, v in splited_kwargs.items()} |
| 32 | results.append(fn(*chunk_args, **chunk_kwargs)) |
| 33 | |
| 34 | if isinstance(results[0], tuple): |
| 35 | return tuple(torch.cat(r, dim=0) for r in zip(*results)) |
| 36 | else: |
| 37 | return torch.cat(results, dim=0) |
| 38 | |
| 39 | |
| 40 | def _pad_inf(x_: torch.Tensor): |
no test coverage detected