MCPcopy
hub / github.com/OpenPPL/ppq / convert_any_to_torch_tensor

Function convert_any_to_torch_tensor

ppq/core/data.py:266–291  ·  view source on GitHub ↗
(
    x: Union[torch.Tensor, np.ndarray, int, float, list, tuple],
    accept_none: bool=True, dtype: torch.dtype=None, device='cpu')

Source from the content-addressed store, hash-verified

264
265
266def convert_any_to_torch_tensor(
267 x: Union[torch.Tensor, np.ndarray, int, float, list, tuple],
268 accept_none: bool=True, dtype: torch.dtype=None, device='cpu') -> torch.Tensor:
269 if x is None and accept_none: return None
270 if x is None and not accept_none: raise ValueError('Trying to convert an empty value.')
271 if isinstance(x, list) or isinstance(x, tuple):
272 if all([type(element) == int for element in x]):
273 if dtype is None: dtype=torch.int64
274 return torch.tensor(x, dtype=dtype, device=device)
275 elif isinstance(x, int):
276 if dtype is None: dtype=torch.int64
277 return torch.tensor(x, dtype=dtype, device=device)
278 elif isinstance(x, float):
279 if dtype is None: dtype=torch.float32
280 return torch.tensor(x, dtype=dtype, device=device)
281 elif isinstance(x, torch.Tensor):
282 if dtype is not None: x = x.type(dtype)
283 if device is not None: x = x.to(device)
284 return x
285 elif isinstance(x, np.ndarray):
286 if dtype is None:
287 dtype = DataType.convert_from_numpy(x.dtype)
288 dtype = DataType.to_torch(dtype)
289 return torch.tensor(x.copy(), dtype=dtype, device=device)
290 else:
291 raise TypeError(f'input value {x}({type(x)}) can not be converted as torch tensor.')
292
293
294def convert_primary_type_to_list(

Callers 15

TestAlignmentFunction · 0.90
QuantZoo_OCR.pyFile · 0.90
quantize.pyFile · 0.90
prepare_modelMethod · 0.90
insert_quantize_nodeMethod · 0.90
insert_quantize_nodeMethod · 0.90
format_sliceMethod · 0.90
format_parameterMethod · 0.90
convert_to_tensorMethod · 0.90

Calls 5

typeMethod · 0.80
toMethod · 0.80
convert_from_numpyMethod · 0.80
to_torchMethod · 0.80
copyMethod · 0.45

Tested by

no test coverage detected