|
| 1 | +"""Shared backend inference and array-conversion helpers.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import autoray as ar |
| 7 | + |
| 8 | +_NUMPY_DTYPE_MAP = { |
| 9 | + "complex128": np.complex128, |
| 10 | + "complex64": np.complex64, |
| 11 | + "float64": np.float64, |
| 12 | + "float32": np.float32, |
| 13 | + "float16": np.float16, |
| 14 | + "int64": np.int64, |
| 15 | + "int32": np.int32, |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +def resolve_backend_sample_data(obj): |
| 20 | + """Return representative array data from an array- or gate-like object.""" |
| 21 | + if obj is None: |
| 22 | + return None |
| 23 | + |
| 24 | + if hasattr(obj, "shape") and hasattr(obj, "dtype"): |
| 25 | + return obj |
| 26 | + |
| 27 | + data = getattr(obj, "data", None) |
| 28 | + if hasattr(data, "shape") and hasattr(data, "dtype"): |
| 29 | + return data |
| 30 | + |
| 31 | + return None |
| 32 | + |
| 33 | + |
| 34 | +def resolve_backend_sample_data_from_tn(tn): |
| 35 | + """Return representative array data from a tensor network-like object.""" |
| 36 | + if tn is None: |
| 37 | + return None |
| 38 | + |
| 39 | + tensor_map = getattr(tn, "tensor_map", None) |
| 40 | + if tensor_map: |
| 41 | + first_tensor = next(iter(tensor_map.values())) |
| 42 | + data = getattr(first_tensor, "data", None) |
| 43 | + if hasattr(data, "shape") and hasattr(data, "dtype"): |
| 44 | + return data |
| 45 | + |
| 46 | + try: |
| 47 | + first_tensor = next(iter(tn)) |
| 48 | + except (TypeError, StopIteration): |
| 49 | + return None |
| 50 | + |
| 51 | + data = getattr(first_tensor, "data", None) |
| 52 | + if hasattr(data, "shape") and hasattr(data, "dtype"): |
| 53 | + return data |
| 54 | + |
| 55 | + return None |
| 56 | + |
| 57 | + |
| 58 | +def infer_backend_and_dtype(sample_data): |
| 59 | + """Infer backend name and dtype name from sample tensor data.""" |
| 60 | + if sample_data is None: |
| 61 | + raise ValueError("Cannot infer backend: sample_data is None.") |
| 62 | + |
| 63 | + dtype_name = ar.get_dtype_name(sample_data) |
| 64 | + backend = ar.infer_backend(sample_data) |
| 65 | + return backend, dtype_name |
| 66 | + |
| 67 | + |
| 68 | +def _build_to_numpy(sample_data, dtype_name, *, cast_complex_to_real=False): |
| 69 | + del sample_data |
| 70 | + if dtype_name not in _NUMPY_DTYPE_MAP: |
| 71 | + raise ValueError(f"Unsupported dtype '{dtype_name}' for numpy backend.") |
| 72 | + dtype = _NUMPY_DTYPE_MAP[dtype_name] |
| 73 | + |
| 74 | + def _to_numpy(x, dtype=dtype, cast_complex_to_real=cast_complex_to_real): |
| 75 | + arr = np.asarray(x) |
| 76 | + if cast_complex_to_real and np.issubdtype(dtype, np.floating) and np.iscomplexobj(arr): |
| 77 | + arr = arr.real |
| 78 | + return np.asarray(arr, dtype=dtype) |
| 79 | + |
| 80 | + return _to_numpy |
| 81 | + |
| 82 | + |
| 83 | +def _build_to_torch(sample_data, dtype_name, *, cast_complex_to_real=False): |
| 84 | + import torch # pylint: disable=import-outside-toplevel |
| 85 | + |
| 86 | + dtype_map = { |
| 87 | + "complex128": torch.complex128, |
| 88 | + "complex64": torch.complex64, |
| 89 | + "float64": torch.float64, |
| 90 | + "float32": torch.float32, |
| 91 | + "float16": torch.float16, |
| 92 | + "int64": torch.int64, |
| 93 | + "int32": torch.int32, |
| 94 | + } |
| 95 | + if dtype_name not in dtype_map: |
| 96 | + raise ValueError(f"Unsupported dtype '{dtype_name}' for torch backend.") |
| 97 | + |
| 98 | + dtype = getattr(sample_data, "dtype", None) or dtype_map[dtype_name] |
| 99 | + device = getattr(sample_data, "device", None) |
| 100 | + |
| 101 | + def _to_torch( |
| 102 | + x, |
| 103 | + dtype=dtype, |
| 104 | + device=device, |
| 105 | + cast_complex_to_real=cast_complex_to_real, |
| 106 | + ): |
| 107 | + if isinstance(x, torch.Tensor): |
| 108 | + arr = x |
| 109 | + if device is not None: |
| 110 | + arr = arr.to(device=device) |
| 111 | + else: |
| 112 | + if isinstance(x, np.ndarray) and (not x.flags.writeable): |
| 113 | + x = np.array(x, copy=True) |
| 114 | + kwargs = {"device": device} if device is not None else {} |
| 115 | + arr = torch.as_tensor(x, **kwargs) |
| 116 | + |
| 117 | + if cast_complex_to_real and dtype.is_floating_point and torch.is_complex(arr): |
| 118 | + arr = arr.real |
| 119 | + |
| 120 | + kwargs = {"dtype": dtype} |
| 121 | + if device is not None: |
| 122 | + kwargs["device"] = device |
| 123 | + return torch.as_tensor(arr, **kwargs) |
| 124 | + |
| 125 | + return _to_torch |
| 126 | + |
| 127 | + |
| 128 | +def _build_to_cupy(sample_data, dtype_name, *, cast_complex_to_real=False): |
| 129 | + import cupy as cp # pylint: disable=import-outside-toplevel |
| 130 | + |
| 131 | + dtype_map = { |
| 132 | + "complex128": cp.complex128, |
| 133 | + "complex64": cp.complex64, |
| 134 | + "float64": cp.float64, |
| 135 | + "float32": cp.float32, |
| 136 | + "float16": cp.float16, |
| 137 | + "int64": cp.int64, |
| 138 | + "int32": cp.int32, |
| 139 | + } |
| 140 | + if dtype_name not in dtype_map: |
| 141 | + raise ValueError(f"Unsupported dtype '{dtype_name}' for cupy backend.") |
| 142 | + |
| 143 | + dtype = getattr(sample_data, "dtype", None) or dtype_map[dtype_name] |
| 144 | + device = getattr(sample_data, "device", None) |
| 145 | + |
| 146 | + def _to_cupy( |
| 147 | + x, |
| 148 | + dtype=dtype, |
| 149 | + device=device, |
| 150 | + cast_complex_to_real=cast_complex_to_real, |
| 151 | + ): |
| 152 | + if device is None: |
| 153 | + arr = cp.asarray(x) |
| 154 | + else: |
| 155 | + with device: |
| 156 | + arr = cp.asarray(x) |
| 157 | + |
| 158 | + if cast_complex_to_real and cp.issubdtype(dtype, cp.floating) and cp.iscomplexobj(arr): |
| 159 | + arr = arr.real |
| 160 | + |
| 161 | + return arr.astype(dtype, copy=False) |
| 162 | + |
| 163 | + return _to_cupy |
| 164 | + |
| 165 | + |
| 166 | +def dispatch_backend_converter( |
| 167 | + *, |
| 168 | + backend, |
| 169 | + dtype_name, |
| 170 | + sample_data, |
| 171 | + cast_complex_to_real=False, |
| 172 | +): |
| 173 | + """Return backend converter callable for the specified backend and dtype.""" |
| 174 | + if sample_data is None: |
| 175 | + raise ValueError("Cannot infer backend: tensor network has no tensors.") |
| 176 | + |
| 177 | + if backend == "numpy": |
| 178 | + return _build_to_numpy( |
| 179 | + sample_data, |
| 180 | + dtype_name, |
| 181 | + cast_complex_to_real=cast_complex_to_real, |
| 182 | + ) |
| 183 | + if backend == "torch": |
| 184 | + return _build_to_torch( |
| 185 | + sample_data, |
| 186 | + dtype_name, |
| 187 | + cast_complex_to_real=cast_complex_to_real, |
| 188 | + ) |
| 189 | + if backend == "cupy": |
| 190 | + return _build_to_cupy( |
| 191 | + sample_data, |
| 192 | + dtype_name, |
| 193 | + cast_complex_to_real=cast_complex_to_real, |
| 194 | + ) |
| 195 | + |
| 196 | + raise ValueError(f"Unsupported backend: {backend}") |
| 197 | + |
| 198 | + |
| 199 | +def infer_backend_converter_from_sample( |
| 200 | + sample_data, |
| 201 | + *, |
| 202 | + cast_complex_to_real=False, |
| 203 | +): |
| 204 | + """Infer and return converter callable from representative sample data.""" |
| 205 | + if sample_data is None: |
| 206 | + return None |
| 207 | + |
| 208 | + backend, dtype_name = infer_backend_and_dtype(sample_data) |
| 209 | + return dispatch_backend_converter( |
| 210 | + backend=backend, |
| 211 | + dtype_name=dtype_name, |
| 212 | + sample_data=sample_data, |
| 213 | + cast_complex_to_real=cast_complex_to_real, |
| 214 | + ) |
0 commit comments