Python Tensor, which wraps a swig converted Tensor from CPP Tensor. Args: shape (tuple ): a tuple of integers for the tensor shape. If shape is not specified, the created tensor is called a dummy tensor. device: a swig device. If None, the default host device is
| 70 | |
| 71 | |
| 72 | class Tensor(object): |
| 73 | '''Python Tensor, which wraps a swig converted Tensor from CPP Tensor. |
| 74 | |
| 75 | Args: |
| 76 | shape (tuple<int>): a tuple of integers for the tensor shape. If shape |
| 77 | is not specified, the created tensor is called a dummy tensor. |
| 78 | device: a swig device. If None, the default host device is used. |
| 79 | dtype: data type. currently, most operations only accept float32. |
| 80 | data: a numpy array or swig tensor. |
| 81 | requires_grad: boolean indicator for computing the gradient. |
| 82 | stores_grad: boolean indicator for storing and returning the gradient. |
| 83 | Some intermediate tensors' gradient can be released |
| 84 | during the backward propagation. A tensor may require |
| 85 | grad but not store grad; But if a tensor stores grad |
| 86 | then it must require grad. |
| 87 | ''' |
| 88 | tensor_count = 0 |
| 89 | |
| 90 | def __init__(self, |
| 91 | shape=(), |
| 92 | device=None, |
| 93 | dtype=float32, |
| 94 | data=None, |
| 95 | requires_grad=True, |
| 96 | stores_grad=False, |
| 97 | creator=None, |
| 98 | name=None): |
| 99 | if device is None: |
| 100 | device = get_default_device() |
| 101 | if isinstance(data, np.ndarray): |
| 102 | self.data = CTensor(list(data.shape), device, dtype) |
| 103 | copy_from_numpy(self.data, data) |
| 104 | elif isinstance(data, CTensor): |
| 105 | self.data = data |
| 106 | assert data.device().id() == device.id(), 'not the same device' |
| 107 | else: |
| 108 | self.data = CTensor(list(shape), device, dtype) |
| 109 | |
| 110 | self.shape = tuple(self.data.shape()) |
| 111 | self.device = device |
| 112 | self.dtype = self.data.data_type() |
| 113 | self.requires_grad = requires_grad |
| 114 | self.stores_grad = stores_grad |
| 115 | if name is None: |
| 116 | self.name = 'Dummy#{}'.format(Tensor.tensor_count) |
| 117 | Tensor.tensor_count += 1 |
| 118 | else: |
| 119 | self.name = name |
| 120 | if creator is None: |
| 121 | from . import autograd |
| 122 | self.creator = autograd.Dummy(self, name) |
| 123 | else: |
| 124 | self.creator = creator |
| 125 | |
| 126 | def __getitem__(self, keys): |
| 127 | if type(keys) != tuple: |
| 128 | keys = (keys,) |
| 129 |
no outgoing calls
no test coverage detected