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