-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathcutensornet.pyx
More file actions
4624 lines (3544 loc) · 245 KB
/
Copy pathcutensornet.pyx
File metadata and controls
4624 lines (3544 loc) · 245 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2021-2026, NVIDIA CORPORATION & AFFILIATES
#
# SPDX-License-Identifier: BSD-3-Clause
#
# This code was automatically generated across versions from 23.03.0 to 26.06.0, generator version 0.3.1.dev1668+gb1eb0b259. Do not modify it directly.
cimport cython
cimport cpython
from libcpp.vector cimport vector
from ._utils cimport (get_resource_ptr, get_nested_resource_ptr, nested_resource, nullable_unique_ptr,
get_buffer_pointer, get_resource_ptrs, DeviceAllocType, DeviceFreeType,
cuqnt_alloc_wrapper, cuqnt_free_wrapper, logger_callback_with_data)
from enum import IntEnum as _IntEnum
import warnings as _warnings
from libc.stdlib cimport calloc, free, malloc
from cython cimport view
cimport cpython.buffer
cimport cpython.memoryview
cimport cpython
from libc.string cimport memcmp, memcpy
import numpy as _numpy
cdef __from_data(data, dtype_name, expected_dtype, lowpp_type):
# _numpy.recarray is a subclass of _numpy.ndarray, so implicitly handled here.
if isinstance(data, lowpp_type):
return data
if not isinstance(data, _numpy.ndarray):
raise TypeError("data argument must be a NumPy ndarray")
if data.size != 1:
raise ValueError("data array must have a size of 1")
if data.dtype != expected_dtype:
raise ValueError(f"data array must be of dtype {dtype_name}")
return lowpp_type.from_ptr(data.ctypes.data, not data.flags.writeable, data)
cdef __from_buffer(buffer, size, lowpp_type):
cdef Py_buffer view
if cpython.PyObject_GetBuffer(buffer, &view, cpython.PyBUF_SIMPLE) != 0:
raise TypeError("buffer argument does not support the buffer protocol")
try:
if view.itemsize != 1:
raise ValueError("buffer itemsize must be 1 byte")
if view.len != size:
raise ValueError(f"buffer length must be {size} bytes")
return lowpp_type.from_ptr(<intptr_t><void *>view.buf, not view.readonly, buffer)
finally:
cpython.PyBuffer_Release(&view)
cdef __getbuffer(object self, cpython.Py_buffer *buffer, void *ptr, int size, bint readonly):
buffer.buf = <char *>ptr
buffer.format = 'b'
buffer.internal = NULL
buffer.itemsize = 1
buffer.len = size
buffer.ndim = 1
buffer.obj = self
buffer.readonly = readonly
buffer.shape = &buffer.len
buffer.strides = &buffer.itemsize
buffer.suboffsets = NULL
###############################################################################
# POD
###############################################################################
cdef _get_mps_env_bounds_dtype_offsets():
cdef cutensornetMPSEnvBounds_t pod = cutensornetMPSEnvBounds_t()
return _numpy.dtype({
'names': ['lower_bound', 'upper_bound'],
'formats': [_numpy.int32, _numpy.int32],
'offsets': [
(<intptr_t>&(pod.lowerBound)) - (<intptr_t>&pod),
(<intptr_t>&(pod.upperBound)) - (<intptr_t>&pod),
],
'itemsize': sizeof(cutensornetMPSEnvBounds_t),
})
mps_env_bounds_dtype = _get_mps_env_bounds_dtype_offsets()
cdef class MPSEnvBounds:
"""Empty-initialize an array of `cutensornetMPSEnvBounds_t`.
The resulting object is of length `size` and of dtype `mps_env_bounds_dtype`.
If default-constructed, the instance represents a single struct.
Args:
size (int): number of structs, default=1.
.. seealso:: `cutensornetMPSEnvBounds_t`
"""
cdef:
readonly object _data
def __init__(self, size=1):
arr = _numpy.empty(size, dtype=mps_env_bounds_dtype)
self._data = arr.view(_numpy.recarray)
assert self._data.itemsize == sizeof(cutensornetMPSEnvBounds_t), \
f"itemsize {self._data.itemsize} mismatches struct size { sizeof(cutensornetMPSEnvBounds_t) }"
def __repr__(self):
if self._data.size > 1:
return f"<{__name__}.MPSEnvBounds_Array_{self._data.size} object at {hex(id(self))}>"
else:
return f"<{__name__}.MPSEnvBounds object at {hex(id(self))}>"
@property
def ptr(self):
"""Get the pointer address to the data as Python :class:`int`."""
return self._data.ctypes.data
cdef intptr_t _get_ptr(self):
return self._data.ctypes.data
def __int__(self):
if self._data.size > 1:
raise TypeError("int() argument must be a bytes-like object of size 1. "
"To get the pointer address of an array, use .ptr")
return self._data.ctypes.data
def __len__(self):
return self._data.size
def __eq__(self, other):
cdef object self_data = self._data
if (not isinstance(other, MPSEnvBounds)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype:
return False
return bool((self_data == other._data).all())
def __getbuffer__(self, Py_buffer *buffer, int flags):
cpython.PyObject_GetBuffer(self._data, buffer, flags)
def __releasebuffer__(self, Py_buffer *buffer):
cpython.PyBuffer_Release(buffer)
@property
def lower_bound(self):
"""Union[~_numpy.int32, int]: Site index to the left of environment (allowed range -1 to number of qudits - 1)."""
if self._data.size == 1:
return int(self._data.lower_bound[0])
return self._data.lower_bound
@lower_bound.setter
def lower_bound(self, val):
self._data.lower_bound = val
@property
def upper_bound(self):
"""Union[~_numpy.int32, int]: Site index to the right of environment (allowed range +1 to number of qudits + 1)."""
if self._data.size == 1:
return int(self._data.upper_bound[0])
return self._data.upper_bound
@upper_bound.setter
def upper_bound(self, val):
self._data.upper_bound = val
def __getitem__(self, key):
cdef ssize_t key_
cdef ssize_t size
if isinstance(key, int):
key_ = key
size = self._data.size
if key_ >= size or key_ <= -(size+1):
raise IndexError("index is out of bounds")
if key_ < 0:
key_ += size
return MPSEnvBounds.from_data(self._data[key_:key_+1])
out = self._data[key]
if isinstance(out, _numpy.recarray) and out.dtype == mps_env_bounds_dtype:
return MPSEnvBounds.from_data(out)
return out
def __setitem__(self, key, val):
self._data[key] = val
@staticmethod
def from_buffer(buffer):
"""Create an MPSEnvBounds instance with the memory from the given buffer."""
return MPSEnvBounds.from_data(_numpy.frombuffer(buffer, dtype=mps_env_bounds_dtype))
@staticmethod
def from_data(data):
"""Create an MPSEnvBounds instance wrapping the given NumPy array.
Args:
data (_numpy.ndarray): a 1D array of dtype `mps_env_bounds_dtype` holding the data.
"""
cdef MPSEnvBounds obj = MPSEnvBounds.__new__(MPSEnvBounds)
if not isinstance(data, _numpy.ndarray):
raise TypeError("data argument must be a NumPy ndarray")
if data.ndim != 1:
raise ValueError("data array must be 1D")
if data.dtype != mps_env_bounds_dtype:
raise ValueError("data array must be of dtype mps_env_bounds_dtype")
obj._data = data.view(_numpy.recarray)
return obj
@staticmethod
def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False):
"""Create an MPSEnvBounds instance wrapping the given pointer.
Args:
ptr (intptr_t): pointer address as Python :class:`int` to the data.
size (int): number of structs, default=1.
readonly (bool): whether the data is read-only (to the user). default is `False`.
"""
if ptr == 0:
raise ValueError("ptr must not be null (0)")
cdef MPSEnvBounds obj = MPSEnvBounds.__new__(MPSEnvBounds)
cdef flag = cpython.buffer.PyBUF_READ if readonly else cpython.buffer.PyBUF_WRITE
cdef object buf = cpython.memoryview.PyMemoryView_FromMemory(
<char*>ptr, sizeof(cutensornetMPSEnvBounds_t) * size, flag)
data = _numpy.ndarray(size, buffer=buf, dtype=mps_env_bounds_dtype)
obj._data = data.view(_numpy.recarray)
return obj
###############################################################################
# Enum
###############################################################################
class Status(_IntEnum):
"""
cuTensorNet status type returnsThe type is used for function status
returns. All cuTensorNet library functions return their status, which
can have the following values.
See `cutensornetStatus_t`.
"""
SUCCESS = CUTENSORNET_STATUS_SUCCESS
NOT_INITIALIZED = CUTENSORNET_STATUS_NOT_INITIALIZED
ALLOC_FAILED = CUTENSORNET_STATUS_ALLOC_FAILED
INVALID_VALUE = CUTENSORNET_STATUS_INVALID_VALUE
ARCH_MISMATCH = CUTENSORNET_STATUS_ARCH_MISMATCH
MAPPING_ERROR = CUTENSORNET_STATUS_MAPPING_ERROR
EXECUTION_FAILED = CUTENSORNET_STATUS_EXECUTION_FAILED
INTERNAL_ERROR = CUTENSORNET_STATUS_INTERNAL_ERROR
NOT_SUPPORTED = CUTENSORNET_STATUS_NOT_SUPPORTED
LICENSE_ERROR = CUTENSORNET_STATUS_LICENSE_ERROR
CUBLAS_ERROR = CUTENSORNET_STATUS_CUBLAS_ERROR
CUDA_ERROR = CUTENSORNET_STATUS_CUDA_ERROR
INSUFFICIENT_WORKSPACE = CUTENSORNET_STATUS_INSUFFICIENT_WORKSPACE
INSUFFICIENT_DRIVER = CUTENSORNET_STATUS_INSUFFICIENT_DRIVER
IO_ERROR = CUTENSORNET_STATUS_IO_ERROR
CUTENSOR_VERSION_MISMATCH = CUTENSORNET_STATUS_CUTENSOR_VERSION_MISMATCH
NO_DEVICE_ALLOCATOR = CUTENSORNET_STATUS_NO_DEVICE_ALLOCATOR
ALL_HYPER_SAMPLES_FAILED = CUTENSORNET_STATUS_ALL_HYPER_SAMPLES_FAILED
CUSOLVER_ERROR = CUTENSORNET_STATUS_CUSOLVER_ERROR
DEVICE_ALLOCATOR_ERROR = CUTENSORNET_STATUS_DEVICE_ALLOCATOR_ERROR
DISTRIBUTED_FAILURE = CUTENSORNET_STATUS_DISTRIBUTED_FAILURE
INTERRUPTED = CUTENSORNET_STATUS_INTERRUPTED
class ComputeType(_IntEnum):
"""
Encodes cuTensorNet's compute type (see "User Guide - Accuracy
Guarantees" for details).
See `cutensornetComputeType_t`.
"""
COMPUTE_16F = CUTENSORNET_COMPUTE_16F
COMPUTE_16BF = CUTENSORNET_COMPUTE_16BF
COMPUTE_TF32 = CUTENSORNET_COMPUTE_TF32
COMPUTE_3XTF32 = CUTENSORNET_COMPUTE_3XTF32
COMPUTE_32F = CUTENSORNET_COMPUTE_32F
COMPUTE_64F = CUTENSORNET_COMPUTE_64F
COMPUTE_8U = CUTENSORNET_COMPUTE_8U
COMPUTE_8I = CUTENSORNET_COMPUTE_8I
COMPUTE_32U = CUTENSORNET_COMPUTE_32U
COMPUTE_32I = CUTENSORNET_COMPUTE_32I
class GraphAlgo(_IntEnum):
"""
This enum lists graph algorithms that can be set.
See `cutensornetGraphAlgo_t`.
"""
RB = CUTENSORNET_GRAPH_ALGO_RB
KWAY = CUTENSORNET_GRAPH_ALGO_KWAY
class MemoryModel(_IntEnum):
"""
This enum lists memory models used to determine workspace size.
See `cutensornetMemoryModel_t`.
"""
HEURISTIC = CUTENSORNET_MEMORY_MODEL_HEURISTIC
CUTENSOR = CUTENSORNET_MEMORY_MODEL_CUTENSOR
class OptimizerCost(_IntEnum):
"""
This enum lists various cost functions to optimize with.
See `cutensornetOptimizerCost_t`.
"""
FLOPS = CUTENSORNET_OPTIMIZER_COST_FLOPS
TIME = CUTENSORNET_OPTIMIZER_COST_TIME
TIME_TUNED = CUTENSORNET_OPTIMIZER_COST_TIME_TUNED
class ContractionOptimizerConfigAttribute(_IntEnum):
"""
This enum lists all attributes of a
`cutensornetContractionOptimizerConfig_t` that can be modified.
See `cutensornetContractionOptimizerConfigAttributes_t`.
"""
GRAPH_NUM_PARTITIONS = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_NUM_PARTITIONS
GRAPH_CUTOFF_SIZE = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_CUTOFF_SIZE
GRAPH_ALGORITHM = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_ALGORITHM
GRAPH_IMBALANCE_FACTOR = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_IMBALANCE_FACTOR
GRAPH_NUM_ITERATIONS = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_NUM_ITERATIONS
GRAPH_NUM_CUTS = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GRAPH_NUM_CUTS
RECONFIG_NUM_ITERATIONS = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_RECONFIG_NUM_ITERATIONS
RECONFIG_NUM_LEAVES = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_RECONFIG_NUM_LEAVES
SLICER_DISABLE_SLICING = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SLICER_DISABLE_SLICING
SLICER_MEMORY_MODEL = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SLICER_MEMORY_MODEL
SLICER_MEMORY_FACTOR = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SLICER_MEMORY_FACTOR
SLICER_MIN_SLICES = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SLICER_MIN_SLICES
SLICER_SLICE_FACTOR = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SLICER_SLICE_FACTOR
HYPER_NUM_SAMPLES = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_HYPER_NUM_SAMPLES
HYPER_NUM_THREADS = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_HYPER_NUM_THREADS
SIMPLIFICATION_DISABLE_DR = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SIMPLIFICATION_DISABLE_DR
SEED = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SEED
COST_FUNCTION_OBJECTIVE = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_COST_FUNCTION_OBJECTIVE
CACHE_REUSE_NRUNS = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_CACHE_REUSE_NRUNS
SMART_OPTION = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_SMART_OPTION
GPU_ARCH = CUTENSORNET_CONTRACTION_OPTIMIZER_CONFIG_GPU_ARCH
class ContractionOptimizerInfoAttribute(_IntEnum):
"""
This enum lists all attributes of a
`cutensornetContractionOptimizerInfo_t` that are accessible.
See `cutensornetContractionOptimizerInfoAttributes_t`.
"""
PATH = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_PATH
NUM_SLICES = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_NUM_SLICES
NUM_SLICED_MODES = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_NUM_SLICED_MODES
SLICED_MODE = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_SLICED_MODE
SLICED_EXTENT = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_SLICED_EXTENT
SLICING_CONFIG = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_SLICING_CONFIG
SLICING_OVERHEAD = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_SLICING_OVERHEAD
PHASE1_FLOP_COUNT = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_PHASE1_FLOP_COUNT
FLOP_COUNT = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_FLOP_COUNT
EFFECTIVE_FLOPS_EST = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_EFFECTIVE_FLOPS_EST
RUNTIME_EST = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_RUNTIME_EST
LARGEST_TENSOR = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_LARGEST_TENSOR
INTERMEDIATE_MODES = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_INTERMEDIATE_MODES
NUM_INTERMEDIATE_MODES = CUTENSORNET_CONTRACTION_OPTIMIZER_INFO_NUM_INTERMEDIATE_MODES
class ContractionAutotunePreferenceAttribute(_IntEnum):
"""
DEPRECATED: This enum lists all attributes of a
`cutensornetContractionAutotunePreference_t` that are accessible.
See `cutensornetContractionAutotunePreferenceAttributes_t`.
"""
MAX_ITERATIONS = CUTENSORNET_CONTRACTION_AUTOTUNE_MAX_ITERATIONS
INTERMEDIATE_MODES = CUTENSORNET_CONTRACTION_AUTOTUNE_INTERMEDIATE_MODES
class WorksizePref(_IntEnum):
"""
Workspace preference enumeration.
See `cutensornetWorksizePref_t`.
"""
MIN = CUTENSORNET_WORKSIZE_PREF_MIN
RECOMMENDED = CUTENSORNET_WORKSIZE_PREF_RECOMMENDED
MAX = CUTENSORNET_WORKSIZE_PREF_MAX
class Memspace(_IntEnum):
"""
Memory space enumeration for workspace allocation.
See `cutensornetMemspace_t`.
"""
DEVICE = CUTENSORNET_MEMSPACE_DEVICE
HOST = CUTENSORNET_MEMSPACE_HOST
class WorkspaceKind(_IntEnum):
"""
Type enumeration for workspace allocation.
See `cutensornetWorkspaceKind_t`.
"""
SCRATCH = CUTENSORNET_WORKSPACE_SCRATCH
CACHE = CUTENSORNET_WORKSPACE_CACHE
class TensorSVDConfigAttribute(_IntEnum):
"""
This enum lists all attributes of a `cutensornetTensorSVDConfig_t` that
can be modified.
See `cutensornetTensorSVDConfigAttributes_t`.
"""
ABS_CUTOFF = CUTENSORNET_TENSOR_SVD_CONFIG_ABS_CUTOFF
REL_CUTOFF = CUTENSORNET_TENSOR_SVD_CONFIG_REL_CUTOFF
S_NORMALIZATION = CUTENSORNET_TENSOR_SVD_CONFIG_S_NORMALIZATION
S_PARTITION = CUTENSORNET_TENSOR_SVD_CONFIG_S_PARTITION
ALGO = CUTENSORNET_TENSOR_SVD_CONFIG_ALGO
ALGO_PARAMS = CUTENSORNET_TENSOR_SVD_CONFIG_ALGO_PARAMS
DISCARDED_WEIGHT_CUTOFF = CUTENSORNET_TENSOR_SVD_CONFIG_DISCARDED_WEIGHT_CUTOFF
class TensorSVDPartition(_IntEnum):
"""
This enum lists various partition schemes for singular values.
See `cutensornetTensorSVDPartition_t`.
"""
NONE = CUTENSORNET_TENSOR_SVD_PARTITION_NONE
US = CUTENSORNET_TENSOR_SVD_PARTITION_US
SV = CUTENSORNET_TENSOR_SVD_PARTITION_SV
UV_EQUAL = CUTENSORNET_TENSOR_SVD_PARTITION_UV_EQUAL
class TensorSVDNormalization(_IntEnum):
"""
This enum lists various normalization methods for singular values.
See `cutensornetTensorSVDNormalization_t`.
"""
NONE = CUTENSORNET_TENSOR_SVD_NORMALIZATION_NONE
L1 = CUTENSORNET_TENSOR_SVD_NORMALIZATION_L1
L2 = CUTENSORNET_TENSOR_SVD_NORMALIZATION_L2
LINF = CUTENSORNET_TENSOR_SVD_NORMALIZATION_LINF
class TensorSVDInfoAttribute(_IntEnum):
"""
This enum lists all attributes of a `cutensornetTensorSVDInfo_t`.
See `cutensornetTensorSVDInfoAttributes_t`.
"""
FULL_EXTENT = CUTENSORNET_TENSOR_SVD_INFO_FULL_EXTENT
REDUCED_EXTENT = CUTENSORNET_TENSOR_SVD_INFO_REDUCED_EXTENT
DISCARDED_WEIGHT = CUTENSORNET_TENSOR_SVD_INFO_DISCARDED_WEIGHT
ALGO = CUTENSORNET_TENSOR_SVD_INFO_ALGO
ALGO_STATUS = CUTENSORNET_TENSOR_SVD_INFO_ALGO_STATUS
class GateSplitAlgo(_IntEnum):
"""
This enum lists algorithms for applying a gate tensor to two connected
tensors.
See `cutensornetGateSplitAlgo_t`.
"""
DIRECT = CUTENSORNET_GATE_SPLIT_ALGO_DIRECT
REDUCED = CUTENSORNET_GATE_SPLIT_ALGO_REDUCED
class NetworkAttribute(_IntEnum):
"""
This enum lists all attributes of a `cutensornetNetworkDescriptor_t`
that are accessible.
See `cutensornetNetworkAttributes_t`.
"""
INPUT_TENSORS_NUM_CONSTANT = CUTENSORNET_NETWORK_INPUT_TENSORS_NUM_CONSTANT
INPUT_TENSORS_CONSTANT = CUTENSORNET_NETWORK_INPUT_TENSORS_CONSTANT
INPUT_TENSORS_NUM_CONJUGATED = CUTENSORNET_NETWORK_INPUT_TENSORS_NUM_CONJUGATED
INPUT_TENSORS_CONJUGATED = CUTENSORNET_NETWORK_INPUT_TENSORS_CONJUGATED
INPUT_TENSORS_NUM_REQUIRE_GRAD = CUTENSORNET_NETWORK_INPUT_TENSORS_NUM_REQUIRE_GRAD
INPUT_TENSORS_REQUIRE_GRAD = CUTENSORNET_NETWORK_INPUT_TENSORS_REQUIRE_GRAD
COMPUTE_TYPE = CUTENSORNET_NETWORK_COMPUTE_TYPE
class SmartOption(_IntEnum):
"""
This enum lists various smart optimization options.
See `cutensornetSmartOption_t`.
"""
DISABLED = CUTENSORNET_SMART_OPTION_DISABLED
ENABLED = CUTENSORNET_SMART_OPTION_ENABLED
class TensorSVDAlgo(_IntEnum):
"""
This enum lists various algorithms for SVD.
See `cutensornetTensorSVDAlgo_t`.
"""
GESVD = CUTENSORNET_TENSOR_SVD_ALGO_GESVD
GESVDJ = CUTENSORNET_TENSOR_SVD_ALGO_GESVDJ
GESVDP = CUTENSORNET_TENSOR_SVD_ALGO_GESVDP
GESVDR = CUTENSORNET_TENSOR_SVD_ALGO_GESVDR
class StatePurity(_IntEnum):
"""
This enum captures tensor network state purity.
See `cutensornetStatePurity_t`.
"""
PURE = CUTENSORNET_STATE_PURITY_PURE
MIXED = CUTENSORNET_STATE_PURITY_MIXED
class MarginalAttribute(_IntEnum):
"""
This enum lists attributes associated with computation of a tensor
network state marginal tensor.
See `cutensornetMarginalAttributes_t`.
"""
OPT_NUM_HYPER_SAMPLES = CUTENSORNET_MARGINAL_OPT_NUM_HYPER_SAMPLES
CONFIG_NUM_HYPER_SAMPLES = CUTENSORNET_MARGINAL_CONFIG_NUM_HYPER_SAMPLES
INFO_FLOPS = CUTENSORNET_MARGINAL_INFO_FLOPS
INFO_KIND = CUTENSORNET_MARGINAL_INFO_KIND
class SamplerAttribute(_IntEnum):
"""
This enum lists attributes associated with tensor network state
sampling.
See `cutensornetSamplerAttributes_t`.
"""
OPT_NUM_HYPER_SAMPLES = CUTENSORNET_SAMPLER_OPT_NUM_HYPER_SAMPLES
CONFIG_NUM_HYPER_SAMPLES = CUTENSORNET_SAMPLER_CONFIG_NUM_HYPER_SAMPLES
CONFIG_DETERMINISTIC = CUTENSORNET_SAMPLER_CONFIG_DETERMINISTIC
INFO_FLOPS = CUTENSORNET_SAMPLER_INFO_FLOPS
class AccessorAttribute(_IntEnum):
"""
This enum lists attributes associated with computation of tensor
network state amplitudes.
See `cutensornetAccessorAttributes_t`.
"""
OPT_NUM_HYPER_SAMPLES = CUTENSORNET_ACCESSOR_OPT_NUM_HYPER_SAMPLES
CONFIG_NUM_HYPER_SAMPLES = CUTENSORNET_ACCESSOR_CONFIG_NUM_HYPER_SAMPLES
INFO_FLOPS = CUTENSORNET_ACCESSOR_INFO_FLOPS
class ExpectationAttribute(_IntEnum):
"""
This enum lists attributes associated with computation of a tensor
network state expectation value.
See `cutensornetExpectationAttributes_t`.
"""
OPT_NUM_HYPER_SAMPLES = CUTENSORNET_EXPECTATION_OPT_NUM_HYPER_SAMPLES
CONFIG_NUM_HYPER_SAMPLES = CUTENSORNET_EXPECTATION_CONFIG_NUM_HYPER_SAMPLES
INFO_FLOPS = CUTENSORNET_EXPECTATION_INFO_FLOPS
class BoundaryCondition(_IntEnum):
"""
This enum lists supported boundary conditions for supported tensor
network factorizations.
See `cutensornetBoundaryCondition_t`.
"""
OPEN = CUTENSORNET_BOUNDARY_CONDITION_OPEN
class StateAttribute(_IntEnum):
"""
This enum lists all attributes associated with computation of a
`cutensornetState_t`.
See `cutensornetStateAttributes_t`.
"""
MPS_CANONICAL_CENTER = CUTENSORNET_STATE_MPS_CANONICAL_CENTER
MPS_SVD_CONFIG_ABS_CUTOFF = CUTENSORNET_STATE_MPS_SVD_CONFIG_ABS_CUTOFF
MPS_SVD_CONFIG_REL_CUTOFF = CUTENSORNET_STATE_MPS_SVD_CONFIG_REL_CUTOFF
MPS_SVD_CONFIG_S_NORMALIZATION = CUTENSORNET_STATE_MPS_SVD_CONFIG_S_NORMALIZATION
MPS_SVD_CONFIG_ALGO = CUTENSORNET_STATE_MPS_SVD_CONFIG_ALGO
MPS_SVD_CONFIG_ALGO_PARAMS = CUTENSORNET_STATE_MPS_SVD_CONFIG_ALGO_PARAMS
MPS_SVD_CONFIG_DISCARDED_WEIGHT_CUTOFF = CUTENSORNET_STATE_MPS_SVD_CONFIG_DISCARDED_WEIGHT_CUTOFF
NUM_HYPER_SAMPLES = CUTENSORNET_STATE_NUM_HYPER_SAMPLES
CONFIG_MPS_CANONICAL_CENTER = CUTENSORNET_STATE_CONFIG_MPS_CANONICAL_CENTER
CONFIG_MPS_SVD_ABS_CUTOFF = CUTENSORNET_STATE_CONFIG_MPS_SVD_ABS_CUTOFF
CONFIG_MPS_SVD_REL_CUTOFF = CUTENSORNET_STATE_CONFIG_MPS_SVD_REL_CUTOFF
CONFIG_MPS_SVD_S_NORMALIZATION = CUTENSORNET_STATE_CONFIG_MPS_SVD_S_NORMALIZATION
CONFIG_MPS_SVD_ALGO = CUTENSORNET_STATE_CONFIG_MPS_SVD_ALGO
CONFIG_MPS_SVD_ALGO_PARAMS = CUTENSORNET_STATE_CONFIG_MPS_SVD_ALGO_PARAMS
CONFIG_MPS_SVD_DISCARDED_WEIGHT_CUTOFF = CUTENSORNET_STATE_CONFIG_MPS_SVD_DISCARDED_WEIGHT_CUTOFF
CONFIG_MPS_MPO_APPLICATION = CUTENSORNET_STATE_CONFIG_MPS_MPO_APPLICATION
CONFIG_MPS_GAUGE_OPTION = CUTENSORNET_STATE_CONFIG_MPS_GAUGE_OPTION
CONFIG_NUM_HYPER_SAMPLES = CUTENSORNET_STATE_CONFIG_NUM_HYPER_SAMPLES
INFO_FLOPS = CUTENSORNET_STATE_INFO_FLOPS
class StateMPOApplication(_IntEnum):
"""
This enum lists all options for contraction and decomposition
operations in MPS-MPO computation.
See `cutensornetStateMPOApplication_t`.
"""
INEXACT = CUTENSORNET_STATE_MPO_APPLICATION_INEXACT
EXACT = CUTENSORNET_STATE_MPO_APPLICATION_EXACT
class StateMPSGaugeOption(_IntEnum):
"""
This enum lists various gauge options on MPS.
See `cutensornetStateMPSGaugeOption_t`.
"""
STATE_MPS_GAUGE_FREE = CUTENSORNET_STATE_MPS_GAUGE_FREE
STATE_MPS_GAUGE_SIMPLE = CUTENSORNET_STATE_MPS_GAUGE_SIMPLE
class StateProjectionMPSOrthoOption(_IntEnum):
"""
This enum lists orthonormalization behaviour for ProjectionMPS.
See `cutensornetStateProjectionMPSOrthoOption_t`.
"""
STATE_PROJECTION_MPS_ORTHO_AUTO = CUTENSORNET_STATE_PROJECTION_MPS_ORTHO_AUTO
class StateProjectionMPSAttribute(_IntEnum):
"""
This enum lists all attributes associated with computation of a
`cutensornetStateProjectionMPS_t`.
See `cutensornetStateProjectionMPSAttributes_t`.
"""
CONFIG_ORTHO_OPTION = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_ORTHO_OPTION
CONFIG_SVD_ABS_CUTOFF = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_ABS_CUTOFF
CONFIG_SVD_REL_CUTOFF = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_REL_CUTOFF
CONFIG_SVD_S_NORMALIZATION = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_S_NORMALIZATION
CONFIG_SVD_ALGO = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_ALGO
CONFIG_SVD_ALGO_PARAMS = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_ALGO_PARAMS
CONFIG_SVD_DISCARDED_WEIGHT_CUTOFF = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_DISCARDED_WEIGHT_CUTOFF
CONFIG_MAX_EXTENT = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_MAX_EXTENT
CONFIG_MAX_EXTENT_PREPARE_POLICY = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_MAX_EXTENT_PREPARE_POLICY
CONFIG_SVD_MAX_EXTENT = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_SVD_MAX_EXTENT
CONFIG_NUM_HYPER_SAMPLES = CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_NUM_HYPER_SAMPLES
class NetworkAutotunePreferenceAttribute(_IntEnum):
"""
This enum lists all attributes of a
`cutensornetNetworkAutotunePreference_t` that are accessible.
See `cutensornetNetworkAutotunePreferenceAttributes_t`.
"""
NETWORK_AUTOTUNE_MAX_ITERATIONS = CUTENSORNET_NETWORK_AUTOTUNE_MAX_ITERATIONS
NETWORK_AUTOTUNE_INTERMEDIATE_MODES = CUTENSORNET_NETWORK_AUTOTUNE_INTERMEDIATE_MODES
class MarginalKind(_IntEnum):
"""
This enum captures the kind of marginal represented by a
`cutensornetStateMarginal_t` handle.
See `cutensornetMarginalKind_t`.
"""
FULL = CUTENSORNET_MARGINAL_KIND_FULL
DIAGONAL = CUTENSORNET_MARGINAL_KIND_DIAGONAL
class StateProjectionMPSMaxExtentPreparePolicy(_IntEnum):
"""
Policy controlling whether
`CUTENSORNET_STATE_PROJECTION_MPS_CONFIG_MAX_EXTENT` participates in
`cutensornetStateProjectionMPSPrepare`.
See `cutensornetStateProjectionMPSMaxExtentPreparePolicy_t`.
"""
BUFFER = CUTENSORNET_STATE_PROJECTION_MPS_MAX_EXTENT_PREPARE_POLICY_BUFFER
CONFIG = CUTENSORNET_STATE_PROJECTION_MPS_MAX_EXTENT_PREPARE_POLICY_CONFIG
###############################################################################
# Error handling
###############################################################################
class cuTensorNetError(Exception):
def __init__(self, status):
self.status = status
s = Status(status)
cdef str err = f"{s.name} ({s.value}): {get_error_string(status)}"
super(cuTensorNetError, self).__init__(err)
def __reduce__(self):
return (type(self), (self.status,))
@cython.profile(False)
cpdef inline check_status(int status):
if status != 0:
raise cuTensorNetError(status)
###############################################################################
# Special dtypes
###############################################################################
tensor_id_list_dtype = _numpy.dtype(
{'names':['num_tensors','data'],
'formats': (_numpy.int32, _numpy.intp),
'itemsize': sizeof(TensorIDList),
}, align=True
)
contraction_path_dtype = _numpy.dtype(
{'names':['num_contractions','data'],
'formats': (_numpy.uint32, _numpy.intp),
'itemsize': sizeof(ContractionPath),
}, align=True
)
# We need this dtype because its members are not of the same type...
slice_info_pair_dtype = _numpy.dtype(
{'names': ('sliced_mode','sliced_extent'),
'formats': (_numpy.int32, _numpy.int64),
'itemsize': sizeof(SliceInfoPair),
}, align=True
)
slicing_config_dtype = _numpy.dtype(
{'names': ('num_sliced_modes','data'),
'formats': (_numpy.uint32, _numpy.intp),
'itemsize': sizeof(SlicingConfig),
}, align=True
)
gesvdj_params_dtype = _numpy.dtype(
{'names': ('tol','max_sweeps'),
'formats': (_numpy.float64, _numpy.int32),
'itemsize': sizeof(GesvdjParams),
}, align=True
)
gesvdr_params_dtype = _numpy.dtype(
{'names': ('oversampling','niters'),
'formats': (_numpy.int64, _numpy.int64),
'itemsize': sizeof(GesvdrParams),
}, align=True
)
gesvdj_status_dtype = _numpy.dtype(
{'names': ('residual', 'sweeps'),
'formats': (_numpy.float64, _numpy.int32),
'itemsize': sizeof(GesvdjStatus),
}, align=True
)
gesvdp_status_dtype = _numpy.dtype(
{'names': ('err_sigma', ),
'formats': (_numpy.float64, ),
'itemsize': sizeof(GesvdpStatus),
}, align=True
)
tensor_qualifiers_dtype = _numpy.dtype(
{'names':('is_conjugate', 'is_constant', 'requires_gradient'),
'formats': (_numpy.int32, _numpy.int32, _numpy.int32, ),
'itemsize': sizeof(TensorQualifiers),
}, align=True
)
###############################################################################
# Wrapper functions
###############################################################################
cpdef intptr_t create() except? 0:
"""Initializes the cuTensorNet library.
Returns:
intptr_t: Pointer to ``cutensornetHandle_t``.
.. seealso:: `cutensornetCreate`
"""
cdef Handle handle
with nogil:
__status__ = cutensornetCreate(&handle)
check_status(__status__)
return <intptr_t>handle
cpdef destroy(intptr_t handle):
"""Destroys the cuTensorNet library handle.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
.. seealso:: `cutensornetDestroy`
"""
with nogil:
__status__ = cutensornetDestroy(<Handle>handle)
check_status(__status__)
cpdef intptr_t create_network_descriptor(intptr_t handle, int32_t num_inputs, num_modes_in, extents_in, strides_in, modes_in, qualifiers_in, int32_t num_modes_out, extents_out, strides_out, modes_out, int data_type, int compute_type) except? 0:
"""DEPRECATED: Initializes a ``cutensornetNetworkDescriptor_t``, describing the connectivity (i.e., network topology) between the tensors.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
num_inputs (int32_t): Number of input tensors.
num_modes_in (object): Array of size ``num_inputs``; ``num_modes_in[i]`` denotes the number of modes available in the i-th tensor. It can be:
- an :class:`int` as the pointer address to the array, or
- a Python sequence of ``int32_t``.
extents_in (object): Array of size ``num_inputs``; ``extents_in[i]`` has ``num_modes_in[i]`` many entries with ``extents_in[i][j]`` (``j`` < ``num_modes_in[i]``) corresponding to the extent of the j-th mode of tensor ``i``. It can be:
- an :class:`int` as the pointer address to the nested sequence, or
- a Python sequence of :class:`int`\s, each of which is a pointer address
to a valid sequence of 'int64_t', or
- a nested Python sequence of ``int64_t``.
strides_in (object): Array of size ``num_inputs``; ``strides_in[i]`` has ``num_modes_in[i]`` many entries with ``strides_in[i][j]`` (``j`` < ``num_modes_in[i]``) corresponding to the linearized offset -- in physical memory -- between two logically-neighboring elements w.r.t the j-th mode of tensor ``i``. It can be:
- an :class:`int` as the pointer address to the nested sequence, or
- a Python sequence of :class:`int`\s, each of which is a pointer address
to a valid sequence of 'int64_t', or
- a nested Python sequence of ``int64_t``.
modes_in (object): Array of size ``num_inputs``; ``modes_in[i]`` has ``num_modes_in[i]`` many entries -- each entry corresponds to a mode. Each mode that does not appear in the input tensor is implicitly contracted. It can be:
- an :class:`int` as the pointer address to the nested sequence, or
- a Python sequence of :class:`int`\s, each of which is a pointer address
to a valid sequence of 'int32_t', or
- a nested Python sequence of ``int32_t``.
qualifiers_in (object): Array of size ``num_inputs``; ``qualifiers_in[i]`` denotes the qualifiers of the i-th input tensor. Refer to ``cutensornetTensorQualifiers_t``. It can be:
- an :class:`int` as the pointer address to the array, or
- a Python sequence of ``cutensornetTensorQualifiers_t``.
num_modes_out (int32_t): number of modes of the output tensor. On entry, if this value is ``-1`` and the output modes are not provided, the network will infer the output modes. If this value is ``0``, the network is force reduced.
extents_out (object): Array of size ``num_modes_out``; ``extents_out[j]`` (``j`` < ``num_modes_out``) corresponding to the extent of the j-th mode of the output tensor. It can be:
- an :class:`int` as the pointer address to the array, or
- a Python sequence of ``int64_t``.
strides_out (object): Array of size ``num_modes_out``; ``strides_out[j]`` (``j`` < ``num_modes_out``) corresponding to the linearized offset -- in physical memory -- between two logically-neighboring elements w.r.t the j-th mode of the output tensor. It can be:
- an :class:`int` as the pointer address to the array, or
- a Python sequence of ``int64_t``.
modes_out (object): Array of size ``num_modes_out``; ``modes_out[j]`` denotes the j-th mode of the output tensor. It can be:
- an :class:`int` as the pointer address to the array, or
- a Python sequence of ``int32_t``.
data_type (int): Denotes the data type for all input and output tensors.
compute_type (ComputeType): Denotes the compute type used throughout the computation.
Returns:
intptr_t: Pointer to a ``cutensornetNetworkDescriptor_t``.
.. seealso:: `cutensornetCreateNetworkDescriptor`
"""
cdef nullable_unique_ptr[ vector[int32_t] ] _num_modes_in_
get_resource_ptr[int32_t](_num_modes_in_, num_modes_in, <int32_t*>NULL)
cdef nested_resource[ int64_t ] _extents_in_
get_nested_resource_ptr[int64_t](_extents_in_, extents_in, <int64_t*>NULL)
cdef nested_resource[ int64_t ] _strides_in_
get_nested_resource_ptr[int64_t](_strides_in_, strides_in, <int64_t*>NULL)
cdef nested_resource[ int32_t ] _modes_in_
get_nested_resource_ptr[int32_t](_modes_in_, modes_in, <int32_t*>NULL)
cdef nullable_unique_ptr[ vector[cutensornetTensorQualifiers_t] ] _qualifiers_in_
get_resource_ptr[cutensornetTensorQualifiers_t](_qualifiers_in_, qualifiers_in, <cutensornetTensorQualifiers_t*>NULL)
cdef nullable_unique_ptr[ vector[int64_t] ] _extents_out_
get_resource_ptr[int64_t](_extents_out_, extents_out, <int64_t*>NULL)
cdef nullable_unique_ptr[ vector[int64_t] ] _strides_out_
get_resource_ptr[int64_t](_strides_out_, strides_out, <int64_t*>NULL)
cdef nullable_unique_ptr[ vector[int32_t] ] _modes_out_
get_resource_ptr[int32_t](_modes_out_, modes_out, <int32_t*>NULL)
cdef NetworkDescriptor network_desc
with nogil:
__status__ = cutensornetCreateNetworkDescriptor(<const Handle>handle, num_inputs, <const int32_t*>(_num_modes_in_.data()), <const int64_t* const*>(_extents_in_.ptrs.data()), <const int64_t* const*>(_strides_in_.ptrs.data()), <const int32_t* const*>(_modes_in_.ptrs.data()), <const cutensornetTensorQualifiers_t*>(_qualifiers_in_.data()), num_modes_out, <const int64_t*>(_extents_out_.data()), <const int64_t*>(_strides_out_.data()), <const int32_t*>(_modes_out_.data()), <DataType>data_type, <_ComputeType>compute_type, &network_desc)
check_status(__status__)
return <intptr_t>network_desc
cpdef destroy_network_descriptor(intptr_t network_desc):
"""DEPRECATED: Frees all the memory associated with the network descriptor.
Args:
network_desc (intptr_t): Opaque handle to a tensor network descriptor.
.. seealso:: `cutensornetDestroyNetworkDescriptor`
"""
with nogil:
__status__ = cutensornetDestroyNetworkDescriptor(<NetworkDescriptor>network_desc)
check_status(__status__)
cpdef intptr_t get_output_tensor_descriptor(intptr_t handle, intptr_t network_desc) except? 0:
"""Creates a ``cutensornetTensorDescriptor_t`` representing the output tensor of the network.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
network_desc (intptr_t): Pointer to a ``cutensornetNetworkDescriptor_t``.
Returns:
intptr_t: an opaque ``cutensornetTensorDescriptor_t`` struct. Cannot be null. On return, a new ``cutensornetTensorDescriptor_t`` holds the meta-data of the ``network_desc`` output tensor.
.. seealso:: `cutensornetGetOutputTensorDescriptor`
"""
cdef TensorDescriptor output_tensor_desc
with nogil:
__status__ = cutensornetGetOutputTensorDescriptor(<const Handle>handle, <const NetworkDescriptor>network_desc, &output_tensor_desc)
check_status(__status__)
return <intptr_t>output_tensor_desc
cpdef intptr_t create_workspace_descriptor(intptr_t handle) except? 0:
"""Creates a workspace descriptor that holds information about the user provided memory buffer.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
Returns:
intptr_t: Pointer to the opaque workspace descriptor.
.. seealso:: `cutensornetCreateWorkspaceDescriptor`
"""
cdef WorkspaceDescriptor work_desc
with nogil:
__status__ = cutensornetCreateWorkspaceDescriptor(<const Handle>handle, &work_desc)
check_status(__status__)
return <intptr_t>work_desc
cpdef workspace_compute_contraction_sizes(intptr_t handle, intptr_t network_desc, intptr_t optimizer_info, intptr_t work_desc):
"""Computes the workspace size needed to contract the tensor network using the provided contraction path.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
network_desc (intptr_t): Describes the tensor network (i.e., its tensors and their connectivity).
optimizer_info (intptr_t): Opaque structure.
work_desc (intptr_t): The workspace descriptor in which the information is collected.
.. seealso:: `cutensornetWorkspaceComputeContractionSizes`
"""
with nogil:
__status__ = cutensornetWorkspaceComputeContractionSizes(<const Handle>handle, <const NetworkDescriptor>network_desc, <const ContractionOptimizerInfo>optimizer_info, <WorkspaceDescriptor>work_desc)
check_status(__status__)
cpdef int64_t workspace_get_memory_size(intptr_t handle, intptr_t work_desc, int work_pref, int mem_space, int work_kind) except? -1:
"""Retrieves the needed workspace size for the given workspace preference, memory space, workspace kind.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
work_desc (intptr_t): Opaque structure describing the workspace.
work_pref (WorksizePref): Preference of workspace for planning.
mem_space (Memspace): The memory space where the workspace is allocated.
work_kind (WorkspaceKind): The kind of workspace.
Returns:
int64_t: Needed workspace size.
.. seealso:: `cutensornetWorkspaceGetMemorySize`
"""
cdef int64_t memory_size
with nogil:
__status__ = cutensornetWorkspaceGetMemorySize(<const Handle>handle, <const WorkspaceDescriptor>work_desc, <_WorksizePref>work_pref, <_Memspace>mem_space, <_WorkspaceKind>work_kind, &memory_size)
check_status(__status__)
return memory_size
cpdef workspace_set_memory(intptr_t handle, intptr_t work_desc, int mem_space, int work_kind, intptr_t memory_ptr, int64_t memory_size):
"""Sets the memory address and workspace size of the workspace provided by the user.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
work_desc (intptr_t): Opaque structure describing the workspace.
mem_space (Memspace): The memory space where the workspace is allocated.
work_kind (WorkspaceKind): The kind of workspace.
memory_ptr (intptr_t): Workspace memory pointer, may be null.
memory_size (int64_t): Workspace size.
.. seealso:: `cutensornetWorkspaceSetMemory`
"""
with nogil:
__status__ = cutensornetWorkspaceSetMemory(<const Handle>handle, <WorkspaceDescriptor>work_desc, <_Memspace>mem_space, <_WorkspaceKind>work_kind, <void* const>memory_ptr, memory_size)
check_status(__status__)
cpdef tuple workspace_get_memory(intptr_t handle, intptr_t work_desc, int mem_space, int work_kind):
"""Retrieves the memory address and workspace size of workspace hosted in the workspace descriptor.
Args:
handle (intptr_t): Opaque handle holding cuTensorNet's library context.
work_desc (intptr_t): Opaque structure describing the workspace.
mem_space (Memspace): The memory space where the workspace is allocated.
work_kind (WorkspaceKind): The kind of workspace.
Returns:
A 2-tuple containing:
- intptr_t: Workspace memory pointer.
- int64_t: Workspace size.
.. seealso:: `cutensornetWorkspaceGetMemory`
"""
cdef void* memory_ptr
cdef int64_t memory_size
with nogil:
__status__ = cutensornetWorkspaceGetMemory(<const Handle>handle, <const WorkspaceDescriptor>work_desc, <_Memspace>mem_space, <_WorkspaceKind>work_kind, &memory_ptr, &memory_size)
check_status(__status__)
return (<intptr_t>memory_ptr, memory_size)
cpdef destroy_workspace_descriptor(intptr_t work_desc):
"""Frees the workspace descriptor.
Args: