(tensors, reduction=None, clip_value=10000)
| 461 | |
| 462 | |
| 463 | def numpify_tensor_nested(tensors, reduction=None, clip_value=10000): |
| 464 | try: |
| 465 | from modelscope.outputs import ModelOutputBase |
| 466 | except ImportError: |
| 467 | ModelOutputBase = dict |
| 468 | "Numpify `tensors` (even if it's a nested list/tuple of tensors)." |
| 469 | if isinstance(tensors, (Mapping, ModelOutputBase)): |
| 470 | return OrderedDict({ |
| 471 | k: numpify_tensor_nested(t, reduction, clip_value) |
| 472 | for k, t in tensors.items() |
| 473 | }) |
| 474 | if isinstance(tensors, list): |
| 475 | return list( |
| 476 | numpify_tensor_nested(t, reduction, clip_value) for t in tensors) |
| 477 | if isinstance(tensors, tuple): |
| 478 | return tuple( |
| 479 | numpify_tensor_nested(t, reduction, clip_value) for t in tensors) |
| 480 | if isinstance(tensors, torch.Tensor): |
| 481 | t: np.ndarray = tensors.cpu().numpy() |
| 482 | if clip_value is not None: |
| 483 | t = np.where(t > clip_value, clip_value, t) |
| 484 | t = np.where(t < -clip_value, -clip_value, t) |
| 485 | if reduction == 'sum': |
| 486 | return t.sum(dtype=float) |
| 487 | elif reduction == 'mean': |
| 488 | return t.mean(dtype=float) |
| 489 | return t |
| 490 | return tensors |
| 491 | |
| 492 | |
| 493 | def detach_tensor_nested(tensors): |
no test coverage detected
searching dependent graphs…