| 47 | _constant_cache = dict() |
| 48 | |
| 49 | def constant(value, shape=None, dtype=None, device=None, memory_format=None): |
| 50 | value = np.asarray(value) |
| 51 | if shape is not None: |
| 52 | shape = tuple(shape) |
| 53 | if dtype is None: |
| 54 | dtype = torch.get_default_dtype() |
| 55 | if device is None: |
| 56 | device = torch.device('cpu') |
| 57 | if memory_format is None: |
| 58 | memory_format = torch.contiguous_format |
| 59 | |
| 60 | key = (value.shape, value.dtype, value.tobytes(), shape, dtype, device, memory_format) |
| 61 | tensor = _constant_cache.get(key, None) |
| 62 | if tensor is None: |
| 63 | tensor = torch.as_tensor(value.copy(), dtype=dtype, device=device) |
| 64 | if shape is not None: |
| 65 | tensor, _ = torch.broadcast_tensors(tensor, torch.empty(shape)) |
| 66 | tensor = tensor.contiguous(memory_format=memory_format) |
| 67 | _constant_cache[key] = tensor |
| 68 | return tensor |
| 69 | |
| 70 | |
| 71 | # ---------------------------------------------------------------------------- |