Model variable as a Numpy array.
| 670 | |
| 671 | |
| 672 | class NumpyVariable(Variable): |
| 673 | """Model variable as a Numpy array.""" |
| 674 | |
| 675 | def __init__(self, array): |
| 676 | self.array = array |
| 677 | |
| 678 | @property |
| 679 | def shape(self) -> List[int]: |
| 680 | return self.array.shape |
| 681 | |
| 682 | @property |
| 683 | def dtype(self) -> str: |
| 684 | return self.array.dtype.name |
| 685 | |
| 686 | def numpy(self) -> np.ndarray: |
| 687 | return self.array |
| 688 | |
| 689 | def num_bytes(self) -> int: |
| 690 | return self.array.nbytes |
| 691 | |
| 692 | def to_bytes(self) -> bytes: |
| 693 | return self.array.tobytes() |
| 694 | |
| 695 | def _to(self, dtype: str) -> Variable: |
| 696 | if dtype == "bfloat16": |
| 697 | if not torch_is_available: |
| 698 | raise RuntimeError( |
| 699 | "Converting to bfloat16 requires torch to be installed" |
| 700 | ) |
| 701 | return PyTorchVariable.from_numpy(self.array).to(dtype) |
| 702 | |
| 703 | dtype = np.dtype(dtype) |
| 704 | self.array = self.array.astype(dtype) |
| 705 | return self |
| 706 | |
| 707 | def _equal(self, other) -> bool: |
| 708 | a = self.array |
| 709 | b = other.array |
| 710 | return a is b or ( |
| 711 | a.dtype == b.dtype |
| 712 | and a.shape == b.shape |
| 713 | and a.flat[0] == b.flat[0] |
| 714 | and np.array_equal(a, b) |
| 715 | ) |
| 716 | |
| 717 | |
| 718 | class PyTorchVariable(Variable): |