MCPcopy Create free account
hub / github.com/modelscope/FunASR / force_gatherable

Function force_gatherable

funasr/train_utils/device_funcs.py:29–64  ·  view source on GitHub ↗

Change object to gatherable in torch.nn.DataParallel recursively The difference from to_device() is changing to torch.Tensor if float or int value is found. The restriction to the returned value in DataParallel: The object must be - torch.cuda.Tensor - 1 or more

(data, device)

Source from the content-addressed store, hash-verified

27
28
29def force_gatherable(data, device):
30 """Change object to gatherable in torch.nn.DataParallel recursively
31
32 The difference from to_device() is changing to torch.Tensor if float or int
33 value is found.
34
35 The restriction to the returned value in DataParallel:
36 The object must be
37 - torch.cuda.Tensor
38 - 1 or more dimension. 0-dimension-tensor sends warning.
39 or a list, tuple, dict.
40
41 """
42 if isinstance(data, dict):
43 return {k: force_gatherable(v, device) for k, v in data.items()}
44 # DataParallel can't handle NamedTuple well
45 elif isinstance(data, tuple) and type(data) is not tuple:
46 return type(data)(*[force_gatherable(o, device) for o in data])
47 elif isinstance(data, (list, tuple, set)):
48 return type(data)(force_gatherable(v, device) for v in data)
49 elif isinstance(data, np.ndarray):
50 return force_gatherable(torch.from_numpy(data), device)
51 elif isinstance(data, torch.Tensor):
52 if data.dim() == 0:
53 # To 1-dim array
54 data = data[None]
55 return data.to(device)
56 elif isinstance(data, float):
57 return torch.tensor([data], dtype=torch.float, device=device)
58 elif isinstance(data, int):
59 return torch.tensor([data], dtype=torch.long, device=device)
60 elif data is None:
61 return None
62 else:
63 warnings.warn(f"{type(data)} may not be gatherable by DataParallel")
64 return data

Callers 15

forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90
forwardMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…