Split a tensor along its last dimension. Arguments: tensor: input tensor. num_partitions: number of partitions to split the tensor or a list of strides (ratios) for each partition. contiguous_split_chunks: If True, make each chunk contiguous
(tensor, num_partitions,
contiguous_split_chunks=False)
| 32 | |
| 33 | |
| 34 | def split_tensor_along_last_dim(tensor, num_partitions, |
| 35 | contiguous_split_chunks=False): |
| 36 | """Split a tensor along its last dimension. |
| 37 | Arguments: |
| 38 | tensor: input tensor. |
| 39 | num_partitions: number of partitions to split the tensor |
| 40 | or a list of strides (ratios) for each partition. |
| 41 | contiguous_split_chunks: If True, make each chunk contiguous |
| 42 | in memory. |
| 43 | """ |
| 44 | # Get the size and dimension. |
| 45 | last_dim = tensor.dim() - 1 |
| 46 | if isinstance(num_partitions, int): |
| 47 | last_dim_size = divide(tensor.size()[last_dim], num_partitions) |
| 48 | # Split. |
| 49 | tensor_list = torch.split(tensor, last_dim_size, dim=last_dim) |
| 50 | elif isinstance(num_partitions, (list, tuple)): |
| 51 | factor = tensor.size()[last_dim] // sum(num_partitions) |
| 52 | tensor_list = torch.split(tensor, [factor * x for x in num_partitions], |
| 53 | dim=last_dim) |
| 54 | else: |
| 55 | raise ValueError('num_partitions must be either int or list/tuple.') |
| 56 | # Note: torch.split does not create contiguous tensors by default. |
| 57 | if contiguous_split_chunks: |
| 58 | return tuple(chunk.contiguous() for chunk in tensor_list) |
| 59 | |
| 60 | return tensor_list |
| 61 | |
| 62 | |
| 63 | class VocabUtility: |
no test coverage detected