aboutsummaryrefslogtreecommitdiffstats
path: root/look2hear/utils/torch_utils.py
diff options
context:
space:
mode:
authorKai Li (李凯) <tsinghua.kaili@gmail.com>2024-09-07 01:23:39 +0800
committerKai Li (李凯) <tsinghua.kaili@gmail.com>2024-09-07 01:23:39 +0800
commitd72b12cf8b5d9b80acdbe8082f0451389afc6407 (patch)
tree4f8f0554de3e4513fee7afa0cd2707338fe99011 /look2hear/utils/torch_utils.py
downloadapollo-gfx803-d72b12cf8b5d9b80acdbe8082f0451389afc6407.tar.gz
First Commit
Diffstat (limited to 'look2hear/utils/torch_utils.py')
-rw-r--r--look2hear/utils/torch_utils.py49
1 files changed, 49 insertions, 0 deletions
diff --git a/look2hear/utils/torch_utils.py b/look2hear/utils/torch_utils.py
new file mode 100644
index 0000000..7c7cc70
--- /dev/null
+++ b/look2hear/utils/torch_utils.py
@@ -0,0 +1,49 @@
+###
+# Author: Kai Li
+# Date: 2021-06-18 17:29:21
+# LastEditors: Kai Li
+# LastEditTime: 2021-06-21 23:52:52
+###
+
+import torch
+import torch.nn as nn
+
+
+def pad_x_to_y(x, y, axis: int = -1):
+ if axis != -1:
+ raise NotImplementedError
+ inp_len = y.shape[axis]
+ output_len = x.shape[axis]
+ return nn.functional.pad(x, [0, inp_len - output_len])
+
+
+def shape_reconstructed(reconstructed, size):
+ if len(size) == 1:
+ return reconstructed.squeeze(0)
+ return reconstructed
+
+
+def tensors_to_device(tensors, device):
+ """Transfer tensor, dict or list of tensors to device.
+
+ Args:
+ tensors (:class:`torch.Tensor`): May be a single, a list or a
+ dictionary of tensors.
+ device (:class: `torch.device`): the device where to place the tensors.
+
+ Returns:
+ Union [:class:`torch.Tensor`, list, tuple, dict]:
+ Same as input but transferred to device.
+ Goes through lists and dicts and transfers the torch.Tensor to
+ device. Leaves the rest untouched.
+ """
+ if isinstance(tensors, torch.Tensor):
+ return tensors.to(device)
+ elif isinstance(tensors, (list, tuple)):
+ return [tensors_to_device(tens, device) for tens in tensors]
+ elif isinstance(tensors, dict):
+ for key in tensors.keys():
+ tensors[key] = tensors_to_device(tensors[key], device)
+ return tensors
+ else:
+ return tensors