ZTWHHH commited on
Commit
5768fef
·
verified ·
1 Parent(s): 47f975b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. videollama2/lib/python3.10/site-packages/contourpy/_contourpy.pyi +200 -0
  3. videollama2/lib/python3.10/site-packages/contourpy/_version.py +1 -0
  4. videollama2/lib/python3.10/site-packages/contourpy/chunk.py +95 -0
  5. videollama2/lib/python3.10/site-packages/contourpy/enum_util.py +57 -0
  6. videollama2/lib/python3.10/site-packages/contourpy/typecheck.py +203 -0
  7. videollama2/lib/python3.10/site-packages/contourpy/types.py +13 -0
  8. videollama2/lib/python3.10/site-packages/contourpy/util/__init__.py +5 -0
  9. videollama2/lib/python3.10/site-packages/contourpy/util/_build_config.py +60 -0
  10. videollama2/lib/python3.10/site-packages/contourpy/util/data.py +78 -0
  11. videollama2/lib/python3.10/site-packages/numpy-1.24.4.dist-info/INSTALLER +1 -0
  12. videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/COPYING +29 -0
  13. videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/METADATA +222 -0
  14. videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/RECORD +20 -0
  15. videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/REQUESTED +0 -0
  16. videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/INSTALLER +1 -0
  17. videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/METADATA +609 -0
  18. videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/RECORD +510 -0
  19. videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/REQUESTED +0 -0
  20. videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/licenses/LICENSE +201 -0
  21. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/crc_alt.h +1343 -0
  22. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/file_adapter.h +36 -0
  23. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/in_memory_adapter.h +32 -0
  24. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/inline_container.h +277 -0
  25. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/istream_adapter.h +27 -0
  26. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/read_adapter_interface.h +23 -0
  27. videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/versions.h +133 -0
  28. videollama2/lib/python3.10/site-packages/torch/include/pybind11/attr.h +690 -0
  29. videollama2/lib/python3.10/site-packages/torch/include/pybind11/buffer_info.h +208 -0
  30. videollama2/lib/python3.10/site-packages/torch/include/pybind11/cast.h +1704 -0
  31. videollama2/lib/python3.10/site-packages/torch/include/pybind11/chrono.h +225 -0
  32. videollama2/lib/python3.10/site-packages/torch/include/pybind11/common.h +2 -0
  33. videollama2/lib/python3.10/site-packages/torch/include/pybind11/complex.h +74 -0
  34. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/class.h +743 -0
  35. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/common.h +1255 -0
  36. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/descr.h +171 -0
  37. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/init.h +434 -0
  38. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/internals.h +656 -0
  39. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/type_caster_base.h +1177 -0
  40. videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/typeid.h +65 -0
  41. videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen.h +12 -0
  42. videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen/common.h +9 -0
  43. videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen/matrix.h +714 -0
  44. videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen/tensor.h +516 -0
  45. videollama2/lib/python3.10/site-packages/torch/include/pybind11/embed.h +316 -0
  46. videollama2/lib/python3.10/site-packages/torch/include/pybind11/eval.h +156 -0
  47. videollama2/lib/python3.10/site-packages/torch/include/pybind11/functional.h +137 -0
  48. videollama2/lib/python3.10/site-packages/torch/include/pybind11/gil.h +239 -0
  49. videollama2/lib/python3.10/site-packages/torch/include/pybind11/iostream.h +265 -0
  50. videollama2/lib/python3.10/site-packages/torch/include/pybind11/numpy.h +1998 -0
.gitattributes CHANGED
@@ -1736,3 +1736,5 @@ vllm/lib/python3.10/site-packages/cupy/_core/raw.cpython-310-x86_64-linux-gnu.so
1736
  vllm/lib/python3.10/site-packages/cupy/cuda/memory.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1737
  vllm/lib/python3.10/site-packages/cupy/_core/_kernel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1738
  vllm/lib/python3.10/site-packages/cupy/_core/_routines_math.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
1736
  vllm/lib/python3.10/site-packages/cupy/cuda/memory.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1737
  vllm/lib/python3.10/site-packages/cupy/_core/_kernel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1738
  vllm/lib/python3.10/site-packages/cupy/_core/_routines_math.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1739
+ vllm/lib/python3.10/site-packages/cupy/_core/_memory_range.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1740
+ vllm/lib/python3.10/site-packages/cupy/_core/_dtype.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
videollama2/lib/python3.10/site-packages/contourpy/_contourpy.pyi ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import ClassVar, NoReturn
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+ from typing_extensions import TypeAlias
6
+
7
+ import contourpy._contourpy as cpy
8
+
9
+ # Input numpy array types, the same as in common.h
10
+ CoordinateArray: TypeAlias = npt.NDArray[np.float64]
11
+ MaskArray: TypeAlias = npt.NDArray[np.bool_]
12
+ LevelArray: TypeAlias = npt.ArrayLike
13
+
14
+ # Output numpy array types, the same as in common.h
15
+ PointArray: TypeAlias = npt.NDArray[np.float64]
16
+ CodeArray: TypeAlias = npt.NDArray[np.uint8]
17
+ OffsetArray: TypeAlias = npt.NDArray[np.uint32]
18
+
19
+ # Types returned from filled()
20
+ FillReturn_OuterCode: TypeAlias = tuple[list[PointArray], list[CodeArray]]
21
+ FillReturn_OuterOffset: TypeAlias = tuple[list[PointArray], list[OffsetArray]]
22
+ FillReturn_ChunkCombinedCode: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None]]
23
+ FillReturn_ChunkCombinedOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None]]
24
+ FillReturn_ChunkCombinedCodeOffset: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None], list[OffsetArray | None]]
25
+ FillReturn_ChunkCombinedOffsetOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None], list[OffsetArray | None]]
26
+ FillReturn_Chunk: TypeAlias = FillReturn_ChunkCombinedCode | FillReturn_ChunkCombinedOffset | FillReturn_ChunkCombinedCodeOffset | FillReturn_ChunkCombinedOffsetOffset
27
+ FillReturn: TypeAlias = FillReturn_OuterCode | FillReturn_OuterOffset | FillReturn_Chunk
28
+
29
+ # Types returned from lines()
30
+ LineReturn_Separate: TypeAlias = list[PointArray]
31
+ LineReturn_SeparateCode: TypeAlias = tuple[list[PointArray], list[CodeArray]]
32
+ LineReturn_ChunkCombinedCode: TypeAlias = tuple[list[PointArray | None], list[CodeArray | None]]
33
+ LineReturn_ChunkCombinedOffset: TypeAlias = tuple[list[PointArray | None], list[OffsetArray | None]]
34
+ LineReturn_ChunkCombinedNan: TypeAlias = tuple[list[PointArray | None]]
35
+ LineReturn_Chunk: TypeAlias = LineReturn_ChunkCombinedCode | LineReturn_ChunkCombinedOffset | LineReturn_ChunkCombinedNan
36
+ LineReturn: TypeAlias = LineReturn_Separate | LineReturn_SeparateCode | LineReturn_Chunk
37
+
38
+
39
+ NDEBUG: int
40
+ __version__: str
41
+
42
+ class FillType:
43
+ ChunkCombinedCode: ClassVar[cpy.FillType]
44
+ ChunkCombinedCodeOffset: ClassVar[cpy.FillType]
45
+ ChunkCombinedOffset: ClassVar[cpy.FillType]
46
+ ChunkCombinedOffsetOffset: ClassVar[cpy.FillType]
47
+ OuterCode: ClassVar[cpy.FillType]
48
+ OuterOffset: ClassVar[cpy.FillType]
49
+ __members__: ClassVar[dict[str, cpy.FillType]]
50
+ def __eq__(self, other: object) -> bool: ...
51
+ def __getstate__(self) -> int: ...
52
+ def __hash__(self) -> int: ...
53
+ def __index__(self) -> int: ...
54
+ def __init__(self, value: int) -> None: ...
55
+ def __int__(self) -> int: ...
56
+ def __ne__(self, other: object) -> bool: ...
57
+ def __setstate__(self, state: int) -> NoReturn: ...
58
+ @property
59
+ def name(self) -> str: ...
60
+ @property
61
+ def value(self) -> int: ...
62
+
63
+ class LineType:
64
+ ChunkCombinedCode: ClassVar[cpy.LineType]
65
+ ChunkCombinedNan: ClassVar[cpy.LineType]
66
+ ChunkCombinedOffset: ClassVar[cpy.LineType]
67
+ Separate: ClassVar[cpy.LineType]
68
+ SeparateCode: ClassVar[cpy.LineType]
69
+ __members__: ClassVar[dict[str, cpy.LineType]]
70
+ def __eq__(self, other: object) -> bool: ...
71
+ def __getstate__(self) -> int: ...
72
+ def __hash__(self) -> int: ...
73
+ def __index__(self) -> int: ...
74
+ def __init__(self, value: int) -> None: ...
75
+ def __int__(self) -> int: ...
76
+ def __ne__(self, other: object) -> bool: ...
77
+ def __setstate__(self, state: int) -> NoReturn: ...
78
+ @property
79
+ def name(self) -> str: ...
80
+ @property
81
+ def value(self) -> int: ...
82
+
83
+ class ZInterp:
84
+ Linear: ClassVar[cpy.ZInterp]
85
+ Log: ClassVar[cpy.ZInterp]
86
+ __members__: ClassVar[dict[str, cpy.ZInterp]]
87
+ def __eq__(self, other: object) -> bool: ...
88
+ def __getstate__(self) -> int: ...
89
+ def __hash__(self) -> int: ...
90
+ def __index__(self) -> int: ...
91
+ def __init__(self, value: int) -> None: ...
92
+ def __int__(self) -> int: ...
93
+ def __ne__(self, other: object) -> bool: ...
94
+ def __setstate__(self, state: int) -> NoReturn: ...
95
+ @property
96
+ def name(self) -> str: ...
97
+ @property
98
+ def value(self) -> int: ...
99
+
100
+ def max_threads() -> int: ...
101
+
102
+ class ContourGenerator:
103
+ def create_contour(self, level: float) -> LineReturn: ...
104
+ def create_filled_contour(self, lower_level: float, upper_level: float) -> FillReturn: ...
105
+ def filled(self, lower_level: float, upper_level: float) -> FillReturn: ...
106
+ def lines(self, level: float) -> LineReturn: ...
107
+ def multi_filled(self, levels: LevelArray) -> list[FillReturn]: ...
108
+ def multi_lines(self, levels: LevelArray) -> list[LineReturn]: ...
109
+ @staticmethod
110
+ def supports_corner_mask() -> bool: ...
111
+ @staticmethod
112
+ def supports_fill_type(fill_type: FillType) -> bool: ...
113
+ @staticmethod
114
+ def supports_line_type(line_type: LineType) -> bool: ...
115
+ @staticmethod
116
+ def supports_quad_as_tri() -> bool: ...
117
+ @staticmethod
118
+ def supports_threads() -> bool: ...
119
+ @staticmethod
120
+ def supports_z_interp() -> bool: ...
121
+ @property
122
+ def chunk_count(self) -> tuple[int, int]: ...
123
+ @property
124
+ def chunk_size(self) -> tuple[int, int]: ...
125
+ @property
126
+ def corner_mask(self) -> bool: ...
127
+ @property
128
+ def fill_type(self) -> FillType: ...
129
+ @property
130
+ def line_type(self) -> LineType: ...
131
+ @property
132
+ def quad_as_tri(self) -> bool: ...
133
+ @property
134
+ def thread_count(self) -> int: ...
135
+ @property
136
+ def z_interp(self) -> ZInterp: ...
137
+ default_fill_type: cpy.FillType
138
+ default_line_type: cpy.LineType
139
+
140
+ class Mpl2005ContourGenerator(ContourGenerator):
141
+ def __init__(
142
+ self,
143
+ x: CoordinateArray,
144
+ y: CoordinateArray,
145
+ z: CoordinateArray,
146
+ mask: MaskArray,
147
+ *,
148
+ x_chunk_size: int = 0,
149
+ y_chunk_size: int = 0,
150
+ ) -> None: ...
151
+
152
+ class Mpl2014ContourGenerator(ContourGenerator):
153
+ def __init__(
154
+ self,
155
+ x: CoordinateArray,
156
+ y: CoordinateArray,
157
+ z: CoordinateArray,
158
+ mask: MaskArray,
159
+ *,
160
+ corner_mask: bool,
161
+ x_chunk_size: int = 0,
162
+ y_chunk_size: int = 0,
163
+ ) -> None: ...
164
+
165
+ class SerialContourGenerator(ContourGenerator):
166
+ def __init__(
167
+ self,
168
+ x: CoordinateArray,
169
+ y: CoordinateArray,
170
+ z: CoordinateArray,
171
+ mask: MaskArray,
172
+ *,
173
+ corner_mask: bool,
174
+ line_type: LineType,
175
+ fill_type: FillType,
176
+ quad_as_tri: bool,
177
+ z_interp: ZInterp,
178
+ x_chunk_size: int = 0,
179
+ y_chunk_size: int = 0,
180
+ ) -> None: ...
181
+ def _write_cache(self) -> NoReturn: ...
182
+
183
+ class ThreadedContourGenerator(ContourGenerator):
184
+ def __init__(
185
+ self,
186
+ x: CoordinateArray,
187
+ y: CoordinateArray,
188
+ z: CoordinateArray,
189
+ mask: MaskArray,
190
+ *,
191
+ corner_mask: bool,
192
+ line_type: LineType,
193
+ fill_type: FillType,
194
+ quad_as_tri: bool,
195
+ z_interp: ZInterp,
196
+ x_chunk_size: int = 0,
197
+ y_chunk_size: int = 0,
198
+ thread_count: int = 0,
199
+ ) -> None: ...
200
+ def _write_cache(self) -> None: ...
videollama2/lib/python3.10/site-packages/contourpy/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "1.3.0"
videollama2/lib/python3.10/site-packages/contourpy/chunk.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+
6
+ def calc_chunk_sizes(
7
+ chunk_size: int | tuple[int, int] | None,
8
+ chunk_count: int | tuple[int, int] | None,
9
+ total_chunk_count: int | None,
10
+ ny: int,
11
+ nx: int,
12
+ ) -> tuple[int, int]:
13
+ """Calculate chunk sizes.
14
+
15
+ Args:
16
+ chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same
17
+ size in both directions if only one is specified. Cannot be negative.
18
+ chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the
19
+ same count in both directions if only one is specified. If less than 1, set to 1.
20
+ total_chunk_count (int, optional): Total number of chunks. If less than 1, set to 1.
21
+ ny (int): Number of grid points in y-direction.
22
+ nx (int): Number of grid points in x-direction.
23
+
24
+ Return:
25
+ tuple(int, int): Chunk sizes (y_chunk_size, x_chunk_size).
26
+
27
+ Note:
28
+ Zero or one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` should be
29
+ specified.
30
+ """
31
+ if sum([chunk_size is not None, chunk_count is not None, total_chunk_count is not None]) > 1:
32
+ raise ValueError("Only one of chunk_size, chunk_count and total_chunk_count should be set")
33
+
34
+ if nx < 2 or ny < 2:
35
+ raise ValueError(f"(ny, nx) must be at least (2, 2), not ({ny}, {nx})")
36
+
37
+ if total_chunk_count is not None:
38
+ max_chunk_count = (nx-1)*(ny-1)
39
+ total_chunk_count = min(max(total_chunk_count, 1), max_chunk_count)
40
+ if total_chunk_count == 1:
41
+ chunk_size = 0
42
+ elif total_chunk_count == max_chunk_count:
43
+ chunk_size = (1, 1)
44
+ else:
45
+ factors = two_factors(total_chunk_count)
46
+ if ny > nx:
47
+ chunk_count = factors
48
+ else:
49
+ chunk_count = (factors[1], factors[0])
50
+
51
+ if chunk_count is not None:
52
+ if isinstance(chunk_count, tuple):
53
+ y_chunk_count, x_chunk_count = chunk_count
54
+ else:
55
+ y_chunk_count = x_chunk_count = chunk_count
56
+ x_chunk_count = min(max(x_chunk_count, 1), nx-1)
57
+ y_chunk_count = min(max(y_chunk_count, 1), ny-1)
58
+ chunk_size = (math.ceil((ny-1) / y_chunk_count), math.ceil((nx-1) / x_chunk_count))
59
+
60
+ if chunk_size is None:
61
+ y_chunk_size = x_chunk_size = 0
62
+ elif isinstance(chunk_size, tuple):
63
+ y_chunk_size, x_chunk_size = chunk_size
64
+ else:
65
+ y_chunk_size = x_chunk_size = chunk_size
66
+
67
+ if x_chunk_size < 0 or y_chunk_size < 0:
68
+ raise ValueError("chunk_size cannot be negative")
69
+
70
+ return y_chunk_size, x_chunk_size
71
+
72
+
73
+ def two_factors(n: int) -> tuple[int, int]:
74
+ """Split an integer into two integer factors.
75
+
76
+ The two factors will be as close as possible to the sqrt of n, and are returned in decreasing
77
+ order. Worst case returns (n, 1).
78
+
79
+ Args:
80
+ n (int): The integer to factorize, must be positive.
81
+
82
+ Return:
83
+ tuple(int, int): The two factors of n, in decreasing order.
84
+ """
85
+ if n < 0:
86
+ raise ValueError(f"two_factors expects positive integer not {n}")
87
+
88
+ i = math.ceil(math.sqrt(n))
89
+ while n % i != 0:
90
+ i -= 1
91
+ j = n // i
92
+ if i > j:
93
+ return i, j
94
+ else:
95
+ return j, i
videollama2/lib/python3.10/site-packages/contourpy/enum_util.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from contourpy._contourpy import FillType, LineType, ZInterp
4
+
5
+
6
+ def as_fill_type(fill_type: FillType | str) -> FillType:
7
+ """Coerce a FillType or string value to a FillType.
8
+
9
+ Args:
10
+ fill_type (FillType or str): Value to convert.
11
+
12
+ Return:
13
+ FillType: Converted value.
14
+ """
15
+ if isinstance(fill_type, str):
16
+ try:
17
+ return FillType.__members__[fill_type]
18
+ except KeyError as e:
19
+ raise ValueError(f"'{fill_type}' is not a valid FillType") from e
20
+ else:
21
+ return fill_type
22
+
23
+
24
+ def as_line_type(line_type: LineType | str) -> LineType:
25
+ """Coerce a LineType or string value to a LineType.
26
+
27
+ Args:
28
+ line_type (LineType or str): Value to convert.
29
+
30
+ Return:
31
+ LineType: Converted value.
32
+ """
33
+ if isinstance(line_type, str):
34
+ try:
35
+ return LineType.__members__[line_type]
36
+ except KeyError as e:
37
+ raise ValueError(f"'{line_type}' is not a valid LineType") from e
38
+ else:
39
+ return line_type
40
+
41
+
42
+ def as_z_interp(z_interp: ZInterp | str) -> ZInterp:
43
+ """Coerce a ZInterp or string value to a ZInterp.
44
+
45
+ Args:
46
+ z_interp (ZInterp or str): Value to convert.
47
+
48
+ Return:
49
+ ZInterp: Converted value.
50
+ """
51
+ if isinstance(z_interp, str):
52
+ try:
53
+ return ZInterp.__members__[z_interp]
54
+ except KeyError as e:
55
+ raise ValueError(f"'{z_interp}' is not a valid ZInterp") from e
56
+ else:
57
+ return z_interp
videollama2/lib/python3.10/site-packages/contourpy/typecheck.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, cast
4
+
5
+ import numpy as np
6
+
7
+ from contourpy import FillType, LineType
8
+ from contourpy.enum_util import as_fill_type, as_line_type
9
+ from contourpy.types import MOVETO, code_dtype, offset_dtype, point_dtype
10
+
11
+ if TYPE_CHECKING:
12
+ import contourpy._contourpy as cpy
13
+
14
+
15
+ # Minimalist array-checking functions that check dtype, ndims and shape only.
16
+ # They do not walk the arrays to check the contents for performance reasons.
17
+ def check_code_array(codes: Any) -> None:
18
+ if not isinstance(codes, np.ndarray):
19
+ raise TypeError(f"Expected numpy array not {type(codes)}")
20
+ if codes.dtype != code_dtype:
21
+ raise ValueError(f"Expected numpy array of dtype {code_dtype} not {codes.dtype}")
22
+ if not (codes.ndim == 1 and len(codes) > 1):
23
+ raise ValueError(f"Expected numpy array of shape (?,) not {codes.shape}")
24
+ if codes[0] != MOVETO:
25
+ raise ValueError(f"First element of code array must be {MOVETO}, not {codes[0]}")
26
+
27
+
28
+ def check_offset_array(offsets: Any) -> None:
29
+ if not isinstance(offsets, np.ndarray):
30
+ raise TypeError(f"Expected numpy array not {type(offsets)}")
31
+ if offsets.dtype != offset_dtype:
32
+ raise ValueError(f"Expected numpy array of dtype {offset_dtype} not {offsets.dtype}")
33
+ if not (offsets.ndim == 1 and len(offsets) > 1):
34
+ raise ValueError(f"Expected numpy array of shape (?,) not {offsets.shape}")
35
+ if offsets[0] != 0:
36
+ raise ValueError(f"First element of offset array must be 0, not {offsets[0]}")
37
+
38
+
39
+ def check_point_array(points: Any) -> None:
40
+ if not isinstance(points, np.ndarray):
41
+ raise TypeError(f"Expected numpy array not {type(points)}")
42
+ if points.dtype != point_dtype:
43
+ raise ValueError(f"Expected numpy array of dtype {point_dtype} not {points.dtype}")
44
+ if not (points.ndim == 2 and points.shape[1] ==2 and points.shape[0] > 1):
45
+ raise ValueError(f"Expected numpy array of shape (?, 2) not {points.shape}")
46
+
47
+
48
+ def _check_tuple_of_lists_with_same_length(
49
+ maybe_tuple: Any,
50
+ tuple_length: int,
51
+ allow_empty_lists: bool = True,
52
+ ) -> None:
53
+ if not isinstance(maybe_tuple, tuple):
54
+ raise TypeError(f"Expected tuple not {type(maybe_tuple)}")
55
+ if len(maybe_tuple) != tuple_length:
56
+ raise ValueError(f"Expected tuple of length {tuple_length} not {len(maybe_tuple)}")
57
+ for maybe_list in maybe_tuple:
58
+ if not isinstance(maybe_list, list):
59
+ msg = f"Expected tuple to contain {tuple_length} lists but found a {type(maybe_list)}"
60
+ raise TypeError(msg)
61
+ lengths = [len(item) for item in maybe_tuple]
62
+ if len(set(lengths)) != 1:
63
+ msg = f"Expected {tuple_length} lists with same length but lengths are {lengths}"
64
+ raise ValueError(msg)
65
+ if not allow_empty_lists and lengths[0] == 0:
66
+ raise ValueError(f"Expected {tuple_length} non-empty lists")
67
+
68
+
69
+ def check_filled(filled: cpy.FillReturn, fill_type: FillType | str) -> None:
70
+ fill_type = as_fill_type(fill_type)
71
+
72
+ if fill_type == FillType.OuterCode:
73
+ if TYPE_CHECKING:
74
+ filled = cast(cpy.FillReturn_OuterCode, filled)
75
+ _check_tuple_of_lists_with_same_length(filled, 2)
76
+ for i, (points, codes) in enumerate(zip(*filled)):
77
+ check_point_array(points)
78
+ check_code_array(codes)
79
+ if len(points) != len(codes):
80
+ raise ValueError(f"Points and codes have different lengths in polygon {i}")
81
+ elif fill_type == FillType.OuterOffset:
82
+ if TYPE_CHECKING:
83
+ filled = cast(cpy.FillReturn_OuterOffset, filled)
84
+ _check_tuple_of_lists_with_same_length(filled, 2)
85
+ for i, (points, offsets) in enumerate(zip(*filled)):
86
+ check_point_array(points)
87
+ check_offset_array(offsets)
88
+ if offsets[-1] != len(points):
89
+ raise ValueError(f"Inconsistent points and offsets in polygon {i}")
90
+ elif fill_type == FillType.ChunkCombinedCode:
91
+ if TYPE_CHECKING:
92
+ filled = cast(cpy.FillReturn_ChunkCombinedCode, filled)
93
+ _check_tuple_of_lists_with_same_length(filled, 2, allow_empty_lists=False)
94
+ for chunk, (points_or_none, codes_or_none) in enumerate(zip(*filled)):
95
+ if points_or_none is not None and codes_or_none is not None:
96
+ check_point_array(points_or_none)
97
+ check_code_array(codes_or_none)
98
+ if len(points_or_none) != len(codes_or_none):
99
+ raise ValueError(f"Points and codes have different lengths in chunk {chunk}")
100
+ elif not (points_or_none is None and codes_or_none is None):
101
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
102
+ elif fill_type == FillType.ChunkCombinedOffset:
103
+ if TYPE_CHECKING:
104
+ filled = cast(cpy.FillReturn_ChunkCombinedOffset, filled)
105
+ _check_tuple_of_lists_with_same_length(filled, 2, allow_empty_lists=False)
106
+ for chunk, (points_or_none, offsets_or_none) in enumerate(zip(*filled)):
107
+ if points_or_none is not None and offsets_or_none is not None:
108
+ check_point_array(points_or_none)
109
+ check_offset_array(offsets_or_none)
110
+ if offsets_or_none[-1] != len(points_or_none):
111
+ raise ValueError(f"Inconsistent points and offsets in chunk {chunk}")
112
+ elif not (points_or_none is None and offsets_or_none is None):
113
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
114
+ elif fill_type == FillType.ChunkCombinedCodeOffset:
115
+ if TYPE_CHECKING:
116
+ filled = cast(cpy.FillReturn_ChunkCombinedCodeOffset, filled)
117
+ _check_tuple_of_lists_with_same_length(filled, 3, allow_empty_lists=False)
118
+ for i, (points_or_none, codes_or_none, outer_offsets_or_none) in enumerate(zip(*filled)):
119
+ if (points_or_none is not None and codes_or_none is not None and
120
+ outer_offsets_or_none is not None):
121
+ check_point_array(points_or_none)
122
+ check_code_array(codes_or_none)
123
+ check_offset_array(outer_offsets_or_none)
124
+ if len(codes_or_none) != len(points_or_none):
125
+ raise ValueError(f"Points and codes have different lengths in chunk {i}")
126
+ if outer_offsets_or_none[-1] != len(codes_or_none):
127
+ raise ValueError(f"Inconsistent codes and outer_offsets in chunk {i}")
128
+ elif not (points_or_none is None and codes_or_none is None and
129
+ outer_offsets_or_none is None):
130
+ raise ValueError(f"Inconsistent Nones in chunk {i}")
131
+ elif fill_type == FillType.ChunkCombinedOffsetOffset:
132
+ if TYPE_CHECKING:
133
+ filled = cast(cpy.FillReturn_ChunkCombinedOffsetOffset, filled)
134
+ _check_tuple_of_lists_with_same_length(filled, 3, allow_empty_lists=False)
135
+ for i, (points_or_none, offsets_or_none, outer_offsets_or_none) in enumerate(zip(*filled)):
136
+ if (points_or_none is not None and offsets_or_none is not None and
137
+ outer_offsets_or_none is not None):
138
+ check_point_array(points_or_none)
139
+ check_offset_array(offsets_or_none)
140
+ check_offset_array(outer_offsets_or_none)
141
+ if offsets_or_none[-1] != len(points_or_none):
142
+ raise ValueError(f"Inconsistent points and offsets in chunk {i}")
143
+ if outer_offsets_or_none[-1] != len(offsets_or_none) - 1:
144
+ raise ValueError(f"Inconsistent offsets and outer_offsets in chunk {i}")
145
+ elif not (points_or_none is None and offsets_or_none is None and
146
+ outer_offsets_or_none is None):
147
+ raise ValueError(f"Inconsistent Nones in chunk {i}")
148
+ else:
149
+ raise ValueError(f"Invalid FillType {fill_type}")
150
+
151
+
152
+ def check_lines(lines: cpy.LineReturn, line_type: LineType | str) -> None:
153
+ line_type = as_line_type(line_type)
154
+
155
+ if line_type == LineType.Separate:
156
+ if TYPE_CHECKING:
157
+ lines = cast(cpy.LineReturn_Separate, lines)
158
+ if not isinstance(lines, list):
159
+ raise TypeError(f"Expected list not {type(lines)}")
160
+ for points in lines:
161
+ check_point_array(points)
162
+ elif line_type == LineType.SeparateCode:
163
+ if TYPE_CHECKING:
164
+ lines = cast(cpy.LineReturn_SeparateCode, lines)
165
+ _check_tuple_of_lists_with_same_length(lines, 2)
166
+ for i, (points, codes) in enumerate(zip(*lines)):
167
+ check_point_array(points)
168
+ check_code_array(codes)
169
+ if len(points) != len(codes):
170
+ raise ValueError(f"Points and codes have different lengths in line {i}")
171
+ elif line_type == LineType.ChunkCombinedCode:
172
+ if TYPE_CHECKING:
173
+ lines = cast(cpy.LineReturn_ChunkCombinedCode, lines)
174
+ _check_tuple_of_lists_with_same_length(lines, 2, allow_empty_lists=False)
175
+ for chunk, (points_or_none, codes_or_none) in enumerate(zip(*lines)):
176
+ if points_or_none is not None and codes_or_none is not None:
177
+ check_point_array(points_or_none)
178
+ check_code_array(codes_or_none)
179
+ if len(points_or_none) != len(codes_or_none):
180
+ raise ValueError(f"Points and codes have different lengths in chunk {chunk}")
181
+ elif not (points_or_none is None and codes_or_none is None):
182
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
183
+ elif line_type == LineType.ChunkCombinedOffset:
184
+ if TYPE_CHECKING:
185
+ lines = cast(cpy.LineReturn_ChunkCombinedOffset, lines)
186
+ _check_tuple_of_lists_with_same_length(lines, 2, allow_empty_lists=False)
187
+ for chunk, (points_or_none, offsets_or_none) in enumerate(zip(*lines)):
188
+ if points_or_none is not None and offsets_or_none is not None:
189
+ check_point_array(points_or_none)
190
+ check_offset_array(offsets_or_none)
191
+ if offsets_or_none[-1] != len(points_or_none):
192
+ raise ValueError(f"Inconsistent points and offsets in chunk {chunk}")
193
+ elif not (points_or_none is None and offsets_or_none is None):
194
+ raise ValueError(f"Inconsistent Nones in chunk {chunk}")
195
+ elif line_type == LineType.ChunkCombinedNan:
196
+ if TYPE_CHECKING:
197
+ lines = cast(cpy.LineReturn_ChunkCombinedNan, lines)
198
+ _check_tuple_of_lists_with_same_length(lines, 1, allow_empty_lists=False)
199
+ for _chunk, points_or_none in enumerate(lines[0]):
200
+ if points_or_none is not None:
201
+ check_point_array(points_or_none)
202
+ else:
203
+ raise ValueError(f"Invalid LineType {line_type}")
videollama2/lib/python3.10/site-packages/contourpy/types.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ # dtypes of arrays returned by ContourPy.
6
+ point_dtype = np.float64
7
+ code_dtype = np.uint8
8
+ offset_dtype = np.uint32
9
+
10
+ # Kind codes used in Matplotlib Paths.
11
+ MOVETO = 1
12
+ LINETO = 2
13
+ CLOSEPOLY = 79
videollama2/lib/python3.10/site-packages/contourpy/util/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from contourpy.util._build_config import build_config
4
+
5
+ __all__ = ["build_config"]
videollama2/lib/python3.10/site-packages/contourpy/util/_build_config.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # _build_config.py.in is converted into _build_config.py during the meson build process.
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def build_config() -> dict[str, str]:
7
+ """
8
+ Return a dictionary containing build configuration settings.
9
+
10
+ All dictionary keys and values are strings, for example ``False`` is
11
+ returned as ``"False"``.
12
+
13
+ .. versionadded:: 1.1.0
14
+ """
15
+ return dict(
16
+ # Python settings
17
+ python_version="3.10",
18
+ python_install_dir=r"/usr/local/lib/python3.10/site-packages/",
19
+ python_path=r"/tmp/build-env-xuiuilzc/bin/python",
20
+
21
+ # Package versions
22
+ contourpy_version="1.3.0",
23
+ meson_version="1.5.1",
24
+ mesonpy_version="0.16.0",
25
+ pybind11_version="2.13.5",
26
+
27
+ # Misc meson settings
28
+ meson_backend="ninja",
29
+ build_dir=r"/project/.mesonpy-4viy2wlb/lib/contourpy/util",
30
+ source_dir=r"/project/lib/contourpy/util",
31
+ cross_build="False",
32
+
33
+ # Build options
34
+ build_options=r"-Dbuildtype=release -Db_ndebug=if-release -Db_vscrt=md -Dvsenv=True --native-file=/project/.mesonpy-4viy2wlb/meson-python-native-file.ini",
35
+ buildtype="release",
36
+ cpp_std="c++17",
37
+ debug="False",
38
+ optimization="3",
39
+ vsenv="True",
40
+ b_ndebug="if-release",
41
+ b_vscrt="from_buildtype",
42
+
43
+ # C++ compiler
44
+ compiler_name="gcc",
45
+ compiler_version="10.2.1",
46
+ linker_id="ld.bfd",
47
+ compile_command="c++",
48
+
49
+ # Host machine
50
+ host_cpu="x86_64",
51
+ host_cpu_family="x86_64",
52
+ host_cpu_endian="little",
53
+ host_cpu_system="linux",
54
+
55
+ # Build machine, same as host machine if not a cross_build
56
+ build_cpu="x86_64",
57
+ build_cpu_family="x86_64",
58
+ build_cpu_endian="little",
59
+ build_cpu_system="linux",
60
+ )
videollama2/lib/python3.10/site-packages/contourpy/util/data.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ import numpy as np
6
+
7
+ if TYPE_CHECKING:
8
+ from contourpy._contourpy import CoordinateArray
9
+
10
+
11
+ def simple(
12
+ shape: tuple[int, int], want_mask: bool = False,
13
+ ) -> tuple[CoordinateArray, CoordinateArray, CoordinateArray | np.ma.MaskedArray[Any, Any]]:
14
+ """Return simple test data consisting of the sum of two gaussians.
15
+
16
+ Args:
17
+ shape (tuple(int, int)): 2D shape of data to return.
18
+ want_mask (bool, optional): Whether test data should be masked or not, default ``False``.
19
+
20
+ Return:
21
+ Tuple of 3 arrays: ``x``, ``y``, ``z`` test data, ``z`` will be masked if
22
+ ``want_mask=True``.
23
+ """
24
+ ny, nx = shape
25
+ x = np.arange(nx, dtype=np.float64)
26
+ y = np.arange(ny, dtype=np.float64)
27
+ x, y = np.meshgrid(x, y)
28
+
29
+ xscale = nx - 1.0
30
+ yscale = ny - 1.0
31
+
32
+ # z is sum of 2D gaussians.
33
+ amp = np.asarray([1.0, -1.0, 0.8, -0.9, 0.7])
34
+ mid = np.asarray([[0.4, 0.2], [0.3, 0.8], [0.9, 0.75], [0.7, 0.3], [0.05, 0.7]])
35
+ width = np.asarray([0.4, 0.2, 0.2, 0.2, 0.1])
36
+
37
+ z = np.zeros_like(x)
38
+ for i in range(len(amp)):
39
+ z += amp[i]*np.exp(-((x/xscale - mid[i, 0])**2 + (y/yscale - mid[i, 1])**2) / width[i]**2)
40
+
41
+ if want_mask:
42
+ mask = np.logical_or(
43
+ ((x/xscale - 1.0)**2 / 0.2 + (y/yscale - 0.0)**2 / 0.1) < 1.0,
44
+ ((x/xscale - 0.2)**2 / 0.02 + (y/yscale - 0.45)**2 / 0.08) < 1.0,
45
+ )
46
+ z = np.ma.array(z, mask=mask) # type: ignore[no-untyped-call]
47
+
48
+ return x, y, z
49
+
50
+
51
+ def random(
52
+ shape: tuple[int, int], seed: int = 2187, mask_fraction: float = 0.0,
53
+ ) -> tuple[CoordinateArray, CoordinateArray, CoordinateArray | np.ma.MaskedArray[Any, Any]]:
54
+ """Return random test data in the range 0 to 1.
55
+
56
+ Args:
57
+ shape (tuple(int, int)): 2D shape of data to return.
58
+ seed (int, optional): Seed for random number generator, default 2187.
59
+ mask_fraction (float, optional): Fraction of elements to mask, default 0.
60
+
61
+ Return:
62
+ Tuple of 3 arrays: ``x``, ``y``, ``z`` test data, ``z`` will be masked if
63
+ ``mask_fraction`` is greater than zero.
64
+ """
65
+ ny, nx = shape
66
+ x = np.arange(nx, dtype=np.float64)
67
+ y = np.arange(ny, dtype=np.float64)
68
+ x, y = np.meshgrid(x, y)
69
+
70
+ rng = np.random.default_rng(seed)
71
+ z = rng.uniform(size=shape)
72
+
73
+ if mask_fraction > 0.0:
74
+ mask_fraction = min(mask_fraction, 0.99)
75
+ mask = rng.uniform(size=shape) < mask_fraction
76
+ z = np.ma.array(z, mask=mask) # type: ignore[no-untyped-call]
77
+
78
+ return x, y, z
videollama2/lib/python3.10/site-packages/numpy-1.24.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/COPYING ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2011, Stavros Korokithakis
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are
6
+ met:
7
+
8
+ Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+
11
+ Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in the
13
+ documentation and/or other materials provided with the distribution.
14
+
15
+ Neither the name of Stochastic Technologies nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/METADATA ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: shortuuid
3
+ Version: 1.0.13
4
+ Summary: A generator library for concise, unambiguous and URL-safe UUIDs.
5
+ Home-page: https://github.com/skorokithakis/shortuuid/
6
+ License: BSD-3-Clause
7
+ Author: Stavros Korokithakis
8
+ Author-email: hi@stavros.io
9
+ Requires-Python: >=3.6
10
+ Classifier: License :: OSI Approved :: BSD License
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.6
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Description-Content-Type: text/markdown
21
+
22
+ Description
23
+ ===========
24
+
25
+ `shortuuid` is a simple python library that generates concise, unambiguous, URL-safe
26
+ UUIDs.
27
+
28
+ Often, one needs to use non-sequential IDs in places where users will see them, but the
29
+ IDs must be as concise and easy to use as possible. `shortuuid` solves this problem by
30
+ generating uuids using Python's built-in `uuid` module and then translating them to
31
+ base57 using lowercase and uppercase letters and digits, and removing similar-looking
32
+ characters such as l, 1, I, O and 0.
33
+
34
+ [![image](https://travis-ci.org/skorokithakis/shortuuid.svg?branch=master)](https://travis-ci.org/skorokithakis/shortuuid)
35
+
36
+
37
+ Installation
38
+ ------------
39
+
40
+ To install `shortuuid` you need:
41
+
42
+ - Python 3.6+
43
+
44
+ If you have the dependencies, you have multiple options of installation:
45
+
46
+ - With pip (preferred), do `pip install shortuuid`.
47
+ - With setuptools, do `easy_install shortuuid`.
48
+ - To install the source, download it from
49
+ https://github.com/stochastic-technologies/shortuuid and run `python setup.py
50
+ install`.
51
+
52
+
53
+ Usage
54
+ -----
55
+
56
+ To use `shortuuid`, just import it in your project like so:
57
+
58
+ ```python
59
+ >>> import shortuuid
60
+ ```
61
+
62
+ You can then generate a short UUID:
63
+
64
+ ```python
65
+ >>> shortuuid.uuid()
66
+ 'vytxeTZskVKR7C7WgdSP3d'
67
+ ```
68
+
69
+ If you prefer a version 5 UUID, you can pass a name (DNS or URL) to the call and it will
70
+ be used as a namespace (`uuid.NAMESPACE_DNS` or `uuid.NAMESPACE_URL`) for the resulting
71
+ UUID:
72
+
73
+ ```python
74
+ >>> shortuuid.uuid(name="example.com")
75
+ 'exu3DTbj2ncsn9tLdLWspw'
76
+
77
+ >>> shortuuid.uuid(name="<http://example.com>")
78
+ 'shortuuid.uuid(name="<http://example.com>")'
79
+ ```
80
+
81
+ You can also generate a cryptographically secure random string (using `os.urandom()`
82
+ internally) with:
83
+
84
+ ```python
85
+ >>> shortuuid.ShortUUID().random(length=22)
86
+ 'RaF56o2r58hTKT7AYS9doj'
87
+ ```
88
+
89
+ To see the alphabet that is being used to generate new UUIDs:
90
+
91
+ ```python
92
+ >>> shortuuid.get_alphabet()
93
+ '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
94
+ ```
95
+
96
+ If you want to use your own alphabet to generate UUIDs, use `set_alphabet()`:
97
+
98
+ ```python
99
+ >>> shortuuid.set_alphabet("aaaaabcdefgh1230123")
100
+ >>> shortuuid.uuid()
101
+ '0agee20aa1hehebcagddhedddc0d2chhab3b'
102
+ ```
103
+
104
+ The default alphabet matches the regex `[2-9A-HJ-NP-Za-km-z]{22}`.
105
+
106
+ `shortuuid` will automatically sort and remove duplicates from your alphabet to ensure
107
+ consistency:
108
+
109
+ ```python
110
+ >>> shortuuid.get_alphabet()
111
+ '0123abcdefgh'
112
+ ```
113
+
114
+ If the default 22 digits are too long for you, you can get shorter IDs by just
115
+ truncating the string to the desired length. The IDs won't be universally unique any
116
+ longer, but the probability of a collision will still be very low.
117
+
118
+ To serialize existing UUIDs, use `encode()` and `decode()`:
119
+
120
+ ```python
121
+ >>> import uuid
122
+ >>> u = uuid.uuid4()
123
+ >>> u
124
+ UUID('6ca4f0f8-2508-4bac-b8f1-5d1e3da2247a')
125
+
126
+ >>> s = shortuuid.encode(u)
127
+ >>> s
128
+ 'MLpZDiEXM4VsUryR9oE8uc'
129
+
130
+ >>> shortuuid.decode(s) == u
131
+ True
132
+
133
+ >>> short = s[:7]
134
+ >>> short
135
+ 'MLpZDiE'
136
+
137
+ >>> h = shortuuid.decode(short)
138
+ UUID('00000000-0000-0000-0000-009a5b27f8b9')
139
+
140
+ >>> shortuuid.decode(shortuuid.encode(h)) == h
141
+ True
142
+ ```
143
+
144
+
145
+ Class-based usage
146
+ -----------------
147
+
148
+ If you need to have various alphabets per-thread, you can use the `ShortUUID` class,
149
+ like so:
150
+
151
+ ```python
152
+ >>> su = shortuuid.ShortUUID(alphabet="01345678")
153
+ >>> su.uuid()
154
+ '034636353306816784480643806546503818874456'
155
+
156
+ >>> su.get_alphabet()
157
+ '01345678'
158
+
159
+ >>> su.set_alphabet("21345687654123456")
160
+ >>> su.get_alphabet()
161
+ '12345678'
162
+ ```
163
+
164
+
165
+ Command-line usage
166
+ ------------------
167
+
168
+ `shortuuid` provides a simple way to generate a short UUID in a terminal:
169
+
170
+ ```bash
171
+ $ shortuuid
172
+ fZpeF6gcskHbSpTgpQCkcJ
173
+ ```
174
+
175
+
176
+ Django field
177
+ ------------
178
+
179
+ `shortuuid` includes a Django field that generates random short UUIDs by default, for
180
+ your convenience:
181
+
182
+ ```python
183
+ from shortuuid.django_fields import ShortUUIDField
184
+
185
+ class MyModel(models.Model):
186
+ # A primary key ID of length 16 and a short alphabet.
187
+ id = ShortUUIDField(
188
+ length=16,
189
+ max_length=40,
190
+ prefix="id_",
191
+ alphabet="abcdefg1234",
192
+ primary_key=True,
193
+ )
194
+
195
+ # A short UUID of length 22 and the default alphabet.
196
+ api_key = ShortUUIDField()
197
+ ```
198
+
199
+ The field is the same as the `CharField`, with a `length` argument (the length of the
200
+ ID), an `alphabet` argument, and the `default` argument removed. Everything else is
201
+ exactly the same, e.g. `index`, `help_text`, `max_length`, etc.
202
+
203
+
204
+ Compatibility note
205
+ ------------------
206
+
207
+ Versions of ShortUUID prior to 1.0.0 generated UUIDs with their MSB last, i.e. reversed.
208
+ This was later fixed, but if you have some UUIDs stored as a string with the old method,
209
+ you need to pass `legacy=True` to `decode()` when converting your strings back to UUIDs.
210
+
211
+ That option will go away in the future, so you will want to convert your UUIDs to
212
+ strings using the new method. This can be done like so:
213
+
214
+ ```python
215
+ >>> new_uuid_str = encode(decode(old_uuid_str, legacy=True))
216
+ ```
217
+
218
+ License
219
+ -------
220
+
221
+ `shortuuid` is distributed under the BSD license.
222
+
videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/RECORD ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/shortuuid,sha256=UKWJmVmWAF_gS2Wwle7CPBE-WL_SCAFW-qg4Do2xJJo,227
2
+ COPYING,sha256=ELKwYb5jpsdKluWiyWdCWwZsX7SDt8OIBwM0f80u4ME,1484
3
+ shortuuid-1.0.13.dist-info/COPYING,sha256=ELKwYb5jpsdKluWiyWdCWwZsX7SDt8OIBwM0f80u4ME,1484
4
+ shortuuid-1.0.13.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
5
+ shortuuid-1.0.13.dist-info/METADATA,sha256=dvOetBtLs2-ONmgheP9HDTYVPJpJ5tRR2wrp5KgfWBk,5767
6
+ shortuuid-1.0.13.dist-info/RECORD,,
7
+ shortuuid-1.0.13.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ shortuuid-1.0.13.dist-info/WHEEL,sha256=d2fvjOD7sXsVzChCqf0Ty0JbHKBaLYwDbGQDwQTnJ50,88
9
+ shortuuid-1.0.13.dist-info/entry_points.txt,sha256=F7-SvJ-aAiTOhrP7VkrJyg45WPWRqM8mQUa8dd7IBj4,47
10
+ shortuuid/__init__.py,sha256=LWYow59sUDM8M609UaraCH-W27sn6RcbFB41tnfa-88,400
11
+ shortuuid/__pycache__/__init__.cpython-310.pyc,,
12
+ shortuuid/__pycache__/cli.cpython-310.pyc,,
13
+ shortuuid/__pycache__/django_fields.cpython-310.pyc,,
14
+ shortuuid/__pycache__/main.cpython-310.pyc,,
15
+ shortuuid/__pycache__/test_shortuuid.cpython-310.pyc,,
16
+ shortuuid/cli.py,sha256=llBRZMvGb0FHP9yXTrxcqWJxpqyCYnNe_0u2jBHcrSs,1422
17
+ shortuuid/django_fields.py,sha256=JbxaGG4dMPz941pGeBAybYsFNanrLRqvIFlw3wk8ZXo,1349
18
+ shortuuid/main.py,sha256=plbRNcFSCi0Xe_s70kpgCDW5IArLfFLzq8UOTChqgPo,4688
19
+ shortuuid/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ shortuuid/test_shortuuid.py,sha256=MumPW69U-apESWlCs8VR4x1Ici00OVrLB-0Y-4_atGU,7207
videollama2/lib/python3.10/site-packages/shortuuid-1.0.13.dist-info/REQUESTED ADDED
File without changes
videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/METADATA ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: timm
3
+ Version: 1.0.3
4
+ Summary: PyTorch Image Models
5
+ Keywords: pytorch,image-classification
6
+ Home-page: https://github.com/huggingface/pytorch-image-models
7
+ Author-Email: Ross Wightman <ross@huggingface.co>
8
+ License: Apache-2.0
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Education
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Project-URL: Homepage, https://github.com/huggingface/pytorch-image-models
24
+ Project-URL: Documentation, https://huggingface.co/docs/timm/en/index
25
+ Project-URL: Repository, https://github.com/huggingface/pytorch-image-models
26
+ Requires-Python: >=3.8
27
+ Requires-Dist: torch
28
+ Requires-Dist: torchvision
29
+ Requires-Dist: pyyaml
30
+ Requires-Dist: huggingface_hub
31
+ Requires-Dist: safetensors
32
+ Description-Content-Type: text/markdown
33
+
34
+ # PyTorch Image Models
35
+ - [What's New](#whats-new)
36
+ - [Introduction](#introduction)
37
+ - [Models](#models)
38
+ - [Features](#features)
39
+ - [Results](#results)
40
+ - [Getting Started (Documentation)](#getting-started-documentation)
41
+ - [Train, Validation, Inference Scripts](#train-validation-inference-scripts)
42
+ - [Awesome PyTorch Resources](#awesome-pytorch-resources)
43
+ - [Licenses](#licenses)
44
+ - [Citing](#citing)
45
+
46
+ ## What's New
47
+
48
+ ❗Updates after Oct 10, 2022 are available in version >= 0.9❗
49
+ * Many changes since the last 0.6.x stable releases. They were previewed in 0.8.x dev releases but not everyone transitioned.
50
+ * `timm.models.layers` moved to `timm.layers`:
51
+ * `from timm.models.layers import name` will still work via deprecation mapping (but please transition to `timm.layers`).
52
+ * `import timm.models.layers.module` or `from timm.models.layers.module import name` needs to be changed now.
53
+ * Builder, helper, non-model modules in `timm.models` have a `_` prefix added, ie `timm.models.helpers` -> `timm.models._helpers`, there are temporary deprecation mapping files but those will be removed.
54
+ * All models now support `architecture.pretrained_tag` naming (ex `resnet50.rsb_a1`).
55
+ * The pretrained_tag is the specific weight variant (different head) for the architecture.
56
+ * Using only `architecture` defaults to the first weights in the default_cfgs for that model architecture.
57
+ * In adding pretrained tags, many model names that existed to differentiate were renamed to use the tag (ex: `vit_base_patch16_224_in21k` -> `vit_base_patch16_224.augreg_in21k`). There are deprecation mappings for these.
58
+ * A number of models had their checkpoints remaped to match architecture changes needed to better support `features_only=True`, there are `checkpoint_filter_fn` methods in any model module that was remapped. These can be passed to `timm.models.load_checkpoint(..., filter_fn=timm.models.swin_transformer_v2.checkpoint_filter_fn)` to remap your existing checkpoint.
59
+ * The Hugging Face Hub (https://huggingface.co/timm) is now the primary source for `timm` weights. Model cards include link to papers, original source, license.
60
+ * Previous 0.6.x can be cloned from [0.6.x](https://github.com/rwightman/pytorch-image-models/tree/0.6.x) branch or installed via pip with version.
61
+
62
+ ### May 14, 2024
63
+ * Support loading PaliGemma jax weights into SigLIP ViT models with average pooling.
64
+ * Add Hiera models from Meta (https://github.com/facebookresearch/hiera).
65
+ * Add `normalize=` flag for transorms, return non-normalized torch.Tensor with original dytpe (for `chug`)
66
+ * Version 1.0.3 release
67
+
68
+ ### May 11, 2024
69
+ * `Searching for Better ViT Baselines (For the GPU Poor)` weights and vit variants released. Exploring model shapes between Tiny and Base.
70
+
71
+ | model | top1 | top5 | param_count | img_size |
72
+ | -------------------------------------------------- | ------ | ------ | ----------- | -------- |
73
+ | [vit_mediumd_patch16_reg4_gap_256.sbb_in12k_ft_in1k](https://huggingface.co/timm/vit_mediumd_patch16_reg4_gap_256.sbb_in12k_ft_in1k) | 86.202 | 97.874 | 64.11 | 256 |
74
+ | [vit_betwixt_patch16_reg4_gap_256.sbb_in12k_ft_in1k](https://huggingface.co/timm/vit_betwixt_patch16_reg4_gap_256.sbb_in12k_ft_in1k) | 85.418 | 97.48 | 60.4 | 256 |
75
+ | [vit_mediumd_patch16_rope_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_mediumd_patch16_rope_reg1_gap_256.sbb_in1k) | 84.322 | 96.812 | 63.95 | 256 |
76
+ | [vit_betwixt_patch16_rope_reg4_gap_256.sbb_in1k](https://huggingface.co/timm/vit_betwixt_patch16_rope_reg4_gap_256.sbb_in1k) | 83.906 | 96.684 | 60.23 | 256 |
77
+ | [vit_base_patch16_rope_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_base_patch16_rope_reg1_gap_256.sbb_in1k) | 83.866 | 96.67 | 86.43 | 256 |
78
+ | [vit_medium_patch16_rope_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_medium_patch16_rope_reg1_gap_256.sbb_in1k) | 83.81 | 96.824 | 38.74 | 256 |
79
+ | [vit_betwixt_patch16_reg4_gap_256.sbb_in1k](https://huggingface.co/timm/vit_betwixt_patch16_reg4_gap_256.sbb_in1k) | 83.706 | 96.616 | 60.4 | 256 |
80
+ | [vit_betwixt_patch16_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_betwixt_patch16_reg1_gap_256.sbb_in1k) | 83.628 | 96.544 | 60.4 | 256 |
81
+ | [vit_medium_patch16_reg4_gap_256.sbb_in1k](https://huggingface.co/timm/vit_medium_patch16_reg4_gap_256.sbb_in1k) | 83.47 | 96.622 | 38.88 | 256 |
82
+ | [vit_medium_patch16_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_medium_patch16_reg1_gap_256.sbb_in1k) | 83.462 | 96.548 | 38.88 | 256 |
83
+ | [vit_little_patch16_reg4_gap_256.sbb_in1k](https://huggingface.co/timm/vit_little_patch16_reg4_gap_256.sbb_in1k) | 82.514 | 96.262 | 22.52 | 256 |
84
+ | [vit_wee_patch16_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_wee_patch16_reg1_gap_256.sbb_in1k) | 80.256 | 95.360 | 13.42 | 256 |
85
+ | [vit_pwee_patch16_reg1_gap_256.sbb_in1k](https://huggingface.co/timm/vit_pwee_patch16_reg1_gap_256.sbb_in1k) | 80.072 | 95.136 | 15.25 | 256 |
86
+ | [vit_mediumd_patch16_reg4_gap_256.sbb_in12k](https://huggingface.co/timm/vit_mediumd_patch16_reg4_gap_256.sbb_in12k) | N/A | N/A | 64.11 | 256 |
87
+ | [vit_betwixt_patch16_reg4_gap_256.sbb_in12k](https://huggingface.co/timm/vit_betwixt_patch16_reg4_gap_256.sbb_in12k) | N/A | N/A | 60.4 | 256 |
88
+
89
+ * AttentionExtract helper added to extract attention maps from `timm` models. See example in https://github.com/huggingface/pytorch-image-models/discussions/1232#discussioncomment-9320949
90
+ * `forward_intermediates()` API refined and added to more models including some ConvNets that have other extraction methods.
91
+ * 1017 of 1047 model architectures support `features_only=True` feature extraction. Remaining 34 architectures can be supported but based on priority requests.
92
+ * Remove torch.jit.script annotated functions including old JIT activations. Conflict with dynamo and dynamo does a much better job when used.
93
+
94
+ ### April 11, 2024
95
+ * Prepping for a long overdue 1.0 release, things have been stable for a while now.
96
+ * Significant feature that's been missing for a while, `features_only=True` support for ViT models with flat hidden states or non-std module layouts (so far covering `'vit_*', 'twins_*', 'deit*', 'beit*', 'mvitv2*', 'eva*', 'samvit_*', 'flexivit*'`)
97
+ * Above feature support achieved through a new `forward_intermediates()` API that can be used with a feature wrapping module or direclty.
98
+ ```python
99
+ model = timm.create_model('vit_base_patch16_224')
100
+ final_feat, intermediates = model.forward_intermediates(input)
101
+ output = model.forward_head(final_feat) # pooling + classifier head
102
+
103
+ print(final_feat.shape)
104
+ torch.Size([2, 197, 768])
105
+
106
+ for f in intermediates:
107
+ print(f.shape)
108
+ torch.Size([2, 768, 14, 14])
109
+ torch.Size([2, 768, 14, 14])
110
+ torch.Size([2, 768, 14, 14])
111
+ torch.Size([2, 768, 14, 14])
112
+ torch.Size([2, 768, 14, 14])
113
+ torch.Size([2, 768, 14, 14])
114
+ torch.Size([2, 768, 14, 14])
115
+ torch.Size([2, 768, 14, 14])
116
+ torch.Size([2, 768, 14, 14])
117
+ torch.Size([2, 768, 14, 14])
118
+ torch.Size([2, 768, 14, 14])
119
+ torch.Size([2, 768, 14, 14])
120
+
121
+ print(output.shape)
122
+ torch.Size([2, 1000])
123
+ ```
124
+
125
+ ```python
126
+ model = timm.create_model('eva02_base_patch16_clip_224', pretrained=True, img_size=512, features_only=True, out_indices=(-3, -2,))
127
+ output = model(torch.randn(2, 3, 512, 512))
128
+
129
+ for o in output:
130
+ print(o.shape)
131
+ torch.Size([2, 768, 32, 32])
132
+ torch.Size([2, 768, 32, 32])
133
+ ```
134
+ * TinyCLIP vision tower weights added, thx [Thien Tran](https://github.com/gau-nernst)
135
+
136
+ ### Feb 19, 2024
137
+ * Next-ViT models added. Adapted from https://github.com/bytedance/Next-ViT
138
+ * HGNet and PP-HGNetV2 models added. Adapted from https://github.com/PaddlePaddle/PaddleClas by [SeeFun](https://github.com/seefun)
139
+ * Removed setup.py, moved to pyproject.toml based build supported by PDM
140
+ * Add updated model EMA impl using _for_each for less overhead
141
+ * Support device args in train script for non GPU devices
142
+ * Other misc fixes and small additions
143
+ * Min supported Python version increased to 3.8
144
+ * Release 0.9.16
145
+
146
+ ### Jan 8, 2024
147
+ Datasets & transform refactoring
148
+ * HuggingFace streaming (iterable) dataset support (`--dataset hfids:org/dataset`)
149
+ * Webdataset wrapper tweaks for improved split info fetching, can auto fetch splits from supported HF hub webdataset
150
+ * Tested HF `datasets` and webdataset wrapper streaming from HF hub with recent `timm` ImageNet uploads to https://huggingface.co/timm
151
+ * Make input & target column/field keys consistent across datasets and pass via args
152
+ * Full monochrome support when using e:g: `--input-size 1 224 224` or `--in-chans 1`, sets PIL image conversion appropriately in dataset
153
+ * Improved several alternate crop & resize transforms (ResizeKeepRatio, RandomCropOrPad, etc) for use in PixParse document AI project
154
+ * Add SimCLR style color jitter prob along with grayscale and gaussian blur options to augmentations and args
155
+ * Allow train without validation set (`--val-split ''`) in train script
156
+ * Add `--bce-sum` (sum over class dim) and `--bce-pos-weight` (positive weighting) args for training as they're common BCE loss tweaks I was often hard coding
157
+
158
+ ### Nov 23, 2023
159
+ * Added EfficientViT-Large models, thanks [SeeFun](https://github.com/seefun)
160
+ * Fix Python 3.7 compat, will be dropping support for it soon
161
+ * Other misc fixes
162
+ * Release 0.9.12
163
+
164
+ ### Nov 20, 2023
165
+ * Added significant flexibility for Hugging Face Hub based timm models via `model_args` config entry. `model_args` will be passed as kwargs through to models on creation.
166
+ * See example at https://huggingface.co/gaunernst/vit_base_patch16_1024_128.audiomae_as2m_ft_as20k/blob/main/config.json
167
+ * Usage: https://github.com/huggingface/pytorch-image-models/discussions/2035
168
+ * Updated imagenet eval and test set csv files with latest models
169
+ * `vision_transformer.py` typing and doc cleanup by [Laureηt](https://github.com/Laurent2916)
170
+ * 0.9.11 release
171
+
172
+ ### Nov 3, 2023
173
+ * [DFN (Data Filtering Networks)](https://huggingface.co/papers/2309.17425) and [MetaCLIP](https://huggingface.co/papers/2309.16671) ViT weights added
174
+ * DINOv2 'register' ViT model weights added (https://huggingface.co/papers/2309.16588, https://huggingface.co/papers/2304.07193)
175
+ * Add `quickgelu` ViT variants for OpenAI, DFN, MetaCLIP weights that use it (less efficient)
176
+ * Improved typing added to ResNet, MobileNet-v3 thanks to [Aryan](https://github.com/a-r-r-o-w)
177
+ * ImageNet-12k fine-tuned (from LAION-2B CLIP) `convnext_xxlarge`
178
+ * 0.9.9 release
179
+
180
+ ### Oct 20, 2023
181
+ * [SigLIP](https://huggingface.co/papers/2303.15343) image tower weights supported in `vision_transformer.py`.
182
+ * Great potential for fine-tune and downstream feature use.
183
+ * Experimental 'register' support in vit models as per [Vision Transformers Need Registers](https://huggingface.co/papers/2309.16588)
184
+ * Updated RepViT with new weight release. Thanks [wangao](https://github.com/jameslahm)
185
+ * Add patch resizing support (on pretrained weight load) to Swin models
186
+ * 0.9.8 release pending
187
+
188
+ ### Sep 1, 2023
189
+ * TinyViT added by [SeeFun](https://github.com/seefun)
190
+ * Fix EfficientViT (MIT) to use torch.autocast so it works back to PT 1.10
191
+ * 0.9.7 release
192
+
193
+ ### Aug 28, 2023
194
+ * Add dynamic img size support to models in `vision_transformer.py`, `vision_transformer_hybrid.py`, `deit.py`, and `eva.py` w/o breaking backward compat.
195
+ * Add `dynamic_img_size=True` to args at model creation time to allow changing the grid size (interpolate abs and/or ROPE pos embed each forward pass).
196
+ * Add `dynamic_img_pad=True` to allow image sizes that aren't divisible by patch size (pad bottom right to patch size each forward pass).
197
+ * Enabling either dynamic mode will break FX tracing unless PatchEmbed module added as leaf.
198
+ * Existing method of resizing position embedding by passing different `img_size` (interpolate pretrained embed weights once) on creation still works.
199
+ * Existing method of changing `patch_size` (resize pretrained patch_embed weights once) on creation still works.
200
+ * Example validation cmd `python validate.py /imagenet --model vit_base_patch16_224 --amp --amp-dtype bfloat16 --img-size 255 --crop-pct 1.0 --model-kwargs dynamic_img_size=True dyamic_img_pad=True`
201
+
202
+ ### Aug 25, 2023
203
+ * Many new models since last release
204
+ * FastViT - https://arxiv.org/abs/2303.14189
205
+ * MobileOne - https://arxiv.org/abs/2206.04040
206
+ * InceptionNeXt - https://arxiv.org/abs/2303.16900
207
+ * RepGhostNet - https://arxiv.org/abs/2211.06088 (thanks https://github.com/ChengpengChen)
208
+ * GhostNetV2 - https://arxiv.org/abs/2211.12905 (thanks https://github.com/yehuitang)
209
+ * EfficientViT (MSRA) - https://arxiv.org/abs/2305.07027 (thanks https://github.com/seefun)
210
+ * EfficientViT (MIT) - https://arxiv.org/abs/2205.14756 (thanks https://github.com/seefun)
211
+ * Add `--reparam` arg to `benchmark.py`, `onnx_export.py`, and `validate.py` to trigger layer reparameterization / fusion for models with any one of `reparameterize()`, `switch_to_deploy()` or `fuse()`
212
+ * Including FastViT, MobileOne, RepGhostNet, EfficientViT (MSRA), RepViT, RepVGG, and LeViT
213
+ * Preparing 0.9.6 'back to school' release
214
+
215
+ ### Aug 11, 2023
216
+ * Swin, MaxViT, CoAtNet, and BEiT models support resizing of image/window size on creation with adaptation of pretrained weights
217
+ * Example validation cmd to test w/ non-square resize `python validate.py /imagenet --model swin_base_patch4_window7_224.ms_in22k_ft_in1k --amp --amp-dtype bfloat16 --input-size 3 256 320 --model-kwargs window_size=8,10 img_size=256,320`
218
+
219
+ ### Aug 3, 2023
220
+ * Add GluonCV weights for HRNet w18_small and w18_small_v2. Converted by [SeeFun](https://github.com/seefun)
221
+ * Fix `selecsls*` model naming regression
222
+ * Patch and position embedding for ViT/EVA works for bfloat16/float16 weights on load (or activations for on-the-fly resize)
223
+ * v0.9.5 release prep
224
+
225
+ ### July 27, 2023
226
+ * Added timm trained `seresnextaa201d_32x8d.sw_in12k_ft_in1k_384` weights (and `.sw_in12k` pretrain) with 87.3% top-1 on ImageNet-1k, best ImageNet ResNet family model I'm aware of.
227
+ * RepViT model and weights (https://arxiv.org/abs/2307.09283) added by [wangao](https://github.com/jameslahm)
228
+ * I-JEPA ViT feature weights (no classifier) added by [SeeFun](https://github.com/seefun)
229
+ * SAM-ViT (segment anything) feature weights (no classifier) added by [SeeFun](https://github.com/seefun)
230
+ * Add support for alternative feat extraction methods and -ve indices to EfficientNet
231
+ * Add NAdamW optimizer
232
+ * Misc fixes
233
+
234
+ ### May 11, 2023
235
+ * `timm` 0.9 released, transition from 0.8.xdev releases
236
+
237
+ ### May 10, 2023
238
+ * Hugging Face Hub downloading is now default, 1132 models on https://huggingface.co/timm, 1163 weights in `timm`
239
+ * DINOv2 vit feature backbone weights added thanks to [Leng Yue](https://github.com/leng-yue)
240
+ * FB MAE vit feature backbone weights added
241
+ * OpenCLIP DataComp-XL L/14 feat backbone weights added
242
+ * MetaFormer (poolformer-v2, caformer, convformer, updated poolformer (v1)) w/ weights added by [Fredo Guan](https://github.com/fffffgggg54)
243
+ * Experimental `get_intermediate_layers` function on vit/deit models for grabbing hidden states (inspired by DINO impl). This is WIP and may change significantly... feedback welcome.
244
+ * Model creation throws error if `pretrained=True` and no weights exist (instead of continuing with random initialization)
245
+ * Fix regression with inception / nasnet TF sourced weights with 1001 classes in original classifiers
246
+ * bitsandbytes (https://github.com/TimDettmers/bitsandbytes) optimizers added to factory, use `bnb` prefix, ie `bnbadam8bit`
247
+ * Misc cleanup and fixes
248
+ * Final testing before switching to a 0.9 and bringing `timm` out of pre-release state
249
+
250
+ ### April 27, 2023
251
+ * 97% of `timm` models uploaded to HF Hub and almost all updated to support multi-weight pretrained configs
252
+ * Minor cleanup and refactoring of another batch of models as multi-weight added. More fused_attn (F.sdpa) and features_only support, and torchscript fixes.
253
+
254
+ ### April 21, 2023
255
+ * Gradient accumulation support added to train script and tested (`--grad-accum-steps`), thanks [Taeksang Kim](https://github.com/voidbag)
256
+ * More weights on HF Hub (cspnet, cait, volo, xcit, tresnet, hardcorenas, densenet, dpn, vovnet, xception_aligned)
257
+ * Added `--head-init-scale` and `--head-init-bias` to train.py to scale classiifer head and set fixed bias for fine-tune
258
+ * Remove all InplaceABN (`inplace_abn`) use, replaced use in tresnet with standard BatchNorm (modified weights accordingly).
259
+
260
+ ### April 12, 2023
261
+ * Add ONNX export script, validate script, helpers that I've had kicking around for along time. Tweak 'same' padding for better export w/ recent ONNX + pytorch.
262
+ * Refactor dropout args for vit and vit-like models, separate drop_rate into `drop_rate` (classifier dropout), `proj_drop_rate` (block mlp / out projections), `pos_drop_rate` (position embedding drop), `attn_drop_rate` (attention dropout). Also add patch dropout (FLIP) to vit and eva models.
263
+ * fused F.scaled_dot_product_attention support to more vit models, add env var (TIMM_FUSED_ATTN) to control, and config interface to enable/disable
264
+ * Add EVA-CLIP backbones w/ image tower weights, all the way up to 4B param 'enormous' model, and 336x336 OpenAI ViT mode that was missed.
265
+
266
+ ### April 5, 2023
267
+ * ALL ResNet models pushed to Hugging Face Hub with multi-weight support
268
+ * All past `timm` trained weights added with recipe based tags to differentiate
269
+ * All ResNet strikes back A1/A2/A3 (seed 0) and R50 example B/C1/C2/D weights available
270
+ * Add torchvision v2 recipe weights to existing torchvision originals
271
+ * See comparison table in https://huggingface.co/timm/seresnextaa101d_32x8d.sw_in12k_ft_in1k_288#model-comparison
272
+ * New ImageNet-12k + ImageNet-1k fine-tunes available for a few anti-aliased ResNet models
273
+ * `resnetaa50d.sw_in12k_ft_in1k` - 81.7 @ 224, 82.6 @ 288
274
+ * `resnetaa101d.sw_in12k_ft_in1k` - 83.5 @ 224, 84.1 @ 288
275
+ * `seresnextaa101d_32x8d.sw_in12k_ft_in1k` - 86.0 @ 224, 86.5 @ 288
276
+ * `seresnextaa101d_32x8d.sw_in12k_ft_in1k_288` - 86.5 @ 288, 86.7 @ 320
277
+
278
+ ### March 31, 2023
279
+ * Add first ConvNext-XXLarge CLIP -> IN-1k fine-tune and IN-12k intermediate fine-tunes for convnext-base/large CLIP models.
280
+
281
+ | model |top1 |top5 |img_size|param_count|gmacs |macts |
282
+ |----------------------------------------------------------------------------------------------------------------------|------|------|--------|-----------|------|------|
283
+ | [convnext_xxlarge.clip_laion2b_soup_ft_in1k](https://huggingface.co/timm/convnext_xxlarge.clip_laion2b_soup_ft_in1k) |88.612|98.704|256 |846.47 |198.09|124.45|
284
+ | convnext_large_mlp.clip_laion2b_soup_ft_in12k_in1k_384 |88.312|98.578|384 |200.13 |101.11|126.74|
285
+ | convnext_large_mlp.clip_laion2b_soup_ft_in12k_in1k_320 |87.968|98.47 |320 |200.13 |70.21 |88.02 |
286
+ | convnext_base.clip_laion2b_augreg_ft_in12k_in1k_384 |87.138|98.212|384 |88.59 |45.21 |84.49 |
287
+ | convnext_base.clip_laion2b_augreg_ft_in12k_in1k |86.344|97.97 |256 |88.59 |20.09 |37.55 |
288
+
289
+ * Add EVA-02 MIM pretrained and fine-tuned weights, push to HF hub and update model cards for all EVA models. First model over 90% top-1 (99% top-5)! Check out the original code & weights at https://github.com/baaivision/EVA for more details on their work blending MIM, CLIP w/ many model, dataset, and train recipe tweaks.
290
+
291
+ | model |top1 |top5 |param_count|img_size|
292
+ |----------------------------------------------------|------|------|-----------|--------|
293
+ | [eva02_large_patch14_448.mim_m38m_ft_in22k_in1k](https://huggingface.co/timm/eva02_large_patch14_448.mim_m38m_ft_in1k) |90.054|99.042|305.08 |448 |
294
+ | eva02_large_patch14_448.mim_in22k_ft_in22k_in1k |89.946|99.01 |305.08 |448 |
295
+ | eva_giant_patch14_560.m30m_ft_in22k_in1k |89.792|98.992|1014.45 |560 |
296
+ | eva02_large_patch14_448.mim_in22k_ft_in1k |89.626|98.954|305.08 |448 |
297
+ | eva02_large_patch14_448.mim_m38m_ft_in1k |89.57 |98.918|305.08 |448 |
298
+ | eva_giant_patch14_336.m30m_ft_in22k_in1k |89.56 |98.956|1013.01 |336 |
299
+ | eva_giant_patch14_336.clip_ft_in1k |89.466|98.82 |1013.01 |336 |
300
+ | eva_large_patch14_336.in22k_ft_in22k_in1k |89.214|98.854|304.53 |336 |
301
+ | eva_giant_patch14_224.clip_ft_in1k |88.882|98.678|1012.56 |224 |
302
+ | eva02_base_patch14_448.mim_in22k_ft_in22k_in1k |88.692|98.722|87.12 |448 |
303
+ | eva_large_patch14_336.in22k_ft_in1k |88.652|98.722|304.53 |336 |
304
+ | eva_large_patch14_196.in22k_ft_in22k_in1k |88.592|98.656|304.14 |196 |
305
+ | eva02_base_patch14_448.mim_in22k_ft_in1k |88.23 |98.564|87.12 |448 |
306
+ | eva_large_patch14_196.in22k_ft_in1k |87.934|98.504|304.14 |196 |
307
+ | eva02_small_patch14_336.mim_in22k_ft_in1k |85.74 |97.614|22.13 |336 |
308
+ | eva02_tiny_patch14_336.mim_in22k_ft_in1k |80.658|95.524|5.76 |336 |
309
+
310
+ * Multi-weight and HF hub for DeiT and MLP-Mixer based models
311
+
312
+ ### March 22, 2023
313
+ * More weights pushed to HF hub along with multi-weight support, including: `regnet.py`, `rexnet.py`, `byobnet.py`, `resnetv2.py`, `swin_transformer.py`, `swin_transformer_v2.py`, `swin_transformer_v2_cr.py`
314
+ * Swin Transformer models support feature extraction (NCHW feat maps for `swinv2_cr_*`, and NHWC for all others) and spatial embedding outputs.
315
+ * FocalNet (from https://github.com/microsoft/FocalNet) models and weights added with significant refactoring, feature extraction, no fixed resolution / sizing constraint
316
+ * RegNet weights increased with HF hub push, SWAG, SEER, and torchvision v2 weights. SEER is pretty poor wrt to performance for model size, but possibly useful.
317
+ * More ImageNet-12k pretrained and 1k fine-tuned `timm` weights:
318
+ * `rexnetr_200.sw_in12k_ft_in1k` - 82.6 @ 224, 83.2 @ 288
319
+ * `rexnetr_300.sw_in12k_ft_in1k` - 84.0 @ 224, 84.5 @ 288
320
+ * `regnety_120.sw_in12k_ft_in1k` - 85.0 @ 224, 85.4 @ 288
321
+ * `regnety_160.lion_in12k_ft_in1k` - 85.6 @ 224, 86.0 @ 288
322
+ * `regnety_160.sw_in12k_ft_in1k` - 85.6 @ 224, 86.0 @ 288 (compare to SWAG PT + 1k FT this is same BUT much lower res, blows SEER FT away)
323
+ * Model name deprecation + remapping functionality added (a milestone for bringing 0.8.x out of pre-release). Mappings being added...
324
+ * Minor bug fixes and improvements.
325
+
326
+ ### Feb 26, 2023
327
+ * Add ConvNeXt-XXLarge CLIP pretrained image tower weights for fine-tune & features (fine-tuning TBD) -- see [model card](https://huggingface.co/laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-soup)
328
+ * Update `convnext_xxlarge` default LayerNorm eps to 1e-5 (for CLIP weights, improved stability)
329
+ * 0.8.15dev0
330
+
331
+ ### Feb 20, 2023
332
+ * Add 320x320 `convnext_large_mlp.clip_laion2b_ft_320` and `convnext_lage_mlp.clip_laion2b_ft_soup_320` CLIP image tower weights for features & fine-tune
333
+ * 0.8.13dev0 pypi release for latest changes w/ move to huggingface org
334
+
335
+ ### Feb 16, 2023
336
+ * `safetensor` checkpoint support added
337
+ * Add ideas from 'Scaling Vision Transformers to 22 B. Params' (https://arxiv.org/abs/2302.05442) -- qk norm, RmsNorm, parallel block
338
+ * Add F.scaled_dot_product_attention support (PyTorch 2.0 only) to `vit_*`, `vit_relpos*`, `coatnet` / `maxxvit` (to start)
339
+ * Lion optimizer (w/ multi-tensor option) added (https://arxiv.org/abs/2302.06675)
340
+ * gradient checkpointing works with `features_only=True`
341
+
342
+ ## Introduction
343
+
344
+ Py**T**orch **Im**age **M**odels (`timm`) is a collection of image models, layers, utilities, optimizers, schedulers, data-loaders / augmentations, and reference training / validation scripts that aim to pull together a wide variety of SOTA models with ability to reproduce ImageNet training results.
345
+
346
+ The work of many others is present here. I've tried to make sure all source material is acknowledged via links to github, arxiv papers, etc in the README, documentation, and code docstrings. Please let me know if I missed anything.
347
+
348
+ ## Features
349
+
350
+ ### Models
351
+
352
+ All model architecture families include variants with pretrained weights. There are specific model variants without any weights, it is NOT a bug. Help training new or better weights is always appreciated.
353
+
354
+ * Aggregating Nested Transformers - https://arxiv.org/abs/2105.12723
355
+ * BEiT - https://arxiv.org/abs/2106.08254
356
+ * Big Transfer ResNetV2 (BiT) - https://arxiv.org/abs/1912.11370
357
+ * Bottleneck Transformers - https://arxiv.org/abs/2101.11605
358
+ * CaiT (Class-Attention in Image Transformers) - https://arxiv.org/abs/2103.17239
359
+ * CoaT (Co-Scale Conv-Attentional Image Transformers) - https://arxiv.org/abs/2104.06399
360
+ * CoAtNet (Convolution and Attention) - https://arxiv.org/abs/2106.04803
361
+ * ConvNeXt - https://arxiv.org/abs/2201.03545
362
+ * ConvNeXt-V2 - http://arxiv.org/abs/2301.00808
363
+ * ConViT (Soft Convolutional Inductive Biases Vision Transformers)- https://arxiv.org/abs/2103.10697
364
+ * CspNet (Cross-Stage Partial Networks) - https://arxiv.org/abs/1911.11929
365
+ * DeiT - https://arxiv.org/abs/2012.12877
366
+ * DeiT-III - https://arxiv.org/pdf/2204.07118.pdf
367
+ * DenseNet - https://arxiv.org/abs/1608.06993
368
+ * DLA - https://arxiv.org/abs/1707.06484
369
+ * DPN (Dual-Path Network) - https://arxiv.org/abs/1707.01629
370
+ * EdgeNeXt - https://arxiv.org/abs/2206.10589
371
+ * EfficientFormer - https://arxiv.org/abs/2206.01191
372
+ * EfficientNet (MBConvNet Family)
373
+ * EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252
374
+ * EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665
375
+ * EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946
376
+ * EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html
377
+ * EfficientNet V2 - https://arxiv.org/abs/2104.00298
378
+ * FBNet-C - https://arxiv.org/abs/1812.03443
379
+ * MixNet - https://arxiv.org/abs/1907.09595
380
+ * MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626
381
+ * MobileNet-V2 - https://arxiv.org/abs/1801.04381
382
+ * Single-Path NAS - https://arxiv.org/abs/1904.02877
383
+ * TinyNet - https://arxiv.org/abs/2010.14819
384
+ * EfficientViT (MIT) - https://arxiv.org/abs/2205.14756
385
+ * EfficientViT (MSRA) - https://arxiv.org/abs/2305.07027
386
+ * EVA - https://arxiv.org/abs/2211.07636
387
+ * EVA-02 - https://arxiv.org/abs/2303.11331
388
+ * FastViT - https://arxiv.org/abs/2303.14189
389
+ * FlexiViT - https://arxiv.org/abs/2212.08013
390
+ * FocalNet (Focal Modulation Networks) - https://arxiv.org/abs/2203.11926
391
+ * GCViT (Global Context Vision Transformer) - https://arxiv.org/abs/2206.09959
392
+ * GhostNet - https://arxiv.org/abs/1911.11907
393
+ * GhostNet-V2 - https://arxiv.org/abs/2211.12905
394
+ * gMLP - https://arxiv.org/abs/2105.08050
395
+ * GPU-Efficient Networks - https://arxiv.org/abs/2006.14090
396
+ * Halo Nets - https://arxiv.org/abs/2103.12731
397
+ * HGNet / HGNet-V2 - TBD
398
+ * HRNet - https://arxiv.org/abs/1908.07919
399
+ * InceptionNeXt - https://arxiv.org/abs/2303.16900
400
+ * Inception-V3 - https://arxiv.org/abs/1512.00567
401
+ * Inception-ResNet-V2 and Inception-V4 - https://arxiv.org/abs/1602.07261
402
+ * Lambda Networks - https://arxiv.org/abs/2102.08602
403
+ * LeViT (Vision Transformer in ConvNet's Clothing) - https://arxiv.org/abs/2104.01136
404
+ * MaxViT (Multi-Axis Vision Transformer) - https://arxiv.org/abs/2204.01697
405
+ * MetaFormer (PoolFormer-v2, ConvFormer, CAFormer) - https://arxiv.org/abs/2210.13452
406
+ * MLP-Mixer - https://arxiv.org/abs/2105.01601
407
+ * MobileNet-V3 (MBConvNet w/ Efficient Head) - https://arxiv.org/abs/1905.02244
408
+ * FBNet-V3 - https://arxiv.org/abs/2006.02049
409
+ * HardCoRe-NAS - https://arxiv.org/abs/2102.11646
410
+ * LCNet - https://arxiv.org/abs/2109.15099
411
+ * MobileOne - https://arxiv.org/abs/2206.04040
412
+ * MobileViT - https://arxiv.org/abs/2110.02178
413
+ * MobileViT-V2 - https://arxiv.org/abs/2206.02680
414
+ * MViT-V2 (Improved Multiscale Vision Transformer) - https://arxiv.org/abs/2112.01526
415
+ * NASNet-A - https://arxiv.org/abs/1707.07012
416
+ * NesT - https://arxiv.org/abs/2105.12723
417
+ * Next-ViT - https://arxiv.org/abs/2207.05501
418
+ * NFNet-F - https://arxiv.org/abs/2102.06171
419
+ * NF-RegNet / NF-ResNet - https://arxiv.org/abs/2101.08692
420
+ * PNasNet - https://arxiv.org/abs/1712.00559
421
+ * PoolFormer (MetaFormer) - https://arxiv.org/abs/2111.11418
422
+ * Pooling-based Vision Transformer (PiT) - https://arxiv.org/abs/2103.16302
423
+ * PVT-V2 (Improved Pyramid Vision Transformer) - https://arxiv.org/abs/2106.13797
424
+ * RegNet - https://arxiv.org/abs/2003.13678
425
+ * RegNetZ - https://arxiv.org/abs/2103.06877
426
+ * RepVGG - https://arxiv.org/abs/2101.03697
427
+ * RepGhostNet - https://arxiv.org/abs/2211.06088
428
+ * RepViT - https://arxiv.org/abs/2307.09283
429
+ * ResMLP - https://arxiv.org/abs/2105.03404
430
+ * ResNet/ResNeXt
431
+ * ResNet (v1b/v1.5) - https://arxiv.org/abs/1512.03385
432
+ * ResNeXt - https://arxiv.org/abs/1611.05431
433
+ * 'Bag of Tricks' / Gluon C, D, E, S variations - https://arxiv.org/abs/1812.01187
434
+ * Weakly-supervised (WSL) Instagram pretrained / ImageNet tuned ResNeXt101 - https://arxiv.org/abs/1805.00932
435
+ * Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet/ResNeXts - https://arxiv.org/abs/1905.00546
436
+ * ECA-Net (ECAResNet) - https://arxiv.org/abs/1910.03151v4
437
+ * Squeeze-and-Excitation Networks (SEResNet) - https://arxiv.org/abs/1709.01507
438
+ * ResNet-RS - https://arxiv.org/abs/2103.07579
439
+ * Res2Net - https://arxiv.org/abs/1904.01169
440
+ * ResNeSt - https://arxiv.org/abs/2004.08955
441
+ * ReXNet - https://arxiv.org/abs/2007.00992
442
+ * SelecSLS - https://arxiv.org/abs/1907.00837
443
+ * Selective Kernel Networks - https://arxiv.org/abs/1903.06586
444
+ * Sequencer2D - https://arxiv.org/abs/2205.01972
445
+ * Swin S3 (AutoFormerV2) - https://arxiv.org/abs/2111.14725
446
+ * Swin Transformer - https://arxiv.org/abs/2103.14030
447
+ * Swin Transformer V2 - https://arxiv.org/abs/2111.09883
448
+ * Transformer-iN-Transformer (TNT) - https://arxiv.org/abs/2103.00112
449
+ * TResNet - https://arxiv.org/abs/2003.13630
450
+ * Twins (Spatial Attention in Vision Transformers) - https://arxiv.org/pdf/2104.13840.pdf
451
+ * Visformer - https://arxiv.org/abs/2104.12533
452
+ * Vision Transformer - https://arxiv.org/abs/2010.11929
453
+ * VOLO (Vision Outlooker) - https://arxiv.org/abs/2106.13112
454
+ * VovNet V2 and V1 - https://arxiv.org/abs/1911.06667
455
+ * Xception - https://arxiv.org/abs/1610.02357
456
+ * Xception (Modified Aligned, Gluon) - https://arxiv.org/abs/1802.02611
457
+ * Xception (Modified Aligned, TF) - https://arxiv.org/abs/1802.02611
458
+ * XCiT (Cross-Covariance Image Transformers) - https://arxiv.org/abs/2106.09681
459
+
460
+ ### Optimizers
461
+
462
+ Included optimizers available via `create_optimizer` / `create_optimizer_v2` factory methods:
463
+ * `adabelief` an implementation of AdaBelief adapted from https://github.com/juntang-zhuang/Adabelief-Optimizer - https://arxiv.org/abs/2010.07468
464
+ * `adafactor` adapted from [FAIRSeq impl](https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py) - https://arxiv.org/abs/1804.04235
465
+ * `adahessian` by [David Samuel](https://github.com/davda54/ada-hessian) - https://arxiv.org/abs/2006.00719
466
+ * `adamp` and `sgdp` by [Naver ClovAI](https://github.com/clovaai) - https://arxiv.org/abs/2006.08217
467
+ * `adan` an implementation of Adan adapted from https://github.com/sail-sg/Adan - https://arxiv.org/abs/2208.06677
468
+ * `lamb` an implementation of Lamb and LambC (w/ trust-clipping) cleaned up and modified to support use with XLA - https://arxiv.org/abs/1904.00962
469
+ * `lars` an implementation of LARS and LARC (w/ trust-clipping) - https://arxiv.org/abs/1708.03888
470
+ * `lion` and implementation of Lion adapted from https://github.com/google/automl/tree/master/lion - https://arxiv.org/abs/2302.06675
471
+ * `lookahead` adapted from impl by [Liam](https://github.com/alphadl/lookahead.pytorch) - https://arxiv.org/abs/1907.08610
472
+ * `madgrad` - and implementation of MADGRAD adapted from https://github.com/facebookresearch/madgrad - https://arxiv.org/abs/2101.11075
473
+ * `nadam` an implementation of Adam w/ Nesterov momentum
474
+ * `nadamw` an impementation of AdamW (Adam w/ decoupled weight-decay) w/ Nesterov momentum. A simplified impl based on https://github.com/mlcommons/algorithmic-efficiency
475
+ * `novograd` by [Masashi Kimura](https://github.com/convergence-lab/novograd) - https://arxiv.org/abs/1905.11286
476
+ * `radam` by [Liyuan Liu](https://github.com/LiyuanLucasLiu/RAdam) - https://arxiv.org/abs/1908.03265
477
+ * `rmsprop_tf` adapted from PyTorch RMSProp by myself. Reproduces much improved Tensorflow RMSProp behaviour
478
+ * `sgdw` and implementation of SGD w/ decoupled weight-decay
479
+ * `fused<name>` optimizers by name with [NVIDIA Apex](https://github.com/NVIDIA/apex/tree/master/apex/optimizers) installed
480
+ * `bits<name>` optimizers by name with [BitsAndBytes](https://github.com/TimDettmers/bitsandbytes) installed
481
+
482
+ ### Augmentations
483
+ * Random Erasing from [Zhun Zhong](https://github.com/zhunzhong07/Random-Erasing/blob/master/transforms.py) - https://arxiv.org/abs/1708.04896)
484
+ * Mixup - https://arxiv.org/abs/1710.09412
485
+ * CutMix - https://arxiv.org/abs/1905.04899
486
+ * AutoAugment (https://arxiv.org/abs/1805.09501) and RandAugment (https://arxiv.org/abs/1909.13719) ImageNet configurations modeled after impl for EfficientNet training (https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py)
487
+ * AugMix w/ JSD loss, JSD w/ clean + augmented mixing support works with AutoAugment and RandAugment as well - https://arxiv.org/abs/1912.02781
488
+ * SplitBachNorm - allows splitting batch norm layers between clean and augmented (auxiliary batch norm) data
489
+
490
+ ### Regularization
491
+ * DropPath aka "Stochastic Depth" - https://arxiv.org/abs/1603.09382
492
+ * DropBlock - https://arxiv.org/abs/1810.12890
493
+ * Blur Pooling - https://arxiv.org/abs/1904.11486
494
+
495
+ ### Other
496
+
497
+ Several (less common) features that I often utilize in my projects are included. Many of their additions are the reason why I maintain my own set of models, instead of using others' via PIP:
498
+
499
+ * All models have a common default configuration interface and API for
500
+ * accessing/changing the classifier - `get_classifier` and `reset_classifier`
501
+ * doing a forward pass on just the features - `forward_features` (see [documentation](https://huggingface.co/docs/timm/feature_extraction))
502
+ * these makes it easy to write consistent network wrappers that work with any of the models
503
+ * All models support multi-scale feature map extraction (feature pyramids) via create_model (see [documentation](https://huggingface.co/docs/timm/feature_extraction))
504
+ * `create_model(name, features_only=True, out_indices=..., output_stride=...)`
505
+ * `out_indices` creation arg specifies which feature maps to return, these indices are 0 based and generally correspond to the `C(i + 1)` feature level.
506
+ * `output_stride` creation arg controls output stride of the network by using dilated convolutions. Most networks are stride 32 by default. Not all networks support this.
507
+ * feature map channel counts, reduction level (stride) can be queried AFTER model creation via the `.feature_info` member
508
+ * All models have a consistent pretrained weight loader that adapts last linear if necessary, and from 3 to 1 channel input if desired
509
+ * High performance [reference training, validation, and inference scripts](https://huggingface.co/docs/timm/training_script) that work in several process/GPU modes:
510
+ * NVIDIA DDP w/ a single GPU per process, multiple processes with APEX present (AMP mixed-precision optional)
511
+ * PyTorch DistributedDataParallel w/ multi-gpu, single process (AMP disabled as it crashes when enabled)
512
+ * PyTorch w/ single GPU single process (AMP optional)
513
+ * A dynamic global pool implementation that allows selecting from average pooling, max pooling, average + max, or concat([average, max]) at model creation. All global pooling is adaptive average by default and compatible with pretrained weights.
514
+ * A 'Test Time Pool' wrapper that can wrap any of the included models and usually provides improved performance doing inference with input images larger than the training size. Idea adapted from original DPN implementation when I ported (https://github.com/cypw/DPNs)
515
+ * Learning rate schedulers
516
+ * Ideas adopted from
517
+ * [AllenNLP schedulers](https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers)
518
+ * [FAIRseq lr_scheduler](https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler)
519
+ * SGDR: Stochastic Gradient Descent with Warm Restarts (https://arxiv.org/abs/1608.03983)
520
+ * Schedulers include `step`, `cosine` w/ restarts, `tanh` w/ restarts, `plateau`
521
+ * Space-to-Depth by [mrT23](https://github.com/mrT23/TResNet/blob/master/src/models/tresnet/layers/space_to_depth.py) (https://arxiv.org/abs/1801.04590) -- original paper?
522
+ * Adaptive Gradient Clipping (https://arxiv.org/abs/2102.06171, https://github.com/deepmind/deepmind-research/tree/master/nfnets)
523
+ * An extensive selection of channel and/or spatial attention modules:
524
+ * Bottleneck Transformer - https://arxiv.org/abs/2101.11605
525
+ * CBAM - https://arxiv.org/abs/1807.06521
526
+ * Effective Squeeze-Excitation (ESE) - https://arxiv.org/abs/1911.06667
527
+ * Efficient Channel Attention (ECA) - https://arxiv.org/abs/1910.03151
528
+ * Gather-Excite (GE) - https://arxiv.org/abs/1810.12348
529
+ * Global Context (GC) - https://arxiv.org/abs/1904.11492
530
+ * Halo - https://arxiv.org/abs/2103.12731
531
+ * Involution - https://arxiv.org/abs/2103.06255
532
+ * Lambda Layer - https://arxiv.org/abs/2102.08602
533
+ * Non-Local (NL) - https://arxiv.org/abs/1711.07971
534
+ * Squeeze-and-Excitation (SE) - https://arxiv.org/abs/1709.01507
535
+ * Selective Kernel (SK) - (https://arxiv.org/abs/1903.06586
536
+ * Split (SPLAT) - https://arxiv.org/abs/2004.08955
537
+ * Shifted Window (SWIN) - https://arxiv.org/abs/2103.14030
538
+
539
+ ## Results
540
+
541
+ Model validation results can be found in the [results tables](results/README.md)
542
+
543
+ ## Getting Started (Documentation)
544
+
545
+ The official documentation can be found at https://huggingface.co/docs/hub/timm. Documentation contributions are welcome.
546
+
547
+ [Getting Started with PyTorch Image Models (timm): A Practitioner’s Guide](https://towardsdatascience.com/getting-started-with-pytorch-image-models-timm-a-practitioners-guide-4e77b4bf9055) by [Chris Hughes](https://github.com/Chris-hughes10) is an extensive blog post covering many aspects of `timm` in detail.
548
+
549
+ [timmdocs](http://timm.fast.ai/) is an alternate set of documentation for `timm`. A big thanks to [Aman Arora](https://github.com/amaarora) for his efforts creating timmdocs.
550
+
551
+ [paperswithcode](https://paperswithcode.com/lib/timm) is a good resource for browsing the models within `timm`.
552
+
553
+ ## Train, Validation, Inference Scripts
554
+
555
+ The root folder of the repository contains reference train, validation, and inference scripts that work with the included models and other features of this repository. They are adaptable for other datasets and use cases with a little hacking. See [documentation](https://huggingface.co/docs/timm/training_script).
556
+
557
+ ## Awesome PyTorch Resources
558
+
559
+ One of the greatest assets of PyTorch is the community and their contributions. A few of my favourite resources that pair well with the models and components here are listed below.
560
+
561
+ ### Object Detection, Instance and Semantic Segmentation
562
+ * Detectron2 - https://github.com/facebookresearch/detectron2
563
+ * Segmentation Models (Semantic) - https://github.com/qubvel/segmentation_models.pytorch
564
+ * EfficientDet (Obj Det, Semantic soon) - https://github.com/rwightman/efficientdet-pytorch
565
+
566
+ ### Computer Vision / Image Augmentation
567
+ * Albumentations - https://github.com/albumentations-team/albumentations
568
+ * Kornia - https://github.com/kornia/kornia
569
+
570
+ ### Knowledge Distillation
571
+ * RepDistiller - https://github.com/HobbitLong/RepDistiller
572
+ * torchdistill - https://github.com/yoshitomo-matsubara/torchdistill
573
+
574
+ ### Metric Learning
575
+ * PyTorch Metric Learning - https://github.com/KevinMusgrave/pytorch-metric-learning
576
+
577
+ ### Training / Frameworks
578
+ * fastai - https://github.com/fastai/fastai
579
+
580
+ ## Licenses
581
+
582
+ ### Code
583
+ The code here is licensed Apache 2.0. I've taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. I've made an effort to avoid any GPL / LGPL conflicts. That said, it is your responsibility to ensure you comply with licenses here and conditions of any dependent licenses. Where applicable, I've linked the sources/references for various components in docstrings. If you think I've missed anything please create an issue.
584
+
585
+ ### Pretrained Weights
586
+ So far all of the pretrained weights available here are pretrained on ImageNet with a select few that have some additional pretraining (see extra note below). ImageNet was released for non-commercial research purposes only (https://image-net.org/download). It's not clear what the implications of that are for the use of pretrained weights from that dataset. Any models I have trained with ImageNet are done for research purposes and one should assume that the original dataset license applies to the weights. It's best to seek legal advice if you intend to use the pretrained weights in a commercial product.
587
+
588
+ #### Pretrained on more than ImageNet
589
+ Several weights included or references here were pretrained with proprietary datasets that I do not have access to. These include the Facebook WSL, SSL, SWSL ResNe(Xt) and the Google Noisy Student EfficientNet models. The Facebook models have an explicit non-commercial license (CC-BY-NC 4.0, https://github.com/facebookresearch/semi-supervised-ImageNet1K-models, https://github.com/facebookresearch/WSL-Images). The Google models do not appear to have any restriction beyond the Apache 2.0 license (and ImageNet concerns). In either case, you should contact Facebook or Google with any questions.
590
+
591
+ ## Citing
592
+
593
+ ### BibTeX
594
+
595
+ ```bibtex
596
+ @misc{rw2019timm,
597
+ author = {Ross Wightman},
598
+ title = {PyTorch Image Models},
599
+ year = {2019},
600
+ publisher = {GitHub},
601
+ journal = {GitHub repository},
602
+ doi = {10.5281/zenodo.4414861},
603
+ howpublished = {\url{https://github.com/rwightman/pytorch-image-models}}
604
+ }
605
+ ```
606
+
607
+ ### Latest DOI
608
+
609
+ [![DOI](https://zenodo.org/badge/168799526.svg)](https://zenodo.org/badge/latestdoi/168799526)
videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/RECORD ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ timm-1.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ timm-1.0.3.dist-info/METADATA,sha256=gFPUgkNFYqViN6ruFuJc8RABDrTC_NEMYXiPv8RR0nE,43575
3
+ timm-1.0.3.dist-info/RECORD,,
4
+ timm-1.0.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ timm-1.0.3.dist-info/WHEEL,sha256=vnE8JVcI2Wz7GRKorsPArnBdnW2SWKWGow5gu5tHlRU,90
6
+ timm-1.0.3.dist-info/licenses/LICENSE,sha256=cbERYg-jLBeoDM1tstp1nTGlkeSX2LXzghdPWdG1nUk,11343
7
+ timm/__init__.py,sha256=0bkaVTGjSB6BZhqG8Fw6PFcmGXI47BdNt4cg-eA_QdA,292
8
+ timm/__pycache__/__init__.cpython-310.pyc,,
9
+ timm/__pycache__/version.cpython-310.pyc,,
10
+ timm/data/__init__.py,sha256=z6Rudp7e489CWoOw3TXBMG0A1mzXSgGBWz5MptnPAW0,819
11
+ timm/data/__pycache__/__init__.cpython-310.pyc,,
12
+ timm/data/__pycache__/auto_augment.cpython-310.pyc,,
13
+ timm/data/__pycache__/config.cpython-310.pyc,,
14
+ timm/data/__pycache__/constants.cpython-310.pyc,,
15
+ timm/data/__pycache__/dataset.cpython-310.pyc,,
16
+ timm/data/__pycache__/dataset_factory.cpython-310.pyc,,
17
+ timm/data/__pycache__/dataset_info.cpython-310.pyc,,
18
+ timm/data/__pycache__/distributed_sampler.cpython-310.pyc,,
19
+ timm/data/__pycache__/imagenet_info.cpython-310.pyc,,
20
+ timm/data/__pycache__/loader.cpython-310.pyc,,
21
+ timm/data/__pycache__/mixup.cpython-310.pyc,,
22
+ timm/data/__pycache__/random_erasing.cpython-310.pyc,,
23
+ timm/data/__pycache__/real_labels.cpython-310.pyc,,
24
+ timm/data/__pycache__/tf_preprocessing.cpython-310.pyc,,
25
+ timm/data/__pycache__/transforms.cpython-310.pyc,,
26
+ timm/data/__pycache__/transforms_factory.cpython-310.pyc,,
27
+ timm/data/_info/imagenet12k_synsets.txt,sha256=9kg-efGKm2cNQ9kV3bpAu8r4LPxOkqB71EBXudRJNfM,118210
28
+ timm/data/_info/imagenet21k_goog_synsets.txt,sha256=ZjYr3t822TM4LtylST_FYtzBcSjONkA8nnMKdfSMsvI,218430
29
+ timm/data/_info/imagenet21k_goog_to_12k_indices.txt,sha256=a1iOnVXH_tZ6rILpG-6r5-rOLeHtZxFQEMoHYXnoxQg,64070
30
+ timm/data/_info/imagenet21k_goog_to_22k_indices.txt,sha256=hqdngDZvgHqfgEYX6iRMob9YF0FNAzDPEbop4oXBzFc,119937
31
+ timm/data/_info/imagenet21k_miil_synsets.txt,sha256=zXbZd9qqLxOkqR_KD1NxPy8pZ1MI1M4PDuDlsHoxZMY,112210
32
+ timm/data/_info/imagenet21k_miil_w21_synsets.txt,sha256=9J3ePWmUa4Y1WGQy8081mF-AfRaChs5f3nRqrDp9lMg,104500
33
+ timm/data/_info/imagenet22k_ms_synsets.txt,sha256=8sesR1AOHR1wQy08suKyGHxogBJUOYMr9LQDj3Fsong,218420
34
+ timm/data/_info/imagenet22k_ms_to_12k_indices.txt,sha256=wMkQkjtw2JKm-KzN6bDKvaqN1nuMD8_QuC1IFVei1js,63625
35
+ timm/data/_info/imagenet22k_ms_to_22k_indices.txt,sha256=Sp_dB0M-ncOF_j_rAhWGMI-JSj3LhfSIKyXtIEz2MyE,119938
36
+ timm/data/_info/imagenet22k_synsets.txt,sha256=CuJFOHUZc3l7KdjexBKyvcYbxOw-zQgeugc1gEI2u9I,218410
37
+ timm/data/_info/imagenet22k_to_12k_indices.txt,sha256=0_-qtIBkurHqfOFibHL1oBHuRQPKxhK5DuHaDRR8joc,64070
38
+ timm/data/_info/imagenet_a_indices.txt,sha256=6BIjo1rdbnj5r-byFWUsGSbr7-HY78JsbpI9eskUOTc,774
39
+ timm/data/_info/imagenet_a_synsets.txt,sha256=mCaiQWbnTOYvuHsniJh0yiaRdULHRXEjCdbiWFXWO8I,2000
40
+ timm/data/_info/imagenet_r_indices.txt,sha256=keCdL_CgAhBLwNN6iSp-df_CzA20eytQYEejSTuRFtI,769
41
+ timm/data/_info/imagenet_r_synsets.txt,sha256=pqByn3qZIwKAY5yrblHgFIWjtBpnbqNWIaUBydboPKQ,2000
42
+ timm/data/_info/imagenet_real_labels.json,sha256=2D6b_zdMYxquhDnrBkxwGazFbhs7w_Vrg4DCpxCwIgs,388478
43
+ timm/data/_info/imagenet_synset_to_definition.txt,sha256=GR4ifUj8jHt-LSo8rEH8iy61F9nSgZ0O28kcV2clDu0,1748917
44
+ timm/data/_info/imagenet_synset_to_lemma.txt,sha256=G4ur2hh0IaS94MnFoZfDb2vdqWL3yhH_soE4BsuyF48,741457
45
+ timm/data/_info/imagenet_synsets.txt,sha256=cAArD_XeYKOheoLb_P8pGTH5YiXd-UGtLhgvw54YPRU,10000
46
+ timm/data/auto_augment.py,sha256=E1JZWZLV6GZowIkeAFU0ZuaF7MhHkoaSbKVQogLDinA,35550
47
+ timm/data/config.py,sha256=uf2p-mNW_wntCe34K_Xr3J45cJh8IWEl_cMwgyKGR-g,4616
48
+ timm/data/constants.py,sha256=ZkSr7QArcsDyOOBRYQpLe4c2VOJKRAYoDRU1JwYJseE,442
49
+ timm/data/dataset.py,sha256=WQKkoyZRtgmWbREn-D5i-PyHHgKdVhOWxypdWzpffrk,6210
50
+ timm/data/dataset_factory.py,sha256=DakZNEZlCYeKnizm-hXzGtEUEHxg1XypgRCEXS4jLNc,8180
51
+ timm/data/dataset_info.py,sha256=fAjTkbi-3oEZveKg-n1cxOYM_gcD5kcUeWMWWRRkhOQ,2391
52
+ timm/data/distributed_sampler.py,sha256=mfcS_bzL_zEIREpRer8LAdXw1WvUFYJrXgqKw2fqlHE,5540
53
+ timm/data/imagenet_info.py,sha256=c_DKVQQyzHYftgoUO-12BuqhsBJI_h6Scyg6Gzue-fY,4167
54
+ timm/data/loader.py,sha256=H3QYKjfpK1IoxRZWEPP1eOuzKr2BlZd0qlYXPi8g7io,15511
55
+ timm/data/mixup.py,sha256=-U4kqPGFOZCz_u2rXVXLXvLkdRX1rhIjHmqJfVjzZgs,14634
56
+ timm/data/random_erasing.py,sha256=jSTJq-1zGZT1zRWv5ByyBuA4lQdj_EFcoibdLjRQaDo,4964
57
+ timm/data/readers/__init__.py,sha256=AuKgQjZ5q9XILIZu6iRDIJy-Xydig_zC1TlaVRmRcCY,72
58
+ timm/data/readers/__pycache__/__init__.cpython-310.pyc,,
59
+ timm/data/readers/__pycache__/class_map.cpython-310.pyc,,
60
+ timm/data/readers/__pycache__/img_extensions.cpython-310.pyc,,
61
+ timm/data/readers/__pycache__/reader.cpython-310.pyc,,
62
+ timm/data/readers/__pycache__/reader_factory.cpython-310.pyc,,
63
+ timm/data/readers/__pycache__/reader_hfds.cpython-310.pyc,,
64
+ timm/data/readers/__pycache__/reader_hfids.cpython-310.pyc,,
65
+ timm/data/readers/__pycache__/reader_image_folder.cpython-310.pyc,,
66
+ timm/data/readers/__pycache__/reader_image_in_tar.cpython-310.pyc,,
67
+ timm/data/readers/__pycache__/reader_image_tar.cpython-310.pyc,,
68
+ timm/data/readers/__pycache__/reader_tfds.cpython-310.pyc,,
69
+ timm/data/readers/__pycache__/reader_wds.cpython-310.pyc,,
70
+ timm/data/readers/__pycache__/shared_count.cpython-310.pyc,,
71
+ timm/data/readers/class_map.py,sha256=dMXs4PuEDqJroaOmlBttTpjMlaeXMiB4H4barDKtzvc,895
72
+ timm/data/readers/img_extensions.py,sha256=KTtkCyfrOhLwH7vws7k7xshkEqekdrEGZ-rmErySvcQ,1482
73
+ timm/data/readers/reader.py,sha256=_Fp97wLI1cxFFI1QlOkvWIKwdmtQaPEgH97KmtQDZoI,487
74
+ timm/data/readers/reader_factory.py,sha256=cYqgl-7Ix-xslL83N8Ae6kzAIKlpdd2qkMYciRBO4PA,1732
75
+ timm/data/readers/reader_hfds.py,sha256=qriamfkj7z2csZYeIMm1_uzr_Xeel_h_tlgqP3535DI,2608
76
+ timm/data/readers/reader_hfids.py,sha256=Ok6dchV4HFPvry8gyELnyxgq_nk6EIKJlHwnjZxCBcE,8282
77
+ timm/data/readers/reader_image_folder.py,sha256=_htQ_ouMibCeeemg0097v7nj14qXlFAtpS9HVQwoqNI,3508
78
+ timm/data/readers/reader_image_in_tar.py,sha256=ok4IDPkpuu_3RKxK83EEo7zfLPnqJq_x7CwDmepAf3E,9182
79
+ timm/data/readers/reader_image_tar.py,sha256=h0PlhmHU_1QzUy4p3psI9JoeaAao1_OBFK1_K6Re9e4,2644
80
+ timm/data/readers/reader_tfds.py,sha256=5daaqhJzYq7hbYBAeuF06lXCO7A0tPipHbJVMFMv-Nk,17909
81
+ timm/data/readers/reader_wds.py,sha256=S91U97D9aKpL1INHA4biFkD5NZiUSa2sLTz7onllDxQ,16947
82
+ timm/data/readers/shared_count.py,sha256=___RvLR-johRZ0Ins6iKVAkKU44LxU3o4H7E0B0b25o,303
83
+ timm/data/real_labels.py,sha256=xdexeoU_KE6c2HY0G81Ny2-T_iTQ_1HOWLj7R_WfAls,1800
84
+ timm/data/tf_preprocessing.py,sha256=xClMeZyUPx8YATBvVnzig0bDJNBa8ZqzcpmVWUwefWg,9169
85
+ timm/data/transforms.py,sha256=gGWrF6hkBNbMHD7aBl1Cj8bIT4yQT8pFmHyzOaEKMQ4,18852
86
+ timm/data/transforms_factory.py,sha256=caLsQ77hIqAnsKJOJBDFcbizT5kTBsL2JurgfzJ9eL4,19051
87
+ timm/layers/__init__.py,sha256=9nFiGHJd2vfx-1lgaWn-pOMIEUenXg6Vd-zfqIU8Kms,3842
88
+ timm/layers/__pycache__/__init__.cpython-310.pyc,,
89
+ timm/layers/__pycache__/activations.cpython-310.pyc,,
90
+ timm/layers/__pycache__/activations_me.cpython-310.pyc,,
91
+ timm/layers/__pycache__/adaptive_avgmax_pool.cpython-310.pyc,,
92
+ timm/layers/__pycache__/attention_pool.cpython-310.pyc,,
93
+ timm/layers/__pycache__/attention_pool2d.cpython-310.pyc,,
94
+ timm/layers/__pycache__/blur_pool.cpython-310.pyc,,
95
+ timm/layers/__pycache__/bottleneck_attn.cpython-310.pyc,,
96
+ timm/layers/__pycache__/cbam.cpython-310.pyc,,
97
+ timm/layers/__pycache__/classifier.cpython-310.pyc,,
98
+ timm/layers/__pycache__/cond_conv2d.cpython-310.pyc,,
99
+ timm/layers/__pycache__/config.cpython-310.pyc,,
100
+ timm/layers/__pycache__/conv2d_same.cpython-310.pyc,,
101
+ timm/layers/__pycache__/conv_bn_act.cpython-310.pyc,,
102
+ timm/layers/__pycache__/create_act.cpython-310.pyc,,
103
+ timm/layers/__pycache__/create_attn.cpython-310.pyc,,
104
+ timm/layers/__pycache__/create_conv2d.cpython-310.pyc,,
105
+ timm/layers/__pycache__/create_norm.cpython-310.pyc,,
106
+ timm/layers/__pycache__/create_norm_act.cpython-310.pyc,,
107
+ timm/layers/__pycache__/drop.cpython-310.pyc,,
108
+ timm/layers/__pycache__/eca.cpython-310.pyc,,
109
+ timm/layers/__pycache__/evo_norm.cpython-310.pyc,,
110
+ timm/layers/__pycache__/fast_norm.cpython-310.pyc,,
111
+ timm/layers/__pycache__/filter_response_norm.cpython-310.pyc,,
112
+ timm/layers/__pycache__/format.cpython-310.pyc,,
113
+ timm/layers/__pycache__/gather_excite.cpython-310.pyc,,
114
+ timm/layers/__pycache__/global_context.cpython-310.pyc,,
115
+ timm/layers/__pycache__/grid.cpython-310.pyc,,
116
+ timm/layers/__pycache__/grn.cpython-310.pyc,,
117
+ timm/layers/__pycache__/halo_attn.cpython-310.pyc,,
118
+ timm/layers/__pycache__/helpers.cpython-310.pyc,,
119
+ timm/layers/__pycache__/inplace_abn.cpython-310.pyc,,
120
+ timm/layers/__pycache__/interpolate.cpython-310.pyc,,
121
+ timm/layers/__pycache__/lambda_layer.cpython-310.pyc,,
122
+ timm/layers/__pycache__/linear.cpython-310.pyc,,
123
+ timm/layers/__pycache__/median_pool.cpython-310.pyc,,
124
+ timm/layers/__pycache__/mixed_conv2d.cpython-310.pyc,,
125
+ timm/layers/__pycache__/ml_decoder.cpython-310.pyc,,
126
+ timm/layers/__pycache__/mlp.cpython-310.pyc,,
127
+ timm/layers/__pycache__/non_local_attn.cpython-310.pyc,,
128
+ timm/layers/__pycache__/norm.cpython-310.pyc,,
129
+ timm/layers/__pycache__/norm_act.cpython-310.pyc,,
130
+ timm/layers/__pycache__/padding.cpython-310.pyc,,
131
+ timm/layers/__pycache__/patch_dropout.cpython-310.pyc,,
132
+ timm/layers/__pycache__/patch_embed.cpython-310.pyc,,
133
+ timm/layers/__pycache__/pool2d_same.cpython-310.pyc,,
134
+ timm/layers/__pycache__/pos_embed.cpython-310.pyc,,
135
+ timm/layers/__pycache__/pos_embed_rel.cpython-310.pyc,,
136
+ timm/layers/__pycache__/pos_embed_sincos.cpython-310.pyc,,
137
+ timm/layers/__pycache__/selective_kernel.cpython-310.pyc,,
138
+ timm/layers/__pycache__/separable_conv.cpython-310.pyc,,
139
+ timm/layers/__pycache__/space_to_depth.cpython-310.pyc,,
140
+ timm/layers/__pycache__/split_attn.cpython-310.pyc,,
141
+ timm/layers/__pycache__/split_batchnorm.cpython-310.pyc,,
142
+ timm/layers/__pycache__/squeeze_excite.cpython-310.pyc,,
143
+ timm/layers/__pycache__/std_conv.cpython-310.pyc,,
144
+ timm/layers/__pycache__/test_time_pool.cpython-310.pyc,,
145
+ timm/layers/__pycache__/trace_utils.cpython-310.pyc,,
146
+ timm/layers/__pycache__/typing.cpython-310.pyc,,
147
+ timm/layers/__pycache__/weight_init.cpython-310.pyc,,
148
+ timm/layers/activations.py,sha256=5dnM9Fr63FBHTBwmNk7Ps__fYL4aCJfqUbWhFLAYm0I,4882
149
+ timm/layers/activations_me.py,sha256=cPNk1XdvfOunn3Rd9ohNbRh8LtHw5-DPKYp04FMtBZU,5504
150
+ timm/layers/adaptive_avgmax_pool.py,sha256=58cPkSKechsJHJQvcfW_onZRMLntnDNduMitWjmqSMo,6583
151
+ timm/layers/attention_pool.py,sha256=-XLq9I4j8FPwC0jHh1M9meT3fG17afQBhrDg1rDEwRA,3458
152
+ timm/layers/attention_pool2d.py,sha256=zQ0P6VRo_VsZ1PdmjCEbOybqHilTmVQHiRjfFGlm29c,4934
153
+ timm/layers/blur_pool.py,sha256=MfwXZp6m7OtjTJzXS1Ihxtne2it4hqyI2VHdjWgEU_E,1594
154
+ timm/layers/bottleneck_attn.py,sha256=HLuZbyep1Nf9Qq9Aei81kCzQMs6U1aQBQRLrOnjnkHo,6895
155
+ timm/layers/cbam.py,sha256=b6lo3KFOc88MV4ITw2pSokuvpLkAFpB9lNc1e20QdGI,4426
156
+ timm/layers/classifier.py,sha256=renoMpweK-LUrxeNWjzHwtE-DsXa_XQDtutE5BWDTaI,7522
157
+ timm/layers/cond_conv2d.py,sha256=bUfMYl3PRnfdIULJoXlLjh71UT8ZSsb8lQBa_n-q7Vo,5199
158
+ timm/layers/config.py,sha256=_11jlMV9cDw--w1zSKxHeJINOf60N6IDqns0m2gPGts,4175
159
+ timm/layers/conv2d_same.py,sha256=ssxoaAlxauEavfvR792KBfIImVEATlql7tDssv7xyRY,3216
160
+ timm/layers/conv_bn_act.py,sha256=Jr2pUtKhj8LzuoOVhTO4IaIn08uBqfzLkzMPdiv7JJI,3836
161
+ timm/layers/create_act.py,sha256=yoti9tg10vou0yczhrbQdszaAAvQsJ5QZUf3WwYzmVI,4434
162
+ timm/layers/create_attn.py,sha256=d9-j6iPcFPpC2o7_DW4QLKKP1KWZBhZn6-AHH-iSfh4,3514
163
+ timm/layers/create_conv2d.py,sha256=darxUzkvPYUxguuJ_WJd1PepkxOK4if5JwJzC5IC85k,1622
164
+ timm/layers/create_norm.py,sha256=KGGBpC0Ep7Cmumgl5kUIzkIGyeHbCGXlunNSdgVwz-4,1581
165
+ timm/layers/create_norm_act.py,sha256=i5EIl-X8gr75TFJ0t7OQaExFIFc_OLMpDVHLhCJFfIo,3836
166
+ timm/layers/drop.py,sha256=HocUkCNINxvSRHV0dQR7zpeRiJQG_Kkk8_ww2AHK2Zg,6973
167
+ timm/layers/eca.py,sha256=MiVhboDUqLUfeubpypWfaR3LMLHwgLCNsWO3iemcQFs,6386
168
+ timm/layers/evo_norm.py,sha256=mOJu-pMlBkVGjp3aKN0lhjnuED3lXLETNqbJIHpSSSA,13862
169
+ timm/layers/fast_norm.py,sha256=IIlM2VUs-DSUNs_Iq0KET-5zjP_dTYMj8QTQ_c1WhBo,4008
170
+ timm/layers/filter_response_norm.py,sha256=mDJ3nbu5nicP-5actvDiZa4HYd393Vq-_06ZTca5d4w,2540
171
+ timm/layers/format.py,sha256=i02NLXbWXPv4WJCSUF4MnSjQp699-UGr5Z3rnMZk364,1109
172
+ timm/layers/gather_excite.py,sha256=53DHt6cySjPqd9NW3voZuhw8b9nUzvsG9NVl_D-9NAo,3824
173
+ timm/layers/global_context.py,sha256=aZWvij4J-T5I1rdTK725D6R0fDuJyYPDaXvl36QMmkw,2445
174
+ timm/layers/grid.py,sha256=lMM8bM3ggxunvQFqQCB943SZAfY7Nw04w-lFaMBkxt8,1624
175
+ timm/layers/grn.py,sha256=dxLWn-V48OiFlKLLKaU8Zt0mdBcR_AOg0mh1i8tmHKY,1319
176
+ timm/layers/halo_attn.py,sha256=zMJkf9S-ocCvrfvWOe0I97UHTpEQIkP381DON3OXm-c,10662
177
+ timm/layers/helpers.py,sha256=9VLqID8jjdw_Un270F3rQLvNz9vQMhN9mts7kk_Ma_Y,1053
178
+ timm/layers/inplace_abn.py,sha256=CTJcx3n_Ds6Q-Uds83I87DuQy2jgzX8ummBVKkrlyA0,3374
179
+ timm/layers/interpolate.py,sha256=OsobWqF1CrpLe6YkXLmRzASbAsw_uzztyqsBZ6xUYrs,2439
180
+ timm/layers/lambda_layer.py,sha256=-jB-uYoYqk0QjStAhaec30uyEAWp64N96_Bw33oY8H8,5958
181
+ timm/layers/linear.py,sha256=baS2Wpl0vYELnvhnQ6Lw65jVotaJz5iGbroJJ9JmIRM,743
182
+ timm/layers/median_pool.py,sha256=b02v36VGvs_gCY9NhVwU7-mglcXJHzrJVzcEpEUuHBI,1737
183
+ timm/layers/mixed_conv2d.py,sha256=mRSmAUtpgHya_RdnUq4j85K5QS7JFTdSPUXOUTKgpmA,1843
184
+ timm/layers/ml_decoder.py,sha256=Kk7JBS8TIlVWsFE8o9iFgN70JzIOJNmJqXrWWvCxpb0,6701
185
+ timm/layers/mlp.py,sha256=2vNBR6ML5BbS1wrleEuqmVZ7pRGvPaZZwn2rWPBV-Ls,8457
186
+ timm/layers/non_local_attn.py,sha256=29ZunmS6vrMmkhPNwl7DtPoFYgGlDpuwF17coCEy7HU,6218
187
+ timm/layers/norm.py,sha256=ogSoW2JJq9bbROnf4ybHp5SmAyvyIy_BfMNCEL1cJ-k,6022
188
+ timm/layers/norm_act.py,sha256=buv-jDdjaE-uahC222PmNdw7xe-uYMGyCJcppex-6fQ,17418
189
+ timm/layers/padding.py,sha256=zxIzexHxO8pXnZlDP0SHpxGfE54dvgL7ZcXFske3Cs4,2877
190
+ timm/layers/patch_dropout.py,sha256=3VhnyhMbzOHVAYNwnNA3B_dAWzAdohDaWsT8cz8Foh8,1741
191
+ timm/layers/patch_embed.py,sha256=N2WhCzeelMc7GBol6hKLGqdg0PbxRVDwGymUpb6qx0E,10324
192
+ timm/layers/pool2d_same.py,sha256=UsmtWna5k5kfVTP25T1-OKJOgtcfBQCqSy0FmaZbjRw,3045
193
+ timm/layers/pos_embed.py,sha256=3IGtj3NYTcPNxWHIFkMNQlP9fZ6NFOhnMYWXQDPulm0,2584
194
+ timm/layers/pos_embed_rel.py,sha256=xIkPKYHQBxfXVr3-1xWy6-K8fKM-b9DoNS0WOHkzvfA,19370
195
+ timm/layers/pos_embed_sincos.py,sha256=4lQiwEDsP7pNi4N-6loP954WvE2zCmqgShYRhOC2MBY,14465
196
+ timm/layers/selective_kernel.py,sha256=66jsFM4oa-MkHewe9zHP0n0Y7D9qTB0BE_kH2V9axPQ,5387
197
+ timm/layers/separable_conv.py,sha256=staVZPP-BxtO3q0Ka3_VnI1M1e-xtNAUUACP81rhF_Y,2620
198
+ timm/layers/space_to_depth.py,sha256=BwTu9tEamsmqF-DHdkHgWBv8Paf3_CE8v-IGZiLU1Hc,1068
199
+ timm/layers/split_attn.py,sha256=Cl2gx0lNVosX2zgieLgf_FtqUwuwtGKTyxSoWyvejeg,3076
200
+ timm/layers/split_batchnorm.py,sha256=4ghGtliK5z0ZnzR29zJB_rN9BJPiGuy1PSltmVyF5Ww,3441
201
+ timm/layers/squeeze_excite.py,sha256=YrJELkYE5cB1c-r4Ww9omezUp3dugbgz-qN8XsTbc3I,4327
202
+ timm/layers/std_conv.py,sha256=zYhcKCbE0_Rqn422gEM9gr3LeBewu0CXKqvlsa9-M2Q,5887
203
+ timm/layers/test_time_pool.py,sha256=Z5lPvVLI4IYqrJLGQhgJfxPasug9nts1y6mDD_rznBQ,1996
204
+ timm/layers/trace_utils.py,sha256=cbZufOaGKmhTGEMc52QAnqzGRTfn4vvzqsAOJaLKJQ8,335
205
+ timm/layers/typing.py,sha256=UYrThz9-g8PlmXr7LZutKft6seFaFVp_ZrD0ZGV2aP4,163
206
+ timm/layers/weight_init.py,sha256=ilx0Yq5TxGcb9HTkyW0jo-JoHe7QNjCyBQ3bgaSlKns,4765
207
+ timm/loss/__init__.py,sha256=iCNB9bUAf69neNe1_XO0eeg1QXuxu6jRTAuy4V9yFL8,245
208
+ timm/loss/__pycache__/__init__.cpython-310.pyc,,
209
+ timm/loss/__pycache__/asymmetric_loss.cpython-310.pyc,,
210
+ timm/loss/__pycache__/binary_cross_entropy.cpython-310.pyc,,
211
+ timm/loss/__pycache__/cross_entropy.cpython-310.pyc,,
212
+ timm/loss/__pycache__/jsd.cpython-310.pyc,,
213
+ timm/loss/asymmetric_loss.py,sha256=3BajT94OJslw-MSrqQLRB67SLT2pbhb2vqj0CtOKN6w,3240
214
+ timm/loss/binary_cross_entropy.py,sha256=9AgASCvD-URGZS1E6XyaaYBxf0UOx8AHHKC7tTLTQzU,2483
215
+ timm/loss/cross_entropy.py,sha256=XDE19FnhYjeudAerb6UulIID34AmZoXQ1CPEAjEkCQM,1145
216
+ timm/loss/jsd.py,sha256=MFe8H_JC1srFE_FKinF7jMVIQYgNWgeT7kZL9WeIXGI,1595
217
+ timm/models/__init__.py,sha256=-BWHsuaka_CozrO3jNN8IYm7eRnjKzUUF810ozHgAk0,3333
218
+ timm/models/__pycache__/__init__.cpython-310.pyc,,
219
+ timm/models/__pycache__/_builder.cpython-310.pyc,,
220
+ timm/models/__pycache__/_efficientnet_blocks.cpython-310.pyc,,
221
+ timm/models/__pycache__/_efficientnet_builder.cpython-310.pyc,,
222
+ timm/models/__pycache__/_factory.cpython-310.pyc,,
223
+ timm/models/__pycache__/_features.cpython-310.pyc,,
224
+ timm/models/__pycache__/_features_fx.cpython-310.pyc,,
225
+ timm/models/__pycache__/_helpers.cpython-310.pyc,,
226
+ timm/models/__pycache__/_hub.cpython-310.pyc,,
227
+ timm/models/__pycache__/_manipulate.cpython-310.pyc,,
228
+ timm/models/__pycache__/_pretrained.cpython-310.pyc,,
229
+ timm/models/__pycache__/_prune.cpython-310.pyc,,
230
+ timm/models/__pycache__/_registry.cpython-310.pyc,,
231
+ timm/models/__pycache__/beit.cpython-310.pyc,,
232
+ timm/models/__pycache__/byoanet.cpython-310.pyc,,
233
+ timm/models/__pycache__/byobnet.cpython-310.pyc,,
234
+ timm/models/__pycache__/cait.cpython-310.pyc,,
235
+ timm/models/__pycache__/coat.cpython-310.pyc,,
236
+ timm/models/__pycache__/convit.cpython-310.pyc,,
237
+ timm/models/__pycache__/convmixer.cpython-310.pyc,,
238
+ timm/models/__pycache__/convnext.cpython-310.pyc,,
239
+ timm/models/__pycache__/crossvit.cpython-310.pyc,,
240
+ timm/models/__pycache__/cspnet.cpython-310.pyc,,
241
+ timm/models/__pycache__/davit.cpython-310.pyc,,
242
+ timm/models/__pycache__/deit.cpython-310.pyc,,
243
+ timm/models/__pycache__/densenet.cpython-310.pyc,,
244
+ timm/models/__pycache__/dla.cpython-310.pyc,,
245
+ timm/models/__pycache__/dpn.cpython-310.pyc,,
246
+ timm/models/__pycache__/edgenext.cpython-310.pyc,,
247
+ timm/models/__pycache__/efficientformer.cpython-310.pyc,,
248
+ timm/models/__pycache__/efficientformer_v2.cpython-310.pyc,,
249
+ timm/models/__pycache__/efficientnet.cpython-310.pyc,,
250
+ timm/models/__pycache__/efficientvit_mit.cpython-310.pyc,,
251
+ timm/models/__pycache__/efficientvit_msra.cpython-310.pyc,,
252
+ timm/models/__pycache__/eva.cpython-310.pyc,,
253
+ timm/models/__pycache__/factory.cpython-310.pyc,,
254
+ timm/models/__pycache__/fastvit.cpython-310.pyc,,
255
+ timm/models/__pycache__/features.cpython-310.pyc,,
256
+ timm/models/__pycache__/focalnet.cpython-310.pyc,,
257
+ timm/models/__pycache__/fx_features.cpython-310.pyc,,
258
+ timm/models/__pycache__/gcvit.cpython-310.pyc,,
259
+ timm/models/__pycache__/ghostnet.cpython-310.pyc,,
260
+ timm/models/__pycache__/hardcorenas.cpython-310.pyc,,
261
+ timm/models/__pycache__/helpers.cpython-310.pyc,,
262
+ timm/models/__pycache__/hgnet.cpython-310.pyc,,
263
+ timm/models/__pycache__/hiera.cpython-310.pyc,,
264
+ timm/models/__pycache__/hrnet.cpython-310.pyc,,
265
+ timm/models/__pycache__/hub.cpython-310.pyc,,
266
+ timm/models/__pycache__/inception_next.cpython-310.pyc,,
267
+ timm/models/__pycache__/inception_resnet_v2.cpython-310.pyc,,
268
+ timm/models/__pycache__/inception_v3.cpython-310.pyc,,
269
+ timm/models/__pycache__/inception_v4.cpython-310.pyc,,
270
+ timm/models/__pycache__/levit.cpython-310.pyc,,
271
+ timm/models/__pycache__/maxxvit.cpython-310.pyc,,
272
+ timm/models/__pycache__/metaformer.cpython-310.pyc,,
273
+ timm/models/__pycache__/mlp_mixer.cpython-310.pyc,,
274
+ timm/models/__pycache__/mobilenetv3.cpython-310.pyc,,
275
+ timm/models/__pycache__/mobilevit.cpython-310.pyc,,
276
+ timm/models/__pycache__/mvitv2.cpython-310.pyc,,
277
+ timm/models/__pycache__/nasnet.cpython-310.pyc,,
278
+ timm/models/__pycache__/nest.cpython-310.pyc,,
279
+ timm/models/__pycache__/nextvit.cpython-310.pyc,,
280
+ timm/models/__pycache__/nfnet.cpython-310.pyc,,
281
+ timm/models/__pycache__/pit.cpython-310.pyc,,
282
+ timm/models/__pycache__/pnasnet.cpython-310.pyc,,
283
+ timm/models/__pycache__/pvt_v2.cpython-310.pyc,,
284
+ timm/models/__pycache__/registry.cpython-310.pyc,,
285
+ timm/models/__pycache__/regnet.cpython-310.pyc,,
286
+ timm/models/__pycache__/repghost.cpython-310.pyc,,
287
+ timm/models/__pycache__/repvit.cpython-310.pyc,,
288
+ timm/models/__pycache__/res2net.cpython-310.pyc,,
289
+ timm/models/__pycache__/resnest.cpython-310.pyc,,
290
+ timm/models/__pycache__/resnet.cpython-310.pyc,,
291
+ timm/models/__pycache__/resnetv2.cpython-310.pyc,,
292
+ timm/models/__pycache__/rexnet.cpython-310.pyc,,
293
+ timm/models/__pycache__/selecsls.cpython-310.pyc,,
294
+ timm/models/__pycache__/senet.cpython-310.pyc,,
295
+ timm/models/__pycache__/sequencer.cpython-310.pyc,,
296
+ timm/models/__pycache__/sknet.cpython-310.pyc,,
297
+ timm/models/__pycache__/swin_transformer.cpython-310.pyc,,
298
+ timm/models/__pycache__/swin_transformer_v2.cpython-310.pyc,,
299
+ timm/models/__pycache__/swin_transformer_v2_cr.cpython-310.pyc,,
300
+ timm/models/__pycache__/tiny_vit.cpython-310.pyc,,
301
+ timm/models/__pycache__/tnt.cpython-310.pyc,,
302
+ timm/models/__pycache__/tresnet.cpython-310.pyc,,
303
+ timm/models/__pycache__/twins.cpython-310.pyc,,
304
+ timm/models/__pycache__/vgg.cpython-310.pyc,,
305
+ timm/models/__pycache__/visformer.cpython-310.pyc,,
306
+ timm/models/__pycache__/vision_transformer.cpython-310.pyc,,
307
+ timm/models/__pycache__/vision_transformer_hybrid.cpython-310.pyc,,
308
+ timm/models/__pycache__/vision_transformer_relpos.cpython-310.pyc,,
309
+ timm/models/__pycache__/vision_transformer_sam.cpython-310.pyc,,
310
+ timm/models/__pycache__/volo.cpython-310.pyc,,
311
+ timm/models/__pycache__/vovnet.cpython-310.pyc,,
312
+ timm/models/__pycache__/xception.cpython-310.pyc,,
313
+ timm/models/__pycache__/xception_aligned.cpython-310.pyc,,
314
+ timm/models/__pycache__/xcit.cpython-310.pyc,,
315
+ timm/models/_builder.py,sha256=tZ6iMqVzvmnJQq1AN09iU3AqursbJTMUObiJDXg2Dm0,19879
316
+ timm/models/_efficientnet_blocks.py,sha256=tT2ZiPj-8LP8yvN6YI8fwTGpzujT6gAtOoXY-hJ-AkU,12092
317
+ timm/models/_efficientnet_builder.py,sha256=k2dWyCGlnqyiFzD26kcoo4OWYG0G9dCWYAsEC5Rz0z8,20021
318
+ timm/models/_factory.py,sha256=1yiXCX6ATfvp_Bxs8ThAHktbmaAW5ErifrWJIoOLxa4,5188
319
+ timm/models/_features.py,sha256=5K2GY84NAj23-ePIBM_jWl0AkwQX3IJp6oGlN7nNG3U,19720
320
+ timm/models/_features_fx.py,sha256=Euclise3a1HjpBUYA-j2RAzSgpMO63fNDomRPOAnkfY,5687
321
+ timm/models/_helpers.py,sha256=Br3j6X6rjnHeB7Y2DayQwcdsf-t_ww7xPPVSPNWnijg,5948
322
+ timm/models/_hub.py,sha256=APCLL3mSSlHCreuazIxCy-WWnPbUmOh1ARyzKhkQOzg,16141
323
+ timm/models/_manipulate.py,sha256=PCrCJD-UPPageLuhHfDzIgEgax7pw96bEsr6d6x1_DE,10503
324
+ timm/models/_pretrained.py,sha256=uS95ANJTn4eYOkKdLzuZUDz31BTn0oHMFkY-qs2rCjE,3525
325
+ timm/models/_prune.py,sha256=yAQik6hOhZoIoc4-geVrANB30oQF36fMQsneUA0qgHk,4171
326
+ timm/models/_pruned/ecaresnet101d_pruned.txt,sha256=1zA7XaxsTnFJxZ9PMbfMVST7wPSQcAV-UzSgdFfGgYY,8734
327
+ timm/models/_pruned/ecaresnet50d_pruned.txt,sha256=J4AlTwabaSB6-XrINCPCDWMiM_FrdNjuJN_JJRb89WE,4520
328
+ timm/models/_pruned/efficientnet_b1_pruned.txt,sha256=pNDm1EENJYMT8-GjXZ3kXWCXADLDun-4jfigh74RELE,18596
329
+ timm/models/_pruned/efficientnet_b2_pruned.txt,sha256=e_oaSVM-Ux3NMVARynJ74YwjzxuBAX_w7kzOw9Ml3gM,18676
330
+ timm/models/_pruned/efficientnet_b3_pruned.txt,sha256=A1DJEwjEmrg8oUr0QwzwBkdAJV3dVeUFjnO9pNC_0Pg,21133
331
+ timm/models/_registry.py,sha256=majymk_1iZfsWtEpj2OpkUyhkpp-Hfra3ZWMfpj3rjM,14117
332
+ timm/models/beit.py,sha256=hMGwR77DGDho7u3KHULopVJhiAN_NRZLpI-U6Pn_knk,29295
333
+ timm/models/byoanet.py,sha256=fgvAAkxAHBto0zlUYX4KrH4Wa_T4POpxhWkGa9j4vOs,18985
334
+ timm/models/byobnet.py,sha256=eTs-w7maCoYCQphgysQwaEqFmbOSdkFd-UasbbLu0Kg,89753
335
+ timm/models/cait.py,sha256=EnUedx5DLdkyF_FhNOVPl79oGw-HaLsyI1d-euJi4Xc,21376
336
+ timm/models/coat.py,sha256=adLiGbMj7thWNhYHF9d1RyW3W86NgHCH9aao8nGQkSU,30017
337
+ timm/models/convit.py,sha256=-sBh7m3Aukgr7-Ckb7BTx4kmSLDKDJCk5YZiSkdn-TU,15320
338
+ timm/models/convmixer.py,sha256=LAo8pAo_qvAKLRlmUCEj20gSgdl2rTFswpIVD0qASlM,4649
339
+ timm/models/convnext.py,sha256=Ajf3jb7v8YrWgUI_uTVcKC-fl0Csx_X4RudyAD7U8_o,52338
340
+ timm/models/crossvit.py,sha256=6MBfjqXMRaSot9mvMI9eL1qzQIxsO6UNxxapHiFz5Ck,24285
341
+ timm/models/cspnet.py,sha256=1vZF0VKn5TQU6VpHtJssVQG6clVbuphVae_l-ak6Ki0,40060
342
+ timm/models/davit.py,sha256=7q2bujVAnHKaQGo-bR9CZuQkKoQ9ZyHDg67iDAM_ssw,23281
343
+ timm/models/deit.py,sha256=nqlE01oWkfRx3I55WdciCCGK6pD9FcwVqjLPzIUgZrk,18512
344
+ timm/models/densenet.py,sha256=z9dccK6vudlYJjiE14M9vBIv1Vw5a64AOW5nBvCDhuI,15942
345
+ timm/models/dla.py,sha256=nGhyOO9K6PUIDjpEHoYiIiJVBCxfalNMKE3hSufAh8M,18599
346
+ timm/models/dpn.py,sha256=aJLl3vRDWsFl2WjOPGAFuzWHNP449Jz0WRJiB8P2nY4,13593
347
+ timm/models/edgenext.py,sha256=MGP81f1cj_nLoBDpJUca1AgqD9zxZVLvwFDIAadXsLQ,20900
348
+ timm/models/efficientformer.py,sha256=LMKEeM8kkNu1c_wlDNcEoYNsdkyquO3yhrA2UZkipio,21956
349
+ timm/models/efficientformer_v2.py,sha256=w0b3dPwxxdmsZEruA5NWQoC1zPA4HWcdwWs3y2u9hDg,24873
350
+ timm/models/efficientnet.py,sha256=d8EueppJAYlIXw4YLXCjEjTgQRfwGVuJskyyL4NFiMk,105265
351
+ timm/models/efficientvit_mit.py,sha256=X0tUsAOo0ASQEoPpkbEC6yy_403_OX7l67_4bynPs6g,34173
352
+ timm/models/efficientvit_msra.py,sha256=34psRQWYZeeUMOhJMtUyttPt6YhwlYT2XDxxJIOXIxk,23437
353
+ timm/models/eva.py,sha256=DhV6-xzMnULoy3k4Jat1uqFd7LLCxLV4qiGQT2Aihno,48500
354
+ timm/models/factory.py,sha256=hYPRaA-qi3dkX92PHf8QOA10O3_5cB6Oqeb_9cgsnw0,150
355
+ timm/models/fastvit.py,sha256=1PwPxIo3DxpcpF1-g8Fl5AXDdKFpyfme66Gypr0VQaM,48418
356
+ timm/models/features.py,sha256=TL6qXfNk3mho84rRpnx8UW06pEZgAdNXpDubmRXLR5w,151
357
+ timm/models/focalnet.py,sha256=_DLXXV94pK_i2Uy5vf5AHQfviOh9ps-cnDUj60bm7cg,24087
358
+ timm/models/fx_features.py,sha256=MFUZmcdisM3HrNjak93L3SwWvntYejnzVrJXXbBLAOE,154
359
+ timm/models/gcvit.py,sha256=Ex3Z3kKLxqTaKP8Px1FkNH8v-TzaO3gBo73Wxxe2SdE,21447
360
+ timm/models/ghostnet.py,sha256=av1Ieu9oMAn3H4oP_4Bww4ca6tuliGYIc92TcDWZ200,14559
361
+ timm/models/hardcorenas.py,sha256=MdMhROScNZ92ysLQZP6AxRz1ND0o3hn920FLLbGFtt8,7697
362
+ timm/models/helpers.py,sha256=vZzhyBMrJQoxbu1VxSSq7PjsYz0VzQkN1UuT-luSY7s,223
363
+ timm/models/hgnet.py,sha256=wI1y7qeJ6KGbCXr0lnooeexNlPQI1n37X-Gi90y70SM,23366
364
+ timm/models/hiera.py,sha256=nxlX3RhKAFHt289GpPJy713pK9tXw3eb5Ev5r5jQL0I,33596
365
+ timm/models/hrnet.py,sha256=Ii66t41r-gI8bvlUmo_vqZhb2YRKVqnftc0L4NtGmuQ,33271
366
+ timm/models/hub.py,sha256=7hDmaDdMFjiNS0KJeln_HhZHLBSAN4tx0WzyekJ6P8Q,146
367
+ timm/models/inception_next.py,sha256=32B0hC2uivNlTyqMxIN37zTqzbr19aDD9B9cjJDwiWo,15052
368
+ timm/models/inception_resnet_v2.py,sha256=5MR1fwdIMU9Qb4iNAXsE8AETVH0CTGg2QE2MmuGYCVQ,12077
369
+ timm/models/inception_v3.py,sha256=53jhr4BqBzg85igDt9toPCyOvQD5wNV1vlUt0RVpN5M,17104
370
+ timm/models/inception_v4.py,sha256=Jpz6Dq9AlnpD4VacCotJXVHQEa87D3Y8oIu39d8MZX0,11076
371
+ timm/models/layers/__init__.py,sha256=2y9E02WxVfb08utd-vqtOBEtBdO9dWFQPseI0bu9qng,3374
372
+ timm/models/layers/__pycache__/__init__.cpython-310.pyc,,
373
+ timm/models/levit.py,sha256=RXjQeIsRbsvZH7xWLr7nBicntH9NkHSvRJwDsbe3gyw,34910
374
+ timm/models/maxxvit.py,sha256=g3Zd2zl0M8CsWU3lmihjM26ckljg7-M-QUqGfqxiBJ4,87847
375
+ timm/models/metaformer.py,sha256=QH0aFrx6d4oiwsRbSqO6JHen_K9PCBD2EENR-HrzTqs,35053
376
+ timm/models/mlp_mixer.py,sha256=vm8Jn1NwbdeNMEMRvSsWO5qqKntlNANqt1BAwSm6P8s,27269
377
+ timm/models/mobilenetv3.py,sha256=Mxv4wvKtC9fQT14L7XFy_sOH4UsoJ7jAhScCg1EspAk,35969
378
+ timm/models/mobilevit.py,sha256=ZHbGPG3vFhFCI0f3zLWzH2Jqiasr_Sacah_1MBi9KI8,25734
379
+ timm/models/mvitv2.py,sha256=dpuLMreeI9quk2o-8-VJfgQjKmffTx4j7PPvEBzlJmU,39149
380
+ timm/models/nasnet.py,sha256=se0a_eTW4AbSkXbF0UUdiMzNNq6wKip_u_PMAmLx0Eo,26627
381
+ timm/models/nest.py,sha256=nGn1IsvdCSJEk4hqSK6cCh6tY-n7SA8cGNy8FLuJzoI,21505
382
+ timm/models/nextvit.py,sha256=oCIHrTETfvw2SUHLcxqYl88y_0TVbOisn7HYPebBWcs,22760
383
+ timm/models/nfnet.py,sha256=xPb74bcnze6B5Rb0VSHNAp4ubRyLumafOKi1SAqs__A,41085
384
+ timm/models/pit.py,sha256=vYTtgPO3QbvXX59wtHItAxUrTBmlGhrKHeyeRyUkXig,14967
385
+ timm/models/pnasnet.py,sha256=c6TP54kSQApKHvgV2ov2ic390XjknU28K0Gpb5jwFPs,15389
386
+ timm/models/pvt_v2.py,sha256=mmgTKH1gE6n8gNCEzAcZHlbM_djdY5r69a5YPTwtjyE,17311
387
+ timm/models/registry.py,sha256=RCglax-pGfPS1wHOdoNWmOkHohYJ6IvGWbdxuAN6hKk,151
388
+ timm/models/regnet.py,sha256=7wEzMMvEiDMqPyKNSWchBe4mo9LsJH0PihDDrKiek0k,46496
389
+ timm/models/repghost.py,sha256=bRKpHPZUfzF61sJV4NDEtJ0ZWI0LbT2dndzAg2bC_0U,16340
390
+ timm/models/repvit.py,sha256=gmbeX0WUcS2a8HwbjGHAECC_ncIJvG3DkGqvymyPK0k,16436
391
+ timm/models/res2net.py,sha256=PZeI435TG16x-_Zynvqdwfcvwy4b_1_9ydfu_vyBzOA,7691
392
+ timm/models/resnest.py,sha256=65DB4DAErNleuJ6VTVb9HfSM7QFWsxmTs-HT-e6uEIk,9635
393
+ timm/models/resnet.py,sha256=z6toMcp7Q5T4T2YFchjy8DeL0ruwu8zi0IY1j7jzGUU,98006
394
+ timm/models/resnetv2.py,sha256=uVDC7FVjXvA49ekqF56wMoBoqaoG4uvBtpMy8U0u8lM,30481
395
+ timm/models/rexnet.py,sha256=YSAam3XXFAmefl_HTpLZ6Vujdo-hJW1XALU32oXY-IM,11918
396
+ timm/models/selecsls.py,sha256=vxixyOhZXtzm0kA4pN4DBamCAOXZODB4bpsIZlnU-UM,13254
397
+ timm/models/senet.py,sha256=DdBLDeAZoabhFAfMQqMMIFFnG2fDg3V5V3FDpXjGEkE,18165
398
+ timm/models/sequencer.py,sha256=S9P75pwTvfxD9KrYs0IROS0rlNzqal2C63F23aFQsHE,17286
399
+ timm/models/sknet.py,sha256=3FbRZv0QsBGQajF7lIs00vt_M8FZkk7PBsBZuRY3pNA,8777
400
+ timm/models/swin_transformer.py,sha256=Em3Qm4TcLorgZ9TpwINJdI4RbJm052m95zy-jaL86rk,37091
401
+ timm/models/swin_transformer_v2.py,sha256=jgxoRaA11Mcb2h9wpvcxGPkMF1T4LtfqMaSUxfe5AlE,37364
402
+ timm/models/swin_transformer_v2_cr.py,sha256=MG3uMGmUn3pu0j7AbtfLs43m37kb8ahQ_edq0oXur2Q,43936
403
+ timm/models/tiny_vit.py,sha256=Tw4MupfAIntI4x4F08U8EoQfDwgvP0373nnjwZGhaXE,23796
404
+ timm/models/tnt.py,sha256=Y5E2gGub0csu73xRT0B3FD90XVuGp8xCj6GMThWLEQM,13412
405
+ timm/models/tresnet.py,sha256=4rdlVUuIZP9pyidG_AVOMnjGELMFuwJT73nMQzb7v4k,12951
406
+ timm/models/twins.py,sha256=tVkIV3syRbVXP0daZT8INKkMuJAyymm-AbDit9qgu4w,21959
407
+ timm/models/vgg.py,sha256=HccxLb2BDhfao-x4pTiPhkzlHJ1X6IqtQnxkhRDpa7A,11004
408
+ timm/models/visformer.py,sha256=tHhXqs6O5_8upLRQTg8XlC64jnAelYT1Xe1pVq0XHqA,18982
409
+ timm/models/vision_transformer.py,sha256=uA06g6DsyMBir7omwvoYFINy5kdfk-2beeFIPOPuFvE,138934
410
+ timm/models/vision_transformer_hybrid.py,sha256=Uo2Yn8gzMWgrPFYsm0LDI11Q1Hzyn_Vvg7gFHwsWW4k,18543
411
+ timm/models/vision_transformer_relpos.py,sha256=zkY2GvKp4kkJvPaDLf-pAPhLLS76Xz72U07csK__H80,28504
412
+ timm/models/vision_transformer_sam.py,sha256=oprRMu1lva3VMDeeNG_lQah0rXOZ1WEA76EiHWS56rQ,28249
413
+ timm/models/volo.py,sha256=AWF9kYlN_AxAK-EwJSdjV_RF0bEJmYcFJMy0jK8O0RM,34218
414
+ timm/models/vovnet.py,sha256=1ltC1GmyQVcxO3x_YsjTopE9PM4_5TCHwlM6SWW3j_Y,15509
415
+ timm/models/xception.py,sha256=z_mkJLBd1RmdeVwCnNhe0CZU4pQm-KFyNw7y3cROMks,8098
416
+ timm/models/xception_aligned.py,sha256=wULrWfyB3mz6-5cKsBXKox9s18uOmE_fxqqhT4q8noA,15330
417
+ timm/models/xcit.py,sha256=as4kdfjlwdIo4dZnOvFCJXWnYLoMxmSQQqFUNNUm7Y0,41577
418
+ timm/optim/__init__.py,sha256=PGUpQyjACNNOgKA_ciGsi3AZxlw7ScD0XAK2u4eIujM,530
419
+ timm/optim/__pycache__/__init__.cpython-310.pyc,,
420
+ timm/optim/__pycache__/adabelief.cpython-310.pyc,,
421
+ timm/optim/__pycache__/adafactor.cpython-310.pyc,,
422
+ timm/optim/__pycache__/adahessian.cpython-310.pyc,,
423
+ timm/optim/__pycache__/adamp.cpython-310.pyc,,
424
+ timm/optim/__pycache__/adamw.cpython-310.pyc,,
425
+ timm/optim/__pycache__/adan.cpython-310.pyc,,
426
+ timm/optim/__pycache__/lamb.cpython-310.pyc,,
427
+ timm/optim/__pycache__/lars.cpython-310.pyc,,
428
+ timm/optim/__pycache__/lion.cpython-310.pyc,,
429
+ timm/optim/__pycache__/lookahead.cpython-310.pyc,,
430
+ timm/optim/__pycache__/madgrad.cpython-310.pyc,,
431
+ timm/optim/__pycache__/nadam.cpython-310.pyc,,
432
+ timm/optim/__pycache__/nadamw.cpython-310.pyc,,
433
+ timm/optim/__pycache__/nvnovograd.cpython-310.pyc,,
434
+ timm/optim/__pycache__/optim_factory.cpython-310.pyc,,
435
+ timm/optim/__pycache__/radam.cpython-310.pyc,,
436
+ timm/optim/__pycache__/rmsprop_tf.cpython-310.pyc,,
437
+ timm/optim/__pycache__/sgdp.cpython-310.pyc,,
438
+ timm/optim/__pycache__/sgdw.cpython-310.pyc,,
439
+ timm/optim/adabelief.py,sha256=n8nVbFX0TrCgkI98s7sV9D1l_rwPoqgVdfUW1KxGMPY,9827
440
+ timm/optim/adafactor.py,sha256=UOYdbisCGOXJJF4sklBa4XEb3m68IyV6IkzcEopGack,7459
441
+ timm/optim/adahessian.py,sha256=vJtQ8bZTGLrkMYuGPOJdgO-5V8hjVvM2Il-HSqg59Ao,6535
442
+ timm/optim/adamp.py,sha256=PSJYfobQvxy9K0tdU6-mjaiF4BqhIXY9sHV2vposx5I,3574
443
+ timm/optim/adamw.py,sha256=OKSBGfaWs6DJC1aXJHadAp4FADAnDDwb-ZRKuPao7zk,5147
444
+ timm/optim/adan.py,sha256=szYfq09xWZHHeHcpwLjU-T3nla96mUYA2olJqkI2JkI,5071
445
+ timm/optim/lamb.py,sha256=II9zTpcxWzNqgk4K-bs5VGKlQPabUolSAmHkcSjsqSU,9184
446
+ timm/optim/lars.py,sha256=Pc7laTbk6iDt4iRtL-ZZXtB0dGGCuho6AeBSvxvIYmY,5256
447
+ timm/optim/lion.py,sha256=BhQnG7pL_C_Y1QEWjhiJhUAnWGfXi0CLuyQs3ECkqnA,7099
448
+ timm/optim/lookahead.py,sha256=-fM1DEwFf_bpbNq2cXdkJyrobF4iaVNIBuman_RfRk8,2687
449
+ timm/optim/madgrad.py,sha256=V3LJuPjGwiO7RdHAZFF0Qqa8JT8a9DJJLSEO2PCG7Ho,6893
450
+ timm/optim/nadam.py,sha256=pLV8_hQ5jYGlY3eJNzPvGnFIEVNGkpi8wLgYS6RePHE,3929
451
+ timm/optim/nadamw.py,sha256=ncAgp3F14PkCkZTb0xqMiV9PKg8c3tZe-10WZoAexas,12369
452
+ timm/optim/nvnovograd.py,sha256=NkRLq007qqiRDrhqiZK1KP_kfCcFcDSYCWRcoYvddOQ,4856
453
+ timm/optim/optim_factory.py,sha256=ULeNdcKHnz2SnID_pEw-_iAsgCQi9YBSWb0FROPhDO8,15868
454
+ timm/optim/radam.py,sha256=dCeFJGKo5WC8w7Ad8tuldM6QFz41nYXJIYI5HkH6uxk,3468
455
+ timm/optim/rmsprop_tf.py,sha256=SX47YRaLPNB-YpJpLUbXqx21ZFoDPeqvpJX2kin4wCc,6143
456
+ timm/optim/sgdp.py,sha256=7f4ZMVHbjCTDTgPOZfE06S4lmdUBnIBCDr_Yzy1RFhY,2296
457
+ timm/optim/sgdw.py,sha256=wiCGhF4oOj-dJJ9hD1BBCB-4U_3ZdCiDdqJhlEBKvso,9046
458
+ timm/scheduler/__init__.py,sha256=O3yNRcgje9l_wUhxN5VteAARRGMpCxOmhbOmV_8j2Dw,330
459
+ timm/scheduler/__pycache__/__init__.cpython-310.pyc,,
460
+ timm/scheduler/__pycache__/cosine_lr.cpython-310.pyc,,
461
+ timm/scheduler/__pycache__/multistep_lr.cpython-310.pyc,,
462
+ timm/scheduler/__pycache__/plateau_lr.cpython-310.pyc,,
463
+ timm/scheduler/__pycache__/poly_lr.cpython-310.pyc,,
464
+ timm/scheduler/__pycache__/scheduler.cpython-310.pyc,,
465
+ timm/scheduler/__pycache__/scheduler_factory.cpython-310.pyc,,
466
+ timm/scheduler/__pycache__/step_lr.cpython-310.pyc,,
467
+ timm/scheduler/__pycache__/tanh_lr.cpython-310.pyc,,
468
+ timm/scheduler/cosine_lr.py,sha256=E6wwe8NjWQAfOzzas6llX3_9dPXoYmxV1p5ZlLbMVVE,3887
469
+ timm/scheduler/multistep_lr.py,sha256=m33HB6ToJQCOAfF7n0Ofab7tpzwlg6eB5EOIb_6v_Qc,1950
470
+ timm/scheduler/plateau_lr.py,sha256=6SmHEBIfgzE83GMHK_ZMIz-L0478HJ3ahwRgDZ9CJbk,3603
471
+ timm/scheduler/poly_lr.py,sha256=q5uedgbuQilvU3AICrRvBo_MMPpMGGle0KgheJpXQ0A,3717
472
+ timm/scheduler/scheduler.py,sha256=Dy3Os_z2qI9AA0InPN0oroOdETW7weYb1Uk7C0ZXurk,5426
473
+ timm/scheduler/scheduler_factory.py,sha256=Yz02A5PartDsUdxrBqzgmiKTbd46V9-Krz3Lgq3UwXM,6787
474
+ timm/scheduler/step_lr.py,sha256=rHliA2nLVUQsOInjUnQgeGtH09aupY4uOXmQ-_ouNXc,1777
475
+ timm/scheduler/tanh_lr.py,sha256=bhprzeUZZNJqqRT0PMY9cE7MbBg1R-pq52H-qEHeY7U,3651
476
+ timm/utils/__init__.py,sha256=r-mgE7sAOYatFEYjgdXXKH0RjOLvQ5FH0rcxv8-gNR0,846
477
+ timm/utils/__pycache__/__init__.cpython-310.pyc,,
478
+ timm/utils/__pycache__/agc.cpython-310.pyc,,
479
+ timm/utils/__pycache__/attention_extract.cpython-310.pyc,,
480
+ timm/utils/__pycache__/checkpoint_saver.cpython-310.pyc,,
481
+ timm/utils/__pycache__/clip_grad.cpython-310.pyc,,
482
+ timm/utils/__pycache__/cuda.cpython-310.pyc,,
483
+ timm/utils/__pycache__/decay_batch.cpython-310.pyc,,
484
+ timm/utils/__pycache__/distributed.cpython-310.pyc,,
485
+ timm/utils/__pycache__/jit.cpython-310.pyc,,
486
+ timm/utils/__pycache__/log.cpython-310.pyc,,
487
+ timm/utils/__pycache__/metrics.cpython-310.pyc,,
488
+ timm/utils/__pycache__/misc.cpython-310.pyc,,
489
+ timm/utils/__pycache__/model.cpython-310.pyc,,
490
+ timm/utils/__pycache__/model_ema.cpython-310.pyc,,
491
+ timm/utils/__pycache__/onnx.cpython-310.pyc,,
492
+ timm/utils/__pycache__/random.cpython-310.pyc,,
493
+ timm/utils/__pycache__/summary.cpython-310.pyc,,
494
+ timm/utils/agc.py,sha256=6lZCChfbW0KGNMfkzztWD_NP87ESopjk24Xtb3WbBqU,1624
495
+ timm/utils/attention_extract.py,sha256=DWCKQ14BeZAEnGPh4u54EqJjSAaSxzd3pztfCm0uJxc,2823
496
+ timm/utils/checkpoint_saver.py,sha256=RljigPicMAHnk48K2Qbl17cWnQepgO4QMZQ0FCjd8xw,6133
497
+ timm/utils/clip_grad.py,sha256=iYFEf7fvPbpyh5K1SI-EKey5Gqs2gztR9VUUGja0GB0,796
498
+ timm/utils/cuda.py,sha256=lmDfKZFUqMlkJlpMbba5tDlslSksUd6B2ouYlkd2Uz4,2029
499
+ timm/utils/decay_batch.py,sha256=5fOrMO985Pw8uzvBK78RwYCoH3Nv2jb46OGa9GkJ6LA,1762
500
+ timm/utils/distributed.py,sha256=hSp_k_OgcRBH975srSdC2tj7BHGsPqYdmlYrH9b0how,5762
501
+ timm/utils/jit.py,sha256=ow8sPjtnlzcRDGR_xNL7E6BU0cdjjgUSEkhGXuvMNkw,2203
502
+ timm/utils/log.py,sha256=BdZ2OqWo3v8d7wsDRJ-uACcoeNUhS8TJSwI3CYvq3Ss,1015
503
+ timm/utils/metrics.py,sha256=RSHpbbkyW6FsbxT6TzcBL7MZh4sv4A_GG1Bo8aN5qKc,901
504
+ timm/utils/misc.py,sha256=wh1RUZPEyVOtA3HFkbunNpAKPbrOKQYeJqhvODmSyyQ,1105
505
+ timm/utils/model.py,sha256=KXDSUnFGyN7UJjNCJawEQSS02aufUdTN_UAL3Ruy9-o,10420
506
+ timm/utils/model_ema.py,sha256=-O-HAZKLxo069T_fN3CceNEaxGjJvbCxIFWjxWHJ0SM,11244
507
+ timm/utils/onnx.py,sha256=TjCKpjlBshVuRzC6my22kboyLz5a2BGyzMKmJxgn1aA,3922
508
+ timm/utils/random.py,sha256=Ysv6F3nIO8JYE8j6UrDxGyJDp3uNpq5v8U0KqL_8dic,178
509
+ timm/utils/summary.py,sha256=HYD5nJsTOD3DGqCPUu2L3sX4VjNFTybHbjwntSEWBi4,1325
510
+ timm/version.py,sha256=qKK4BMzdt84HiCorJPWqgEfa_DbJeuGx_bIPrDui2vc,22
videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/REQUESTED ADDED
File without changes
videollama2/lib/python3.10/site-packages/timm-1.0.3.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2019 Ross Wightman
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/crc_alt.h ADDED
@@ -0,0 +1,1343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // //////////////////////////////////////////////////////////
4
+ // Crc32.h
5
+ // Copyright (c) 2011-2019 Stephan Brumme. All rights reserved.
6
+ // Slicing-by-16 contributed by Bulat Ziganshin
7
+ // Tableless bytewise CRC contributed by Hagai Gold
8
+ // see http://create.stephan-brumme.com/disclaimer.html
9
+ //
10
+
11
+ // if running on an embedded system, you might consider shrinking the
12
+ // big Crc32Lookup table by undefining these lines:
13
+ #define CRC32_USE_LOOKUP_TABLE_BYTE
14
+ #define CRC32_USE_LOOKUP_TABLE_SLICING_BY_4
15
+ #define CRC32_USE_LOOKUP_TABLE_SLICING_BY_8
16
+ #define CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
17
+ // - crc32_bitwise doesn't need it at all
18
+ // - crc32_halfbyte has its own small lookup table
19
+ // - crc32_1byte_tableless and crc32_1byte_tableless2 don't need it at all
20
+ // - crc32_1byte needs only Crc32Lookup[0]
21
+ // - crc32_4bytes needs only Crc32Lookup[0..3]
22
+ // - crc32_8bytes needs only Crc32Lookup[0..7]
23
+ // - crc32_4x8bytes needs only Crc32Lookup[0..7]
24
+ // - crc32_16bytes needs all of Crc32Lookup
25
+ // using the aforementioned #defines the table is automatically fitted to your needs
26
+
27
+ // uint8_t, uint32_t, int32_t
28
+ #include <stdint.h>
29
+ // size_t
30
+ #include <cstddef>
31
+
32
+ // crc32_fast selects the fastest algorithm depending on flags (CRC32_USE_LOOKUP_...)
33
+ /// compute CRC32 using the fastest algorithm for large datasets on modern CPUs
34
+ uint32_t crc32_fast (const void* data, size_t length, uint32_t previousCrc32 = 0);
35
+
36
+ /// merge two CRC32 such that result = crc32(dataB, lengthB, crc32(dataA, lengthA))
37
+ uint32_t crc32_combine (uint32_t crcA, uint32_t crcB, size_t lengthB);
38
+
39
+ /// compute CRC32 (bitwise algorithm)
40
+ uint32_t crc32_bitwise (const void* data, size_t length, uint32_t previousCrc32 = 0);
41
+ /// compute CRC32 (half-byte algoritm)
42
+ uint32_t crc32_halfbyte(const void* data, size_t length, uint32_t previousCrc32 = 0);
43
+
44
+ #ifdef CRC32_USE_LOOKUP_TABLE_BYTE
45
+ /// compute CRC32 (standard algorithm)
46
+ uint32_t crc32_1byte (const void* data, size_t length, uint32_t previousCrc32 = 0);
47
+ #endif
48
+
49
+ /// compute CRC32 (byte algorithm) without lookup tables
50
+ uint32_t crc32_1byte_tableless (const void* data, size_t length, uint32_t previousCrc32 = 0);
51
+ /// compute CRC32 (byte algorithm) without lookup tables
52
+ uint32_t crc32_1byte_tableless2(const void* data, size_t length, uint32_t previousCrc32 = 0);
53
+
54
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_4
55
+ /// compute CRC32 (Slicing-by-4 algorithm)
56
+ uint32_t crc32_4bytes (const void* data, size_t length, uint32_t previousCrc32 = 0);
57
+ #endif
58
+
59
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_8
60
+ /// compute CRC32 (Slicing-by-8 algorithm)
61
+ uint32_t crc32_8bytes (const void* data, size_t length, uint32_t previousCrc32 = 0);
62
+ /// compute CRC32 (Slicing-by-8 algorithm), unroll inner loop 4 times
63
+ uint32_t crc32_4x8bytes(const void* data, size_t length, uint32_t previousCrc32 = 0);
64
+ #endif
65
+
66
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
67
+ /// compute CRC32 (Slicing-by-16 algorithm)
68
+ uint32_t crc32_16bytes (const void* data, size_t length, uint32_t previousCrc32 = 0);
69
+ /// compute CRC32 (Slicing-by-16 algorithm, prefetch upcoming data blocks)
70
+ uint32_t crc32_16bytes_prefetch(const void* data, size_t length, uint32_t previousCrc32 = 0, size_t prefetchAhead = 256);
71
+ #endif
72
+
73
+ // //////////////////////////////////////////////////////////
74
+ // Crc32.cpp
75
+ // Copyright (c) 2011-2019 Stephan Brumme. All rights reserved.
76
+ // Slicing-by-16 contributed by Bulat Ziganshin
77
+ // Tableless bytewise CRC contributed by Hagai Gold
78
+ // see http://create.stephan-brumme.com/disclaimer.html
79
+ //
80
+
81
+ // if running on an embedded system, you might consider shrinking the
82
+ // big Crc32Lookup table:
83
+ // - crc32_bitwise doesn't need it at all
84
+ // - crc32_halfbyte has its own small lookup table
85
+ // - crc32_1byte needs only Crc32Lookup[0]
86
+ // - crc32_4bytes needs only Crc32Lookup[0..3]
87
+ // - crc32_8bytes needs only Crc32Lookup[0..7]
88
+ // - crc32_4x8bytes needs only Crc32Lookup[0..7]
89
+ // - crc32_16bytes needs all of Crc32Lookup
90
+
91
+
92
+ #ifndef __LITTLE_ENDIAN
93
+ #define __LITTLE_ENDIAN 1234
94
+ #endif
95
+ #ifndef __BIG_ENDIAN
96
+ #define __BIG_ENDIAN 4321
97
+ #endif
98
+
99
+ // define endianess and some integer data types
100
+ #if defined(_MSC_VER) || defined(__MINGW32__)
101
+ // Windows always little endian
102
+ #define __BYTE_ORDER __LITTLE_ENDIAN
103
+
104
+ // intrinsics / prefetching
105
+ #if defined(_M_ARM64)
106
+ #include <intrin.h>
107
+ #else
108
+ #include <xmmintrin.h>
109
+ #endif
110
+
111
+ #ifdef __MINGW32__
112
+ #define PREFETCH(location) __builtin_prefetch(location)
113
+ #else
114
+ #if defined(_M_ARM64)
115
+ #define PREFETCH(location) __prefetch(location)
116
+ #else
117
+ #define PREFETCH(location) _mm_prefetch(location, _MM_HINT_T0)
118
+ #endif
119
+ #endif
120
+ #elif defined(__APPLE__)
121
+ #include <TargetConditionals.h>
122
+ #if TARGET_IPHONE_SIMULATOR
123
+ #define __BYTE_ORDER __LITTLE_ENDIAN
124
+ #elif TARGET_OS_IPHONE
125
+ #define __BYTE_ORDER __LITTLE_ENDIAN
126
+ #elif TARGET_OS_MAC
127
+ #include <machine/endian.h>
128
+ #if defined(__BIG_ENDIAN__)
129
+ #define __BYTE_ORDER __BIG_ENDIAN
130
+ #endif
131
+ #if defined(__LITTLE_ENDIAN__)
132
+ #define __BYTE_ORDER __LITTLE_ENDIAN
133
+ #endif
134
+ #else
135
+ # error "Unknown Apple platform"
136
+ #endif
137
+ #elif defined(__ARMEB__)
138
+ #define __BYTE_ORDER __BIG_ENDIAN
139
+ #elif (defined(__BYTE_ORDER__) and !defined(__BYTE_ORDER))
140
+ #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
141
+ #define __BYTE_ORDER __BIG_ENDIAN
142
+ #else
143
+ #define __BYTE_ORDER __LITTLE_ENDIAN
144
+ #endif
145
+ #else
146
+ // defines __BYTE_ORDER as __LITTLE_ENDIAN or __BIG_ENDIAN
147
+ #include <sys/param.h>
148
+ #endif
149
+
150
+ // intrinsics / prefetching
151
+ #ifdef __GNUC__
152
+ #define PREFETCH(location) __builtin_prefetch(location)
153
+ #else
154
+ #ifndef PREFETCH
155
+ // no prefetching
156
+ #define PREFETCH(location) ;
157
+ #endif
158
+ #endif
159
+
160
+ // abort if byte order is undefined
161
+ #ifndef __BYTE_ORDER
162
+ #error undefined byte order, compile with -D__BYTE_ORDER=1234 (if little endian) or -D__BYTE_ORDER=4321 (big endian)
163
+ #endif
164
+
165
+
166
+ namespace
167
+ {
168
+ /// zlib's CRC32 polynomial
169
+ const uint32_t Polynomial = 0xEDB88320;
170
+
171
+ /// swap endianess
172
+ static inline uint32_t swap(uint32_t x)
173
+ {
174
+ #if defined(__GNUC__) || defined(__clang__)
175
+ return __builtin_bswap32(x);
176
+ #else
177
+ return (x >> 24) |
178
+ ((x >> 8) & 0x0000FF00) |
179
+ ((x << 8) & 0x00FF0000) |
180
+ (x << 24);
181
+ #endif
182
+ }
183
+
184
+ /// Slicing-By-16
185
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
186
+ const size_t MaxSlice = 16;
187
+ #elif defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_8)
188
+ const size_t MaxSlice = 8;
189
+ #elif defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_4)
190
+ const size_t MaxSlice = 4;
191
+ #elif defined(CRC32_USE_LOOKUP_TABLE_BYTE)
192
+ const size_t MaxSlice = 1;
193
+ #else
194
+ #define NO_LUT // don't need Crc32Lookup at all
195
+ #endif
196
+
197
+ } // anonymous namespace
198
+
199
+ #ifndef NO_LUT
200
+ /// forward declaration, table is at the end of this file
201
+ extern const uint32_t Crc32Lookup[MaxSlice][256]; // extern is needed to keep compiler happy
202
+ #endif
203
+
204
+
205
+ /// compute CRC32 (bitwise algorithm)
206
+ uint32_t crc32_bitwise(const void* data, size_t length, uint32_t previousCrc32)
207
+ {
208
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
209
+ const uint8_t* current = (const uint8_t*) data;
210
+
211
+ while (length-- != 0)
212
+ {
213
+ crc ^= *current++;
214
+
215
+ for (int j = 0; j < 8; j++)
216
+ {
217
+ // branch-free
218
+ crc = (crc >> 1) ^ (-int32_t(crc & 1) & Polynomial);
219
+
220
+ // branching, much slower:
221
+ //if (crc & 1)
222
+ // crc = (crc >> 1) ^ Polynomial;
223
+ //else
224
+ // crc = crc >> 1;
225
+ }
226
+ }
227
+
228
+ return ~crc; // same as crc ^ 0xFFFFFFFF
229
+ }
230
+
231
+
232
+ /// compute CRC32 (half-byte algoritm)
233
+ uint32_t crc32_halfbyte(const void* data, size_t length, uint32_t previousCrc32)
234
+ {
235
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
236
+ const uint8_t* current = (const uint8_t*) data;
237
+
238
+ /// look-up table for half-byte, same as crc32Lookup[0][16*i]
239
+ static const uint32_t Crc32Lookup16[16] =
240
+ {
241
+ 0x00000000,0x1DB71064,0x3B6E20C8,0x26D930AC,0x76DC4190,0x6B6B51F4,0x4DB26158,0x5005713C,
242
+ 0xEDB88320,0xF00F9344,0xD6D6A3E8,0xCB61B38C,0x9B64C2B0,0x86D3D2D4,0xA00AE278,0xBDBDF21C
243
+ };
244
+
245
+ while (length-- != 0)
246
+ {
247
+ crc = Crc32Lookup16[(crc ^ *current ) & 0x0F] ^ (crc >> 4);
248
+ crc = Crc32Lookup16[(crc ^ (*current >> 4)) & 0x0F] ^ (crc >> 4);
249
+ current++;
250
+ }
251
+
252
+ return ~crc; // same as crc ^ 0xFFFFFFFF
253
+ }
254
+
255
+
256
+ #ifdef CRC32_USE_LOOKUP_TABLE_BYTE
257
+ /// compute CRC32 (standard algorithm)
258
+ uint32_t crc32_1byte(const void* data, size_t length, uint32_t previousCrc32)
259
+ {
260
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
261
+ const uint8_t* current = (const uint8_t*) data;
262
+
263
+ while (length-- != 0)
264
+ crc = (crc >> 8) ^ Crc32Lookup[0][(crc & 0xFF) ^ *current++];
265
+
266
+ return ~crc; // same as crc ^ 0xFFFFFFFF
267
+ }
268
+ #endif
269
+
270
+
271
+ /// compute CRC32 (byte algorithm) without lookup tables
272
+ uint32_t crc32_1byte_tableless(const void* data, size_t length, uint32_t previousCrc32)
273
+ {
274
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
275
+ const uint8_t* current = (const uint8_t*) data;
276
+
277
+ while (length-- != 0)
278
+ {
279
+ uint8_t s = uint8_t(crc) ^ *current++;
280
+
281
+ // Hagai Gold made me aware of this table-less algorithm and send me code
282
+
283
+ // polynomial 0xEDB88320 can be written in binary as 11101101101110001000001100100000b
284
+ // reverse the bits (or just assume bit 0 is the first one)
285
+ // and we have bits set at position 0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26
286
+ // => those are the shift offsets:
287
+ //crc = (crc >> 8) ^
288
+ // t ^
289
+ // (t >> 1) ^ (t >> 2) ^ (t >> 4) ^ (t >> 5) ^ // == y
290
+ // (t >> 7) ^ (t >> 8) ^ (t >> 10) ^ (t >> 11) ^ // == y >> 6
291
+ // (t >> 12) ^ (t >> 16) ^ // == z
292
+ // (t >> 22) ^ (t >> 26) ^ // == z >> 10
293
+ // (t >> 23);
294
+
295
+ // the fastest I can come up with:
296
+ uint32_t low = (s ^ (s << 6)) & 0xFF;
297
+ uint32_t a = (low * ((1 << 23) + (1 << 14) + (1 << 2)));
298
+ crc = (crc >> 8) ^
299
+ (low * ((1 << 24) + (1 << 16) + (1 << 8))) ^
300
+ a ^
301
+ (a >> 1) ^
302
+ (low * ((1 << 20) + (1 << 12) )) ^
303
+ (low << 19) ^
304
+ (low << 17) ^
305
+ (low >> 2);
306
+
307
+ // Hagai's code:
308
+ /*uint32_t t = (s ^ (s << 6)) << 24;
309
+ // some temporaries to optimize XOR
310
+ uint32_t x = (t >> 1) ^ (t >> 2);
311
+ uint32_t y = x ^ (x >> 3);
312
+ uint32_t z = (t >> 12) ^ (t >> 16);
313
+ crc = (crc >> 8) ^
314
+ t ^ (t >> 23) ^
315
+ y ^ (y >> 6) ^
316
+ z ^ (z >> 10);*/
317
+ }
318
+
319
+ return ~crc; // same as crc ^ 0xFFFFFFFF
320
+ }
321
+
322
+
323
+ /// compute CRC32 (byte algorithm) without lookup tables
324
+ uint32_t crc32_1byte_tableless2(const void* data, size_t length, uint32_t previousCrc32)
325
+ {
326
+ int32_t crc = ~previousCrc32; // note: signed integer, right shift distributes sign bit into lower bits
327
+ const uint8_t* current = (const uint8_t*) data;
328
+
329
+ while (length-- != 0)
330
+ {
331
+ crc = crc ^ *current++;
332
+
333
+ uint32_t c = (((crc << 31) >> 31) & ((Polynomial >> 7) ^ (Polynomial >> 1))) ^
334
+ (((crc << 30) >> 31) & ((Polynomial >> 6) ^ Polynomial)) ^
335
+ (((crc << 29) >> 31) & (Polynomial >> 5)) ^
336
+ (((crc << 28) >> 31) & (Polynomial >> 4)) ^
337
+ (((crc << 27) >> 31) & (Polynomial >> 3)) ^
338
+ (((crc << 26) >> 31) & (Polynomial >> 2)) ^
339
+ (((crc << 25) >> 31) & (Polynomial >> 1)) ^
340
+ (((crc << 24) >> 31) & Polynomial);
341
+
342
+ crc = ((uint32_t)crc >> 8) ^ c; // convert to unsigned integer before right shift
343
+ }
344
+
345
+ return ~crc; // same as crc ^ 0xFFFFFFFF
346
+ }
347
+
348
+
349
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_4
350
+ /// compute CRC32 (Slicing-by-4 algorithm)
351
+ uint32_t crc32_4bytes(const void* data, size_t length, uint32_t previousCrc32)
352
+ {
353
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
354
+ const uint32_t* current = (const uint32_t*) data;
355
+
356
+ // process four bytes at once (Slicing-by-4)
357
+ while (length >= 4)
358
+ {
359
+ #if __BYTE_ORDER == __BIG_ENDIAN
360
+ uint32_t one = *current++ ^ swap(crc);
361
+ crc = Crc32Lookup[0][ one & 0xFF] ^
362
+ Crc32Lookup[1][(one>> 8) & 0xFF] ^
363
+ Crc32Lookup[2][(one>>16) & 0xFF] ^
364
+ Crc32Lookup[3][(one>>24) & 0xFF];
365
+ #else
366
+ uint32_t one = *current++ ^ crc;
367
+ crc = Crc32Lookup[0][(one>>24) & 0xFF] ^
368
+ Crc32Lookup[1][(one>>16) & 0xFF] ^
369
+ Crc32Lookup[2][(one>> 8) & 0xFF] ^
370
+ Crc32Lookup[3][ one & 0xFF];
371
+ #endif
372
+
373
+ length -= 4;
374
+ }
375
+
376
+ const uint8_t* currentChar = (const uint8_t*) current;
377
+ // remaining 1 to 3 bytes (standard algorithm)
378
+ while (length-- != 0)
379
+ crc = (crc >> 8) ^ Crc32Lookup[0][(crc & 0xFF) ^ *currentChar++];
380
+
381
+ return ~crc; // same as crc ^ 0xFFFFFFFF
382
+ }
383
+ #endif
384
+
385
+
386
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_8
387
+ /// compute CRC32 (Slicing-by-8 algorithm)
388
+ uint32_t crc32_8bytes(const void* data, size_t length, uint32_t previousCrc32)
389
+ {
390
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
391
+ const uint32_t* current = (const uint32_t*) data;
392
+
393
+ // process eight bytes at once (Slicing-by-8)
394
+ while (length >= 8)
395
+ {
396
+ #if __BYTE_ORDER == __BIG_ENDIAN
397
+ uint32_t one = *current++ ^ swap(crc);
398
+ uint32_t two = *current++;
399
+ crc = Crc32Lookup[0][ two & 0xFF] ^
400
+ Crc32Lookup[1][(two>> 8) & 0xFF] ^
401
+ Crc32Lookup[2][(two>>16) & 0xFF] ^
402
+ Crc32Lookup[3][(two>>24) & 0xFF] ^
403
+ Crc32Lookup[4][ one & 0xFF] ^
404
+ Crc32Lookup[5][(one>> 8) & 0xFF] ^
405
+ Crc32Lookup[6][(one>>16) & 0xFF] ^
406
+ Crc32Lookup[7][(one>>24) & 0xFF];
407
+ #else
408
+ uint32_t one = *current++ ^ crc;
409
+ uint32_t two = *current++;
410
+ crc = Crc32Lookup[0][(two>>24) & 0xFF] ^
411
+ Crc32Lookup[1][(two>>16) & 0xFF] ^
412
+ Crc32Lookup[2][(two>> 8) & 0xFF] ^
413
+ Crc32Lookup[3][ two & 0xFF] ^
414
+ Crc32Lookup[4][(one>>24) & 0xFF] ^
415
+ Crc32Lookup[5][(one>>16) & 0xFF] ^
416
+ Crc32Lookup[6][(one>> 8) & 0xFF] ^
417
+ Crc32Lookup[7][ one & 0xFF];
418
+ #endif
419
+
420
+ length -= 8;
421
+ }
422
+
423
+ const uint8_t* currentChar = (const uint8_t*) current;
424
+ // remaining 1 to 7 bytes (standard algorithm)
425
+ while (length-- != 0)
426
+ crc = (crc >> 8) ^ Crc32Lookup[0][(crc & 0xFF) ^ *currentChar++];
427
+
428
+ return ~crc; // same as crc ^ 0xFFFFFFFF
429
+ }
430
+
431
+
432
+ /// compute CRC32 (Slicing-by-8 algorithm), unroll inner loop 4 times
433
+ uint32_t crc32_4x8bytes(const void* data, size_t length, uint32_t previousCrc32)
434
+ {
435
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
436
+ const uint32_t* current = (const uint32_t*) data;
437
+
438
+ // enabling optimization (at least -O2) automatically unrolls the inner for-loop
439
+ const size_t Unroll = 4;
440
+ const size_t BytesAtOnce = 8 * Unroll;
441
+
442
+ // process 4x eight bytes at once (Slicing-by-8)
443
+ while (length >= BytesAtOnce)
444
+ {
445
+ for (size_t unrolling = 0; unrolling < Unroll; unrolling++)
446
+ {
447
+ #if __BYTE_ORDER == __BIG_ENDIAN
448
+ uint32_t one = *current++ ^ swap(crc);
449
+ uint32_t two = *current++;
450
+ crc = Crc32Lookup[0][ two & 0xFF] ^
451
+ Crc32Lookup[1][(two>> 8) & 0xFF] ^
452
+ Crc32Lookup[2][(two>>16) & 0xFF] ^
453
+ Crc32Lookup[3][(two>>24) & 0xFF] ^
454
+ Crc32Lookup[4][ one & 0xFF] ^
455
+ Crc32Lookup[5][(one>> 8) & 0xFF] ^
456
+ Crc32Lookup[6][(one>>16) & 0xFF] ^
457
+ Crc32Lookup[7][(one>>24) & 0xFF];
458
+ #else
459
+ uint32_t one = *current++ ^ crc;
460
+ uint32_t two = *current++;
461
+ crc = Crc32Lookup[0][(two>>24) & 0xFF] ^
462
+ Crc32Lookup[1][(two>>16) & 0xFF] ^
463
+ Crc32Lookup[2][(two>> 8) & 0xFF] ^
464
+ Crc32Lookup[3][ two & 0xFF] ^
465
+ Crc32Lookup[4][(one>>24) & 0xFF] ^
466
+ Crc32Lookup[5][(one>>16) & 0xFF] ^
467
+ Crc32Lookup[6][(one>> 8) & 0xFF] ^
468
+ Crc32Lookup[7][ one & 0xFF];
469
+ #endif
470
+
471
+ }
472
+
473
+ length -= BytesAtOnce;
474
+ }
475
+
476
+ const uint8_t* currentChar = (const uint8_t*) current;
477
+ // remaining 1 to 31 bytes (standard algorithm)
478
+ while (length-- != 0)
479
+ crc = (crc >> 8) ^ Crc32Lookup[0][(crc & 0xFF) ^ *currentChar++];
480
+
481
+ return ~crc; // same as crc ^ 0xFFFFFFFF
482
+ }
483
+ #endif // CRC32_USE_LOOKUP_TABLE_SLICING_BY_8
484
+
485
+
486
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
487
+ /// compute CRC32 (Slicing-by-16 algorithm)
488
+ uint32_t crc32_16bytes(const void* data, size_t length, uint32_t previousCrc32)
489
+ {
490
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
491
+ const uint32_t* current = (const uint32_t*) data;
492
+
493
+ // enabling optimization (at least -O2) automatically unrolls the inner for-loop
494
+ const size_t Unroll = 4;
495
+ const size_t BytesAtOnce = 16 * Unroll;
496
+
497
+ while (length >= BytesAtOnce)
498
+ {
499
+ for (size_t unrolling = 0; unrolling < Unroll; unrolling++)
500
+ {
501
+ #if __BYTE_ORDER == __BIG_ENDIAN
502
+ uint32_t one = *current++ ^ swap(crc);
503
+ uint32_t two = *current++;
504
+ uint32_t three = *current++;
505
+ uint32_t four = *current++;
506
+ crc = Crc32Lookup[ 0][ four & 0xFF] ^
507
+ Crc32Lookup[ 1][(four >> 8) & 0xFF] ^
508
+ Crc32Lookup[ 2][(four >> 16) & 0xFF] ^
509
+ Crc32Lookup[ 3][(four >> 24) & 0xFF] ^
510
+ Crc32Lookup[ 4][ three & 0xFF] ^
511
+ Crc32Lookup[ 5][(three >> 8) & 0xFF] ^
512
+ Crc32Lookup[ 6][(three >> 16) & 0xFF] ^
513
+ Crc32Lookup[ 7][(three >> 24) & 0xFF] ^
514
+ Crc32Lookup[ 8][ two & 0xFF] ^
515
+ Crc32Lookup[ 9][(two >> 8) & 0xFF] ^
516
+ Crc32Lookup[10][(two >> 16) & 0xFF] ^
517
+ Crc32Lookup[11][(two >> 24) & 0xFF] ^
518
+ Crc32Lookup[12][ one & 0xFF] ^
519
+ Crc32Lookup[13][(one >> 8) & 0xFF] ^
520
+ Crc32Lookup[14][(one >> 16) & 0xFF] ^
521
+ Crc32Lookup[15][(one >> 24) & 0xFF];
522
+ #else
523
+ uint32_t one = *current++ ^ crc;
524
+ uint32_t two = *current++;
525
+ uint32_t three = *current++;
526
+ uint32_t four = *current++;
527
+ crc = Crc32Lookup[ 0][(four >> 24) & 0xFF] ^
528
+ Crc32Lookup[ 1][(four >> 16) & 0xFF] ^
529
+ Crc32Lookup[ 2][(four >> 8) & 0xFF] ^
530
+ Crc32Lookup[ 3][ four & 0xFF] ^
531
+ Crc32Lookup[ 4][(three >> 24) & 0xFF] ^
532
+ Crc32Lookup[ 5][(three >> 16) & 0xFF] ^
533
+ Crc32Lookup[ 6][(three >> 8) & 0xFF] ^
534
+ Crc32Lookup[ 7][ three & 0xFF] ^
535
+ Crc32Lookup[ 8][(two >> 24) & 0xFF] ^
536
+ Crc32Lookup[ 9][(two >> 16) & 0xFF] ^
537
+ Crc32Lookup[10][(two >> 8) & 0xFF] ^
538
+ Crc32Lookup[11][ two & 0xFF] ^
539
+ Crc32Lookup[12][(one >> 24) & 0xFF] ^
540
+ Crc32Lookup[13][(one >> 16) & 0xFF] ^
541
+ Crc32Lookup[14][(one >> 8) & 0xFF] ^
542
+ Crc32Lookup[15][ one & 0xFF];
543
+ #endif
544
+ }
545
+
546
+ length -= BytesAtOnce;
547
+ }
548
+
549
+ const uint8_t* currentChar = (const uint8_t*) current;
550
+ // remaining 1 to 63 bytes (standard algorithm)
551
+ while (length-- != 0)
552
+ crc = (crc >> 8) ^ Crc32Lookup[0][(crc & 0xFF) ^ *currentChar++];
553
+
554
+ return ~crc; // same as crc ^ 0xFFFFFFFF
555
+ }
556
+
557
+
558
+ /// compute CRC32 (Slicing-by-16 algorithm, prefetch upcoming data blocks)
559
+ uint32_t crc32_16bytes_prefetch(const void* data, size_t length, uint32_t previousCrc32, size_t prefetchAhead)
560
+ {
561
+ // CRC code is identical to crc32_16bytes (including unrolling), only added prefetching
562
+ // 256 bytes look-ahead seems to be the sweet spot on Core i7 CPUs
563
+
564
+ uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
565
+ const uint32_t* current = (const uint32_t*) data;
566
+
567
+ // enabling optimization (at least -O2) automatically unrolls the for-loop
568
+ const size_t Unroll = 4;
569
+ const size_t BytesAtOnce = 16 * Unroll;
570
+
571
+ while (length >= BytesAtOnce + prefetchAhead)
572
+ {
573
+ PREFETCH(((const char*) current) + prefetchAhead);
574
+
575
+ for (size_t unrolling = 0; unrolling < Unroll; unrolling++)
576
+ {
577
+ #if __BYTE_ORDER == __BIG_ENDIAN
578
+ uint32_t one = *current++ ^ swap(crc);
579
+ uint32_t two = *current++;
580
+ uint32_t three = *current++;
581
+ uint32_t four = *current++;
582
+ crc = Crc32Lookup[ 0][ four & 0xFF] ^
583
+ Crc32Lookup[ 1][(four >> 8) & 0xFF] ^
584
+ Crc32Lookup[ 2][(four >> 16) & 0xFF] ^
585
+ Crc32Lookup[ 3][(four >> 24) & 0xFF] ^
586
+ Crc32Lookup[ 4][ three & 0xFF] ^
587
+ Crc32Lookup[ 5][(three >> 8) & 0xFF] ^
588
+ Crc32Lookup[ 6][(three >> 16) & 0xFF] ^
589
+ Crc32Lookup[ 7][(three >> 24) & 0xFF] ^
590
+ Crc32Lookup[ 8][ two & 0xFF] ^
591
+ Crc32Lookup[ 9][(two >> 8) & 0xFF] ^
592
+ Crc32Lookup[10][(two >> 16) & 0xFF] ^
593
+ Crc32Lookup[11][(two >> 24) & 0xFF] ^
594
+ Crc32Lookup[12][ one & 0xFF] ^
595
+ Crc32Lookup[13][(one >> 8) & 0xFF] ^
596
+ Crc32Lookup[14][(one >> 16) & 0xFF] ^
597
+ Crc32Lookup[15][(one >> 24) & 0xFF];
598
+ #else
599
+ uint32_t one = *current++ ^ crc;
600
+ uint32_t two = *current++;
601
+ uint32_t three = *current++;
602
+ uint32_t four = *current++;
603
+ crc = Crc32Lookup[ 0][(four >> 24) & 0xFF] ^
604
+ Crc32Lookup[ 1][(four >> 16) & 0xFF] ^
605
+ Crc32Lookup[ 2][(four >> 8) & 0xFF] ^
606
+ Crc32Lookup[ 3][ four & 0xFF] ^
607
+ Crc32Lookup[ 4][(three >> 24) & 0xFF] ^
608
+ Crc32Lookup[ 5][(three >> 16) & 0xFF] ^
609
+ Crc32Lookup[ 6][(three >> 8) & 0xFF] ^
610
+ Crc32Lookup[ 7][ three & 0xFF] ^
611
+ Crc32Lookup[ 8][(two >> 24) & 0xFF] ^
612
+ Crc32Lookup[ 9][(two >> 16) & 0xFF] ^
613
+ Crc32Lookup[10][(two >> 8) & 0xFF] ^
614
+ Crc32Lookup[11][ two & 0xFF] ^
615
+ Crc32Lookup[12][(one >> 24) & 0xFF] ^
616
+ Crc32Lookup[13][(one >> 16) & 0xFF] ^
617
+ Crc32Lookup[14][(one >> 8) & 0xFF] ^
618
+ Crc32Lookup[15][ one & 0xFF];
619
+ #endif
620
+ }
621
+
622
+ length -= BytesAtOnce;
623
+ }
624
+
625
+ const uint8_t* currentChar = (const uint8_t*) current;
626
+ // remaining 1 to 63 bytes (standard algorithm)
627
+ while (length-- != 0)
628
+ crc = (crc >> 8) ^ Crc32Lookup[0][(crc & 0xFF) ^ *currentChar++];
629
+
630
+ return ~crc; // same as crc ^ 0xFFFFFFFF
631
+ }
632
+ #endif
633
+
634
+
635
+ /// compute CRC32 using the fastest algorithm for large datasets on modern CPUs
636
+ uint32_t crc32_fast(const void* data, size_t length, uint32_t previousCrc32)
637
+ {
638
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
639
+ return crc32_16bytes (data, length, previousCrc32);
640
+ #elif defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_8)
641
+ return crc32_8bytes (data, length, previousCrc32);
642
+ #elif defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_4)
643
+ return crc32_4bytes (data, length, previousCrc32);
644
+ #elif defined(CRC32_USE_LOOKUP_TABLE_BYTE)
645
+ return crc32_1byte (data, length, previousCrc32);
646
+ #else
647
+ return crc32_halfbyte(data, length, previousCrc32);
648
+ #endif
649
+ }
650
+
651
+
652
+ /// merge two CRC32 such that result = crc32(dataB, lengthB, crc32(dataA, lengthA))
653
+ uint32_t crc32_combine(uint32_t crcA, uint32_t crcB, size_t lengthB)
654
+ {
655
+ // based on Mark Adler's crc_combine from
656
+ // https://github.com/madler/pigz/blob/master/pigz.c
657
+
658
+ // main idea:
659
+ // - if you have two equally-sized blocks A and B,
660
+ // then you can create a block C = A ^ B
661
+ // which has the property crc(C) = crc(A) ^ crc(B)
662
+ // - if you append length(B) zeros to A and call it A' (think of it as AAAA000)
663
+ // and prepend length(A) zeros to B and call it B' (think of it as 0000BBB)
664
+ // then exists a C' = A' ^ B'
665
+ // - remember: if you XOR someting with zero, it remains unchanged: X ^ 0 = X
666
+ // - that means C' = A concat B so that crc(A concat B) = crc(C') = crc(A') ^ crc(B')
667
+ // - the trick is to compute crc(A') based on crc(A)
668
+ // and crc(B') based on crc(B)
669
+ // - since B' starts with many zeros, the crc of those initial zeros is still zero
670
+ // - that means crc(B') = crc(B)
671
+ // - unfortunately the trailing zeros of A' change the crc, so usually crc(A') != crc(A)
672
+ // - the following code is a fast algorithm to compute crc(A')
673
+ // - starting with crc(A) and appending length(B) zeros, needing just log2(length(B)) iterations
674
+ // - the details are explained by the original author at
675
+ // https://stackoverflow.com/questions/23122312/crc-calculation-of-a-mostly-static-data-stream/23126768
676
+ //
677
+ // notes:
678
+ // - I squeezed everything into one function to keep global namespace clean (original code two helper functions)
679
+ // - most original comments are still in place, I added comments where these helper functions where made inline code
680
+ // - performance-wise there isn't any differenze to the original zlib/pigz code
681
+
682
+ // degenerated case
683
+ if (lengthB == 0)
684
+ return crcA;
685
+
686
+ /// CRC32 => 32 bits
687
+ const uint32_t CrcBits = 32;
688
+
689
+ uint32_t odd [CrcBits]; // odd-power-of-two zeros operator
690
+ uint32_t even[CrcBits]; // even-power-of-two zeros operator
691
+
692
+ // put operator for one zero bit in odd
693
+ odd[0] = Polynomial; // CRC-32 polynomial
694
+ for (uint32_t i = 1; i < CrcBits; i++)
695
+ odd[i] = 1 << (i - 1);
696
+
697
+ // put operator for two zero bits in even
698
+ // same as gf2_matrix_square(even, odd);
699
+ for (uint32_t i = 0; i < CrcBits; i++)
700
+ {
701
+ uint32_t vec = odd[i];
702
+ even[i] = 0;
703
+ for (int j = 0; vec != 0; j++, vec >>= 1)
704
+ if (vec & 1)
705
+ even[i] ^= odd[j];
706
+ }
707
+ // put operator for four zero bits in odd
708
+ // same as gf2_matrix_square(odd, even);
709
+ for (uint32_t i = 0; i < CrcBits; i++)
710
+ {
711
+ uint32_t vec = even[i];
712
+ odd[i] = 0;
713
+ for (int j = 0; vec != 0; j++, vec >>= 1)
714
+ if (vec & 1)
715
+ odd[i] ^= even[j];
716
+ }
717
+
718
+ // the following loop becomes much shorter if I keep swapping even and odd
719
+ uint32_t* a = even;
720
+ uint32_t* b = odd;
721
+ // apply secondLength zeros to firstCrc32
722
+ for (; lengthB > 0; lengthB >>= 1)
723
+ {
724
+ // same as gf2_matrix_square(a, b);
725
+ for (uint32_t i = 0; i < CrcBits; i++)
726
+ {
727
+ uint32_t vec = b[i];
728
+ a[i] = 0;
729
+ for (int j = 0; vec != 0; j++, vec >>= 1)
730
+ if (vec & 1)
731
+ a[i] ^= b[j];
732
+ }
733
+
734
+ // apply zeros operator for this bit
735
+ if (lengthB & 1)
736
+ {
737
+ // same as firstCrc32 = gf2_matrix_times(a, firstCrc32);
738
+ uint32_t sum = 0;
739
+ for (int i = 0; crcA != 0; i++, crcA >>= 1)
740
+ if (crcA & 1)
741
+ sum ^= a[i];
742
+ crcA = sum;
743
+ }
744
+
745
+ // switch even and odd
746
+ uint32_t* t = a; a = b; b = t;
747
+ }
748
+
749
+ // return combined crc
750
+ return crcA ^ crcB;
751
+ }
752
+
753
+
754
+ // //////////////////////////////////////////////////////////
755
+ // constants
756
+
757
+
758
+ #ifndef NO_LUT
759
+ /// look-up table, already declared above
760
+ const uint32_t Crc32Lookup[MaxSlice][256] =
761
+ {
762
+ //// same algorithm as crc32_bitwise
763
+ //for (int i = 0; i <= 0xFF; i++)
764
+ //{
765
+ // uint32_t crc = i;
766
+ // for (int j = 0; j < 8; j++)
767
+ // crc = (crc >> 1) ^ ((crc & 1) * Polynomial);
768
+ // Crc32Lookup[0][i] = crc;
769
+ //}
770
+ //// ... and the following slicing-by-8 algorithm (from Intel):
771
+ //// http://www.intel.com/technology/comms/perfnet/download/CRC_generators.pdf
772
+ //// http://sourceforge.net/projects/slicing-by-8/
773
+ //for (int slice = 1; slice < MaxSlice; slice++)
774
+ // Crc32Lookup[slice][i] = (Crc32Lookup[slice - 1][i] >> 8) ^ Crc32Lookup[0][Crc32Lookup[slice - 1][i] & 0xFF];
775
+ {
776
+ // note: the first number of every second row corresponds to the half-byte look-up table !
777
+ 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,
778
+ 0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
779
+ 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,
780
+ 0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
781
+ 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,
782
+ 0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
783
+ 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
784
+ 0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
785
+ 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,
786
+ 0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
787
+ 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,
788
+ 0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
789
+ 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,
790
+ 0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
791
+ 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
792
+ 0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
793
+ 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,
794
+ 0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
795
+ 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,
796
+ 0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
797
+ 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
798
+ 0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
799
+ 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,
800
+ 0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
801
+ 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,
802
+ 0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
803
+ 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
804
+ 0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
805
+ 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,
806
+ 0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
807
+ 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,
808
+ 0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
809
+ }
810
+
811
+ #if defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_4) || defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_8) || defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_16)
812
+ // beyond this point only relevant for Slicing-by-4, Slicing-by-8 and Slicing-by-16
813
+ ,{
814
+ 0x00000000,0x191B3141,0x32366282,0x2B2D53C3,0x646CC504,0x7D77F445,0x565AA786,0x4F4196C7,
815
+ 0xC8D98A08,0xD1C2BB49,0xFAEFE88A,0xE3F4D9CB,0xACB54F0C,0xB5AE7E4D,0x9E832D8E,0x87981CCF,
816
+ 0x4AC21251,0x53D92310,0x78F470D3,0x61EF4192,0x2EAED755,0x37B5E614,0x1C98B5D7,0x05838496,
817
+ 0x821B9859,0x9B00A918,0xB02DFADB,0xA936CB9A,0xE6775D5D,0xFF6C6C1C,0xD4413FDF,0xCD5A0E9E,
818
+ 0x958424A2,0x8C9F15E3,0xA7B24620,0xBEA97761,0xF1E8E1A6,0xE8F3D0E7,0xC3DE8324,0xDAC5B265,
819
+ 0x5D5DAEAA,0x44469FEB,0x6F6BCC28,0x7670FD69,0x39316BAE,0x202A5AEF,0x0B07092C,0x121C386D,
820
+ 0xDF4636F3,0xC65D07B2,0xED705471,0xF46B6530,0xBB2AF3F7,0xA231C2B6,0x891C9175,0x9007A034,
821
+ 0x179FBCFB,0x0E848DBA,0x25A9DE79,0x3CB2EF38,0x73F379FF,0x6AE848BE,0x41C51B7D,0x58DE2A3C,
822
+ 0xF0794F05,0xE9627E44,0xC24F2D87,0xDB541CC6,0x94158A01,0x8D0EBB40,0xA623E883,0xBF38D9C2,
823
+ 0x38A0C50D,0x21BBF44C,0x0A96A78F,0x138D96CE,0x5CCC0009,0x45D73148,0x6EFA628B,0x77E153CA,
824
+ 0xBABB5D54,0xA3A06C15,0x888D3FD6,0x91960E97,0xDED79850,0xC7CCA911,0xECE1FAD2,0xF5FACB93,
825
+ 0x7262D75C,0x6B79E61D,0x4054B5DE,0x594F849F,0x160E1258,0x0F152319,0x243870DA,0x3D23419B,
826
+ 0x65FD6BA7,0x7CE65AE6,0x57CB0925,0x4ED03864,0x0191AEA3,0x188A9FE2,0x33A7CC21,0x2ABCFD60,
827
+ 0xAD24E1AF,0xB43FD0EE,0x9F12832D,0x8609B26C,0xC94824AB,0xD05315EA,0xFB7E4629,0xE2657768,
828
+ 0x2F3F79F6,0x362448B7,0x1D091B74,0x04122A35,0x4B53BCF2,0x52488DB3,0x7965DE70,0x607EEF31,
829
+ 0xE7E6F3FE,0xFEFDC2BF,0xD5D0917C,0xCCCBA03D,0x838A36FA,0x9A9107BB,0xB1BC5478,0xA8A76539,
830
+ 0x3B83984B,0x2298A90A,0x09B5FAC9,0x10AECB88,0x5FEF5D4F,0x46F46C0E,0x6DD93FCD,0x74C20E8C,
831
+ 0xF35A1243,0xEA412302,0xC16C70C1,0xD8774180,0x9736D747,0x8E2DE606,0xA500B5C5,0xBC1B8484,
832
+ 0x71418A1A,0x685ABB5B,0x4377E898,0x5A6CD9D9,0x152D4F1E,0x0C367E5F,0x271B2D9C,0x3E001CDD,
833
+ 0xB9980012,0xA0833153,0x8BAE6290,0x92B553D1,0xDDF4C516,0xC4EFF457,0xEFC2A794,0xF6D996D5,
834
+ 0xAE07BCE9,0xB71C8DA8,0x9C31DE6B,0x852AEF2A,0xCA6B79ED,0xD37048AC,0xF85D1B6F,0xE1462A2E,
835
+ 0x66DE36E1,0x7FC507A0,0x54E85463,0x4DF36522,0x02B2F3E5,0x1BA9C2A4,0x30849167,0x299FA026,
836
+ 0xE4C5AEB8,0xFDDE9FF9,0xD6F3CC3A,0xCFE8FD7B,0x80A96BBC,0x99B25AFD,0xB29F093E,0xAB84387F,
837
+ 0x2C1C24B0,0x350715F1,0x1E2A4632,0x07317773,0x4870E1B4,0x516BD0F5,0x7A468336,0x635DB277,
838
+ 0xCBFAD74E,0xD2E1E60F,0xF9CCB5CC,0xE0D7848D,0xAF96124A,0xB68D230B,0x9DA070C8,0x84BB4189,
839
+ 0x03235D46,0x1A386C07,0x31153FC4,0x280E0E85,0x674F9842,0x7E54A903,0x5579FAC0,0x4C62CB81,
840
+ 0x8138C51F,0x9823F45E,0xB30EA79D,0xAA1596DC,0xE554001B,0xFC4F315A,0xD7626299,0xCE7953D8,
841
+ 0x49E14F17,0x50FA7E56,0x7BD72D95,0x62CC1CD4,0x2D8D8A13,0x3496BB52,0x1FBBE891,0x06A0D9D0,
842
+ 0x5E7EF3EC,0x4765C2AD,0x6C48916E,0x7553A02F,0x3A1236E8,0x230907A9,0x0824546A,0x113F652B,
843
+ 0x96A779E4,0x8FBC48A5,0xA4911B66,0xBD8A2A27,0xF2CBBCE0,0xEBD08DA1,0xC0FDDE62,0xD9E6EF23,
844
+ 0x14BCE1BD,0x0DA7D0FC,0x268A833F,0x3F91B27E,0x70D024B9,0x69CB15F8,0x42E6463B,0x5BFD777A,
845
+ 0xDC656BB5,0xC57E5AF4,0xEE530937,0xF7483876,0xB809AEB1,0xA1129FF0,0x8A3FCC33,0x9324FD72,
846
+ },
847
+
848
+ {
849
+ 0x00000000,0x01C26A37,0x0384D46E,0x0246BE59,0x0709A8DC,0x06CBC2EB,0x048D7CB2,0x054F1685,
850
+ 0x0E1351B8,0x0FD13B8F,0x0D9785D6,0x0C55EFE1,0x091AF964,0x08D89353,0x0A9E2D0A,0x0B5C473D,
851
+ 0x1C26A370,0x1DE4C947,0x1FA2771E,0x1E601D29,0x1B2F0BAC,0x1AED619B,0x18ABDFC2,0x1969B5F5,
852
+ 0x1235F2C8,0x13F798FF,0x11B126A6,0x10734C91,0x153C5A14,0x14FE3023,0x16B88E7A,0x177AE44D,
853
+ 0x384D46E0,0x398F2CD7,0x3BC9928E,0x3A0BF8B9,0x3F44EE3C,0x3E86840B,0x3CC03A52,0x3D025065,
854
+ 0x365E1758,0x379C7D6F,0x35DAC336,0x3418A901,0x3157BF84,0x3095D5B3,0x32D36BEA,0x331101DD,
855
+ 0x246BE590,0x25A98FA7,0x27EF31FE,0x262D5BC9,0x23624D4C,0x22A0277B,0x20E69922,0x2124F315,
856
+ 0x2A78B428,0x2BBADE1F,0x29FC6046,0x283E0A71,0x2D711CF4,0x2CB376C3,0x2EF5C89A,0x2F37A2AD,
857
+ 0x709A8DC0,0x7158E7F7,0x731E59AE,0x72DC3399,0x7793251C,0x76514F2B,0x7417F172,0x75D59B45,
858
+ 0x7E89DC78,0x7F4BB64F,0x7D0D0816,0x7CCF6221,0x798074A4,0x78421E93,0x7A04A0CA,0x7BC6CAFD,
859
+ 0x6CBC2EB0,0x6D7E4487,0x6F38FADE,0x6EFA90E9,0x6BB5866C,0x6A77EC5B,0x68315202,0x69F33835,
860
+ 0x62AF7F08,0x636D153F,0x612BAB66,0x60E9C151,0x65A6D7D4,0x6464BDE3,0x662203BA,0x67E0698D,
861
+ 0x48D7CB20,0x4915A117,0x4B531F4E,0x4A917579,0x4FDE63FC,0x4E1C09CB,0x4C5AB792,0x4D98DDA5,
862
+ 0x46C49A98,0x4706F0AF,0x45404EF6,0x448224C1,0x41CD3244,0x400F5873,0x4249E62A,0x438B8C1D,
863
+ 0x54F16850,0x55330267,0x5775BC3E,0x56B7D609,0x53F8C08C,0x523AAABB,0x507C14E2,0x51BE7ED5,
864
+ 0x5AE239E8,0x5B2053DF,0x5966ED86,0x58A487B1,0x5DEB9134,0x5C29FB03,0x5E6F455A,0x5FAD2F6D,
865
+ 0xE1351B80,0xE0F771B7,0xE2B1CFEE,0xE373A5D9,0xE63CB35C,0xE7FED96B,0xE5B86732,0xE47A0D05,
866
+ 0xEF264A38,0xEEE4200F,0xECA29E56,0xED60F461,0xE82FE2E4,0xE9ED88D3,0xEBAB368A,0xEA695CBD,
867
+ 0xFD13B8F0,0xFCD1D2C7,0xFE976C9E,0xFF5506A9,0xFA1A102C,0xFBD87A1B,0xF99EC442,0xF85CAE75,
868
+ 0xF300E948,0xF2C2837F,0xF0843D26,0xF1465711,0xF4094194,0xF5CB2BA3,0xF78D95FA,0xF64FFFCD,
869
+ 0xD9785D60,0xD8BA3757,0xDAFC890E,0xDB3EE339,0xDE71F5BC,0xDFB39F8B,0xDDF521D2,0xDC374BE5,
870
+ 0xD76B0CD8,0xD6A966EF,0xD4EFD8B6,0xD52DB281,0xD062A404,0xD1A0CE33,0xD3E6706A,0xD2241A5D,
871
+ 0xC55EFE10,0xC49C9427,0xC6DA2A7E,0xC7184049,0xC25756CC,0xC3953CFB,0xC1D382A2,0xC011E895,
872
+ 0xCB4DAFA8,0xCA8FC59F,0xC8C97BC6,0xC90B11F1,0xCC440774,0xCD866D43,0xCFC0D31A,0xCE02B92D,
873
+ 0x91AF9640,0x906DFC77,0x922B422E,0x93E92819,0x96A63E9C,0x976454AB,0x9522EAF2,0x94E080C5,
874
+ 0x9FBCC7F8,0x9E7EADCF,0x9C381396,0x9DFA79A1,0x98B56F24,0x99770513,0x9B31BB4A,0x9AF3D17D,
875
+ 0x8D893530,0x8C4B5F07,0x8E0DE15E,0x8FCF8B69,0x8A809DEC,0x8B42F7DB,0x89044982,0x88C623B5,
876
+ 0x839A6488,0x82580EBF,0x801EB0E6,0x81DCDAD1,0x8493CC54,0x8551A663,0x8717183A,0x86D5720D,
877
+ 0xA9E2D0A0,0xA820BA97,0xAA6604CE,0xABA46EF9,0xAEEB787C,0xAF29124B,0xAD6FAC12,0xACADC625,
878
+ 0xA7F18118,0xA633EB2F,0xA4755576,0xA5B73F41,0xA0F829C4,0xA13A43F3,0xA37CFDAA,0xA2BE979D,
879
+ 0xB5C473D0,0xB40619E7,0xB640A7BE,0xB782CD89,0xB2CDDB0C,0xB30FB13B,0xB1490F62,0xB08B6555,
880
+ 0xBBD72268,0xBA15485F,0xB853F606,0xB9919C31,0xBCDE8AB4,0xBD1CE083,0xBF5A5EDA,0xBE9834ED,
881
+ },
882
+
883
+ {
884
+ 0x00000000,0xB8BC6765,0xAA09C88B,0x12B5AFEE,0x8F629757,0x37DEF032,0x256B5FDC,0x9DD738B9,
885
+ 0xC5B428EF,0x7D084F8A,0x6FBDE064,0xD7018701,0x4AD6BFB8,0xF26AD8DD,0xE0DF7733,0x58631056,
886
+ 0x5019579F,0xE8A530FA,0xFA109F14,0x42ACF871,0xDF7BC0C8,0x67C7A7AD,0x75720843,0xCDCE6F26,
887
+ 0x95AD7F70,0x2D111815,0x3FA4B7FB,0x8718D09E,0x1ACFE827,0xA2738F42,0xB0C620AC,0x087A47C9,
888
+ 0xA032AF3E,0x188EC85B,0x0A3B67B5,0xB28700D0,0x2F503869,0x97EC5F0C,0x8559F0E2,0x3DE59787,
889
+ 0x658687D1,0xDD3AE0B4,0xCF8F4F5A,0x7733283F,0xEAE41086,0x525877E3,0x40EDD80D,0xF851BF68,
890
+ 0xF02BF8A1,0x48979FC4,0x5A22302A,0xE29E574F,0x7F496FF6,0xC7F50893,0xD540A77D,0x6DFCC018,
891
+ 0x359FD04E,0x8D23B72B,0x9F9618C5,0x272A7FA0,0xBAFD4719,0x0241207C,0x10F48F92,0xA848E8F7,
892
+ 0x9B14583D,0x23A83F58,0x311D90B6,0x89A1F7D3,0x1476CF6A,0xACCAA80F,0xBE7F07E1,0x06C36084,
893
+ 0x5EA070D2,0xE61C17B7,0xF4A9B859,0x4C15DF3C,0xD1C2E785,0x697E80E0,0x7BCB2F0E,0xC377486B,
894
+ 0xCB0D0FA2,0x73B168C7,0x6104C729,0xD9B8A04C,0x446F98F5,0xFCD3FF90,0xEE66507E,0x56DA371B,
895
+ 0x0EB9274D,0xB6054028,0xA4B0EFC6,0x1C0C88A3,0x81DBB01A,0x3967D77F,0x2BD27891,0x936E1FF4,
896
+ 0x3B26F703,0x839A9066,0x912F3F88,0x299358ED,0xB4446054,0x0CF80731,0x1E4DA8DF,0xA6F1CFBA,
897
+ 0xFE92DFEC,0x462EB889,0x549B1767,0xEC277002,0x71F048BB,0xC94C2FDE,0xDBF98030,0x6345E755,
898
+ 0x6B3FA09C,0xD383C7F9,0xC1366817,0x798A0F72,0xE45D37CB,0x5CE150AE,0x4E54FF40,0xF6E89825,
899
+ 0xAE8B8873,0x1637EF16,0x048240F8,0xBC3E279D,0x21E91F24,0x99557841,0x8BE0D7AF,0x335CB0CA,
900
+ 0xED59B63B,0x55E5D15E,0x47507EB0,0xFFEC19D5,0x623B216C,0xDA874609,0xC832E9E7,0x708E8E82,
901
+ 0x28ED9ED4,0x9051F9B1,0x82E4565F,0x3A58313A,0xA78F0983,0x1F336EE6,0x0D86C108,0xB53AA66D,
902
+ 0xBD40E1A4,0x05FC86C1,0x1749292F,0xAFF54E4A,0x322276F3,0x8A9E1196,0x982BBE78,0x2097D91D,
903
+ 0x78F4C94B,0xC048AE2E,0xD2FD01C0,0x6A4166A5,0xF7965E1C,0x4F2A3979,0x5D9F9697,0xE523F1F2,
904
+ 0x4D6B1905,0xF5D77E60,0xE762D18E,0x5FDEB6EB,0xC2098E52,0x7AB5E937,0x680046D9,0xD0BC21BC,
905
+ 0x88DF31EA,0x3063568F,0x22D6F961,0x9A6A9E04,0x07BDA6BD,0xBF01C1D8,0xADB46E36,0x15080953,
906
+ 0x1D724E9A,0xA5CE29FF,0xB77B8611,0x0FC7E174,0x9210D9CD,0x2AACBEA8,0x38191146,0x80A57623,
907
+ 0xD8C66675,0x607A0110,0x72CFAEFE,0xCA73C99B,0x57A4F122,0xEF189647,0xFDAD39A9,0x45115ECC,
908
+ 0x764DEE06,0xCEF18963,0xDC44268D,0x64F841E8,0xF92F7951,0x41931E34,0x5326B1DA,0xEB9AD6BF,
909
+ 0xB3F9C6E9,0x0B45A18C,0x19F00E62,0xA14C6907,0x3C9B51BE,0x842736DB,0x96929935,0x2E2EFE50,
910
+ 0x2654B999,0x9EE8DEFC,0x8C5D7112,0x34E11677,0xA9362ECE,0x118A49AB,0x033FE645,0xBB838120,
911
+ 0xE3E09176,0x5B5CF613,0x49E959FD,0xF1553E98,0x6C820621,0xD43E6144,0xC68BCEAA,0x7E37A9CF,
912
+ 0xD67F4138,0x6EC3265D,0x7C7689B3,0xC4CAEED6,0x591DD66F,0xE1A1B10A,0xF3141EE4,0x4BA87981,
913
+ 0x13CB69D7,0xAB770EB2,0xB9C2A15C,0x017EC639,0x9CA9FE80,0x241599E5,0x36A0360B,0x8E1C516E,
914
+ 0x866616A7,0x3EDA71C2,0x2C6FDE2C,0x94D3B949,0x090481F0,0xB1B8E695,0xA30D497B,0x1BB12E1E,
915
+ 0x43D23E48,0xFB6E592D,0xE9DBF6C3,0x516791A6,0xCCB0A91F,0x740CCE7A,0x66B96194,0xDE0506F1,
916
+ }
917
+ #endif // defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_4) || defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_8) || defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_16)
918
+ #if defined (CRC32_USE_LOOKUP_TABLE_SLICING_BY_8) || defined(CRC32_USE_LOOKUP_TABLE_SLICING_BY_16)
919
+ // beyond this point only relevant for Slicing-by-8 and Slicing-by-16
920
+ ,{
921
+ 0x00000000,0x3D6029B0,0x7AC05360,0x47A07AD0,0xF580A6C0,0xC8E08F70,0x8F40F5A0,0xB220DC10,
922
+ 0x30704BC1,0x0D106271,0x4AB018A1,0x77D03111,0xC5F0ED01,0xF890C4B1,0xBF30BE61,0x825097D1,
923
+ 0x60E09782,0x5D80BE32,0x1A20C4E2,0x2740ED52,0x95603142,0xA80018F2,0xEFA06222,0xD2C04B92,
924
+ 0x5090DC43,0x6DF0F5F3,0x2A508F23,0x1730A693,0xA5107A83,0x98705333,0xDFD029E3,0xE2B00053,
925
+ 0xC1C12F04,0xFCA106B4,0xBB017C64,0x866155D4,0x344189C4,0x0921A074,0x4E81DAA4,0x73E1F314,
926
+ 0xF1B164C5,0xCCD14D75,0x8B7137A5,0xB6111E15,0x0431C205,0x3951EBB5,0x7EF19165,0x4391B8D5,
927
+ 0xA121B886,0x9C419136,0xDBE1EBE6,0xE681C256,0x54A11E46,0x69C137F6,0x2E614D26,0x13016496,
928
+ 0x9151F347,0xAC31DAF7,0xEB91A027,0xD6F18997,0x64D15587,0x59B17C37,0x1E1106E7,0x23712F57,
929
+ 0x58F35849,0x659371F9,0x22330B29,0x1F532299,0xAD73FE89,0x9013D739,0xD7B3ADE9,0xEAD38459,
930
+ 0x68831388,0x55E33A38,0x124340E8,0x2F236958,0x9D03B548,0xA0639CF8,0xE7C3E628,0xDAA3CF98,
931
+ 0x3813CFCB,0x0573E67B,0x42D39CAB,0x7FB3B51B,0xCD93690B,0xF0F340BB,0xB7533A6B,0x8A3313DB,
932
+ 0x0863840A,0x3503ADBA,0x72A3D76A,0x4FC3FEDA,0xFDE322CA,0xC0830B7A,0x872371AA,0xBA43581A,
933
+ 0x9932774D,0xA4525EFD,0xE3F2242D,0xDE920D9D,0x6CB2D18D,0x51D2F83D,0x167282ED,0x2B12AB5D,
934
+ 0xA9423C8C,0x9422153C,0xD3826FEC,0xEEE2465C,0x5CC29A4C,0x61A2B3FC,0x2602C92C,0x1B62E09C,
935
+ 0xF9D2E0CF,0xC4B2C97F,0x8312B3AF,0xBE729A1F,0x0C52460F,0x31326FBF,0x7692156F,0x4BF23CDF,
936
+ 0xC9A2AB0E,0xF4C282BE,0xB362F86E,0x8E02D1DE,0x3C220DCE,0x0142247E,0x46E25EAE,0x7B82771E,
937
+ 0xB1E6B092,0x8C869922,0xCB26E3F2,0xF646CA42,0x44661652,0x79063FE2,0x3EA64532,0x03C66C82,
938
+ 0x8196FB53,0xBCF6D2E3,0xFB56A833,0xC6368183,0x74165D93,0x49767423,0x0ED60EF3,0x33B62743,
939
+ 0xD1062710,0xEC660EA0,0xABC67470,0x96A65DC0,0x248681D0,0x19E6A860,0x5E46D2B0,0x6326FB00,
940
+ 0xE1766CD1,0xDC164561,0x9BB63FB1,0xA6D61601,0x14F6CA11,0x2996E3A1,0x6E369971,0x5356B0C1,
941
+ 0x70279F96,0x4D47B626,0x0AE7CCF6,0x3787E546,0x85A73956,0xB8C710E6,0xFF676A36,0xC2074386,
942
+ 0x4057D457,0x7D37FDE7,0x3A978737,0x07F7AE87,0xB5D77297,0x88B75B27,0xCF1721F7,0xF2770847,
943
+ 0x10C70814,0x2DA721A4,0x6A075B74,0x576772C4,0xE547AED4,0xD8278764,0x9F87FDB4,0xA2E7D404,
944
+ 0x20B743D5,0x1DD76A65,0x5A7710B5,0x67173905,0xD537E515,0xE857CCA5,0xAFF7B675,0x92979FC5,
945
+ 0xE915E8DB,0xD475C16B,0x93D5BBBB,0xAEB5920B,0x1C954E1B,0x21F567AB,0x66551D7B,0x5B3534CB,
946
+ 0xD965A31A,0xE4058AAA,0xA3A5F07A,0x9EC5D9CA,0x2CE505DA,0x11852C6A,0x562556BA,0x6B457F0A,
947
+ 0x89F57F59,0xB49556E9,0xF3352C39,0xCE550589,0x7C75D999,0x4115F029,0x06B58AF9,0x3BD5A349,
948
+ 0xB9853498,0x84E51D28,0xC34567F8,0xFE254E48,0x4C059258,0x7165BBE8,0x36C5C138,0x0BA5E888,
949
+ 0x28D4C7DF,0x15B4EE6F,0x521494BF,0x6F74BD0F,0xDD54611F,0xE03448AF,0xA794327F,0x9AF41BCF,
950
+ 0x18A48C1E,0x25C4A5AE,0x6264DF7E,0x5F04F6CE,0xED242ADE,0xD044036E,0x97E479BE,0xAA84500E,
951
+ 0x4834505D,0x755479ED,0x32F4033D,0x0F942A8D,0xBDB4F69D,0x80D4DF2D,0xC774A5FD,0xFA148C4D,
952
+ 0x78441B9C,0x4524322C,0x028448FC,0x3FE4614C,0x8DC4BD5C,0xB0A494EC,0xF704EE3C,0xCA64C78C,
953
+ },
954
+
955
+ {
956
+ 0x00000000,0xCB5CD3A5,0x4DC8A10B,0x869472AE,0x9B914216,0x50CD91B3,0xD659E31D,0x1D0530B8,
957
+ 0xEC53826D,0x270F51C8,0xA19B2366,0x6AC7F0C3,0x77C2C07B,0xBC9E13DE,0x3A0A6170,0xF156B2D5,
958
+ 0x03D6029B,0xC88AD13E,0x4E1EA390,0x85427035,0x9847408D,0x531B9328,0xD58FE186,0x1ED33223,
959
+ 0xEF8580F6,0x24D95353,0xA24D21FD,0x6911F258,0x7414C2E0,0xBF481145,0x39DC63EB,0xF280B04E,
960
+ 0x07AC0536,0xCCF0D693,0x4A64A43D,0x81387798,0x9C3D4720,0x57619485,0xD1F5E62B,0x1AA9358E,
961
+ 0xEBFF875B,0x20A354FE,0xA6372650,0x6D6BF5F5,0x706EC54D,0xBB3216E8,0x3DA66446,0xF6FAB7E3,
962
+ 0x047A07AD,0xCF26D408,0x49B2A6A6,0x82EE7503,0x9FEB45BB,0x54B7961E,0xD223E4B0,0x197F3715,
963
+ 0xE82985C0,0x23755665,0xA5E124CB,0x6EBDF76E,0x73B8C7D6,0xB8E41473,0x3E7066DD,0xF52CB578,
964
+ 0x0F580A6C,0xC404D9C9,0x4290AB67,0x89CC78C2,0x94C9487A,0x5F959BDF,0xD901E971,0x125D3AD4,
965
+ 0xE30B8801,0x28575BA4,0xAEC3290A,0x659FFAAF,0x789ACA17,0xB3C619B2,0x35526B1C,0xFE0EB8B9,
966
+ 0x0C8E08F7,0xC7D2DB52,0x4146A9FC,0x8A1A7A59,0x971F4AE1,0x5C439944,0xDAD7EBEA,0x118B384F,
967
+ 0xE0DD8A9A,0x2B81593F,0xAD152B91,0x6649F834,0x7B4CC88C,0xB0101B29,0x36846987,0xFDD8BA22,
968
+ 0x08F40F5A,0xC3A8DCFF,0x453CAE51,0x8E607DF4,0x93654D4C,0x58399EE9,0xDEADEC47,0x15F13FE2,
969
+ 0xE4A78D37,0x2FFB5E92,0xA96F2C3C,0x6233FF99,0x7F36CF21,0xB46A1C84,0x32FE6E2A,0xF9A2BD8F,
970
+ 0x0B220DC1,0xC07EDE64,0x46EAACCA,0x8DB67F6F,0x90B34FD7,0x5BEF9C72,0xDD7BEEDC,0x16273D79,
971
+ 0xE7718FAC,0x2C2D5C09,0xAAB92EA7,0x61E5FD02,0x7CE0CDBA,0xB7BC1E1F,0x31286CB1,0xFA74BF14,
972
+ 0x1EB014D8,0xD5ECC77D,0x5378B5D3,0x98246676,0x852156CE,0x4E7D856B,0xC8E9F7C5,0x03B52460,
973
+ 0xF2E396B5,0x39BF4510,0xBF2B37BE,0x7477E41B,0x6972D4A3,0xA22E0706,0x24BA75A8,0xEFE6A60D,
974
+ 0x1D661643,0xD63AC5E6,0x50AEB748,0x9BF264ED,0x86F75455,0x4DAB87F0,0xCB3FF55E,0x006326FB,
975
+ 0xF135942E,0x3A69478B,0xBCFD3525,0x77A1E680,0x6AA4D638,0xA1F8059D,0x276C7733,0xEC30A496,
976
+ 0x191C11EE,0xD240C24B,0x54D4B0E5,0x9F886340,0x828D53F8,0x49D1805D,0xCF45F2F3,0x04192156,
977
+ 0xF54F9383,0x3E134026,0xB8873288,0x73DBE12D,0x6EDED195,0xA5820230,0x2316709E,0xE84AA33B,
978
+ 0x1ACA1375,0xD196C0D0,0x5702B27E,0x9C5E61DB,0x815B5163,0x4A0782C6,0xCC93F068,0x07CF23CD,
979
+ 0xF6999118,0x3DC542BD,0xBB513013,0x700DE3B6,0x6D08D30E,0xA65400AB,0x20C07205,0xEB9CA1A0,
980
+ 0x11E81EB4,0xDAB4CD11,0x5C20BFBF,0x977C6C1A,0x8A795CA2,0x41258F07,0xC7B1FDA9,0x0CED2E0C,
981
+ 0xFDBB9CD9,0x36E74F7C,0xB0733DD2,0x7B2FEE77,0x662ADECF,0xAD760D6A,0x2BE27FC4,0xE0BEAC61,
982
+ 0x123E1C2F,0xD962CF8A,0x5FF6BD24,0x94AA6E81,0x89AF5E39,0x42F38D9C,0xC467FF32,0x0F3B2C97,
983
+ 0xFE6D9E42,0x35314DE7,0xB3A53F49,0x78F9ECEC,0x65FCDC54,0xAEA00FF1,0x28347D5F,0xE368AEFA,
984
+ 0x16441B82,0xDD18C827,0x5B8CBA89,0x90D0692C,0x8DD55994,0x46898A31,0xC01DF89F,0x0B412B3A,
985
+ 0xFA1799EF,0x314B4A4A,0xB7DF38E4,0x7C83EB41,0x6186DBF9,0xAADA085C,0x2C4E7AF2,0xE712A957,
986
+ 0x15921919,0xDECECABC,0x585AB812,0x93066BB7,0x8E035B0F,0x455F88AA,0xC3CBFA04,0x089729A1,
987
+ 0xF9C19B74,0x329D48D1,0xB4093A7F,0x7F55E9DA,0x6250D962,0xA90C0AC7,0x2F987869,0xE4C4ABCC,
988
+ },
989
+
990
+ {
991
+ 0x00000000,0xA6770BB4,0x979F1129,0x31E81A9D,0xF44F2413,0x52382FA7,0x63D0353A,0xC5A73E8E,
992
+ 0x33EF4E67,0x959845D3,0xA4705F4E,0x020754FA,0xC7A06A74,0x61D761C0,0x503F7B5D,0xF64870E9,
993
+ 0x67DE9CCE,0xC1A9977A,0xF0418DE7,0x56368653,0x9391B8DD,0x35E6B369,0x040EA9F4,0xA279A240,
994
+ 0x5431D2A9,0xF246D91D,0xC3AEC380,0x65D9C834,0xA07EF6BA,0x0609FD0E,0x37E1E793,0x9196EC27,
995
+ 0xCFBD399C,0x69CA3228,0x582228B5,0xFE552301,0x3BF21D8F,0x9D85163B,0xAC6D0CA6,0x0A1A0712,
996
+ 0xFC5277FB,0x5A257C4F,0x6BCD66D2,0xCDBA6D66,0x081D53E8,0xAE6A585C,0x9F8242C1,0x39F54975,
997
+ 0xA863A552,0x0E14AEE6,0x3FFCB47B,0x998BBFCF,0x5C2C8141,0xFA5B8AF5,0xCBB39068,0x6DC49BDC,
998
+ 0x9B8CEB35,0x3DFBE081,0x0C13FA1C,0xAA64F1A8,0x6FC3CF26,0xC9B4C492,0xF85CDE0F,0x5E2BD5BB,
999
+ 0x440B7579,0xE27C7ECD,0xD3946450,0x75E36FE4,0xB044516A,0x16335ADE,0x27DB4043,0x81AC4BF7,
1000
+ 0x77E43B1E,0xD19330AA,0xE07B2A37,0x460C2183,0x83AB1F0D,0x25DC14B9,0x14340E24,0xB2430590,
1001
+ 0x23D5E9B7,0x85A2E203,0xB44AF89E,0x123DF32A,0xD79ACDA4,0x71EDC610,0x4005DC8D,0xE672D739,
1002
+ 0x103AA7D0,0xB64DAC64,0x87A5B6F9,0x21D2BD4D,0xE47583C3,0x42028877,0x73EA92EA,0xD59D995E,
1003
+ 0x8BB64CE5,0x2DC14751,0x1C295DCC,0xBA5E5678,0x7FF968F6,0xD98E6342,0xE86679DF,0x4E11726B,
1004
+ 0xB8590282,0x1E2E0936,0x2FC613AB,0x89B1181F,0x4C162691,0xEA612D25,0xDB8937B8,0x7DFE3C0C,
1005
+ 0xEC68D02B,0x4A1FDB9F,0x7BF7C102,0xDD80CAB6,0x1827F438,0xBE50FF8C,0x8FB8E511,0x29CFEEA5,
1006
+ 0xDF879E4C,0x79F095F8,0x48188F65,0xEE6F84D1,0x2BC8BA5F,0x8DBFB1EB,0xBC57AB76,0x1A20A0C2,
1007
+ 0x8816EAF2,0x2E61E146,0x1F89FBDB,0xB9FEF06F,0x7C59CEE1,0xDA2EC555,0xEBC6DFC8,0x4DB1D47C,
1008
+ 0xBBF9A495,0x1D8EAF21,0x2C66B5BC,0x8A11BE08,0x4FB68086,0xE9C18B32,0xD82991AF,0x7E5E9A1B,
1009
+ 0xEFC8763C,0x49BF7D88,0x78576715,0xDE206CA1,0x1B87522F,0xBDF0599B,0x8C184306,0x2A6F48B2,
1010
+ 0xDC27385B,0x7A5033EF,0x4BB82972,0xEDCF22C6,0x28681C48,0x8E1F17FC,0xBFF70D61,0x198006D5,
1011
+ 0x47ABD36E,0xE1DCD8DA,0xD034C247,0x7643C9F3,0xB3E4F77D,0x1593FCC9,0x247BE654,0x820CEDE0,
1012
+ 0x74449D09,0xD23396BD,0xE3DB8C20,0x45AC8794,0x800BB91A,0x267CB2AE,0x1794A833,0xB1E3A387,
1013
+ 0x20754FA0,0x86024414,0xB7EA5E89,0x119D553D,0xD43A6BB3,0x724D6007,0x43A57A9A,0xE5D2712E,
1014
+ 0x139A01C7,0xB5ED0A73,0x840510EE,0x22721B5A,0xE7D525D4,0x41A22E60,0x704A34FD,0xD63D3F49,
1015
+ 0xCC1D9F8B,0x6A6A943F,0x5B828EA2,0xFDF58516,0x3852BB98,0x9E25B02C,0xAFCDAAB1,0x09BAA105,
1016
+ 0xFFF2D1EC,0x5985DA58,0x686DC0C5,0xCE1ACB71,0x0BBDF5FF,0xADCAFE4B,0x9C22E4D6,0x3A55EF62,
1017
+ 0xABC30345,0x0DB408F1,0x3C5C126C,0x9A2B19D8,0x5F8C2756,0xF9FB2CE2,0xC813367F,0x6E643DCB,
1018
+ 0x982C4D22,0x3E5B4696,0x0FB35C0B,0xA9C457BF,0x6C636931,0xCA146285,0xFBFC7818,0x5D8B73AC,
1019
+ 0x03A0A617,0xA5D7ADA3,0x943FB73E,0x3248BC8A,0xF7EF8204,0x519889B0,0x6070932D,0xC6079899,
1020
+ 0x304FE870,0x9638E3C4,0xA7D0F959,0x01A7F2ED,0xC400CC63,0x6277C7D7,0x539FDD4A,0xF5E8D6FE,
1021
+ 0x647E3AD9,0xC209316D,0xF3E12BF0,0x55962044,0x90311ECA,0x3646157E,0x07AE0FE3,0xA1D90457,
1022
+ 0x579174BE,0xF1E67F0A,0xC00E6597,0x66796E23,0xA3DE50AD,0x05A95B19,0x34414184,0x92364A30,
1023
+ },
1024
+
1025
+ {
1026
+ 0x00000000,0xCCAA009E,0x4225077D,0x8E8F07E3,0x844A0EFA,0x48E00E64,0xC66F0987,0x0AC50919,
1027
+ 0xD3E51BB5,0x1F4F1B2B,0x91C01CC8,0x5D6A1C56,0x57AF154F,0x9B0515D1,0x158A1232,0xD92012AC,
1028
+ 0x7CBB312B,0xB01131B5,0x3E9E3656,0xF23436C8,0xF8F13FD1,0x345B3F4F,0xBAD438AC,0x767E3832,
1029
+ 0xAF5E2A9E,0x63F42A00,0xED7B2DE3,0x21D12D7D,0x2B142464,0xE7BE24FA,0x69312319,0xA59B2387,
1030
+ 0xF9766256,0x35DC62C8,0xBB53652B,0x77F965B5,0x7D3C6CAC,0xB1966C32,0x3F196BD1,0xF3B36B4F,
1031
+ 0x2A9379E3,0xE639797D,0x68B67E9E,0xA41C7E00,0xAED97719,0x62737787,0xECFC7064,0x205670FA,
1032
+ 0x85CD537D,0x496753E3,0xC7E85400,0x0B42549E,0x01875D87,0xCD2D5D19,0x43A25AFA,0x8F085A64,
1033
+ 0x562848C8,0x9A824856,0x140D4FB5,0xD8A74F2B,0xD2624632,0x1EC846AC,0x9047414F,0x5CED41D1,
1034
+ 0x299DC2ED,0xE537C273,0x6BB8C590,0xA712C50E,0xADD7CC17,0x617DCC89,0xEFF2CB6A,0x2358CBF4,
1035
+ 0xFA78D958,0x36D2D9C6,0xB85DDE25,0x74F7DEBB,0x7E32D7A2,0xB298D73C,0x3C17D0DF,0xF0BDD041,
1036
+ 0x5526F3C6,0x998CF358,0x1703F4BB,0xDBA9F425,0xD16CFD3C,0x1DC6FDA2,0x9349FA41,0x5FE3FADF,
1037
+ 0x86C3E873,0x4A69E8ED,0xC4E6EF0E,0x084CEF90,0x0289E689,0xCE23E617,0x40ACE1F4,0x8C06E16A,
1038
+ 0xD0EBA0BB,0x1C41A025,0x92CEA7C6,0x5E64A758,0x54A1AE41,0x980BAEDF,0x1684A93C,0xDA2EA9A2,
1039
+ 0x030EBB0E,0xCFA4BB90,0x412BBC73,0x8D81BCED,0x8744B5F4,0x4BEEB56A,0xC561B289,0x09CBB217,
1040
+ 0xAC509190,0x60FA910E,0xEE7596ED,0x22DF9673,0x281A9F6A,0xE4B09FF4,0x6A3F9817,0xA6959889,
1041
+ 0x7FB58A25,0xB31F8ABB,0x3D908D58,0xF13A8DC6,0xFBFF84DF,0x37558441,0xB9DA83A2,0x7570833C,
1042
+ 0x533B85DA,0x9F918544,0x111E82A7,0xDDB48239,0xD7718B20,0x1BDB8BBE,0x95548C5D,0x59FE8CC3,
1043
+ 0x80DE9E6F,0x4C749EF1,0xC2FB9912,0x0E51998C,0x04949095,0xC83E900B,0x46B197E8,0x8A1B9776,
1044
+ 0x2F80B4F1,0xE32AB46F,0x6DA5B38C,0xA10FB312,0xABCABA0B,0x6760BA95,0xE9EFBD76,0x2545BDE8,
1045
+ 0xFC65AF44,0x30CFAFDA,0xBE40A839,0x72EAA8A7,0x782FA1BE,0xB485A120,0x3A0AA6C3,0xF6A0A65D,
1046
+ 0xAA4DE78C,0x66E7E712,0xE868E0F1,0x24C2E06F,0x2E07E976,0xE2ADE9E8,0x6C22EE0B,0xA088EE95,
1047
+ 0x79A8FC39,0xB502FCA7,0x3B8DFB44,0xF727FBDA,0xFDE2F2C3,0x3148F25D,0xBFC7F5BE,0x736DF520,
1048
+ 0xD6F6D6A7,0x1A5CD639,0x94D3D1DA,0x5879D144,0x52BCD85D,0x9E16D8C3,0x1099DF20,0xDC33DFBE,
1049
+ 0x0513CD12,0xC9B9CD8C,0x4736CA6F,0x8B9CCAF1,0x8159C3E8,0x4DF3C376,0xC37CC495,0x0FD6C40B,
1050
+ 0x7AA64737,0xB60C47A9,0x3883404A,0xF42940D4,0xFEEC49CD,0x32464953,0xBCC94EB0,0x70634E2E,
1051
+ 0xA9435C82,0x65E95C1C,0xEB665BFF,0x27CC5B61,0x2D095278,0xE1A352E6,0x6F2C5505,0xA386559B,
1052
+ 0x061D761C,0xCAB77682,0x44387161,0x889271FF,0x825778E6,0x4EFD7878,0xC0727F9B,0x0CD87F05,
1053
+ 0xD5F86DA9,0x19526D37,0x97DD6AD4,0x5B776A4A,0x51B26353,0x9D1863CD,0x1397642E,0xDF3D64B0,
1054
+ 0x83D02561,0x4F7A25FF,0xC1F5221C,0x0D5F2282,0x079A2B9B,0xCB302B05,0x45BF2CE6,0x89152C78,
1055
+ 0x50353ED4,0x9C9F3E4A,0x121039A9,0xDEBA3937,0xD47F302E,0x18D530B0,0x965A3753,0x5AF037CD,
1056
+ 0xFF6B144A,0x33C114D4,0xBD4E1337,0x71E413A9,0x7B211AB0,0xB78B1A2E,0x39041DCD,0xF5AE1D53,
1057
+ 0x2C8E0FFF,0xE0240F61,0x6EAB0882,0xA201081C,0xA8C40105,0x646E019B,0xEAE10678,0x264B06E6,
1058
+ }
1059
+ #endif // CRC32_USE_LOOKUP_TABLE_SLICING_BY_8 || CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
1060
+ #ifdef CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
1061
+ // beyond this point only relevant for Slicing-by-16
1062
+ ,{
1063
+ 0x00000000,0x177B1443,0x2EF62886,0x398D3CC5,0x5DEC510C,0x4A97454F,0x731A798A,0x64616DC9,
1064
+ 0xBBD8A218,0xACA3B65B,0x952E8A9E,0x82559EDD,0xE634F314,0xF14FE757,0xC8C2DB92,0xDFB9CFD1,
1065
+ 0xACC04271,0xBBBB5632,0x82366AF7,0x954D7EB4,0xF12C137D,0xE657073E,0xDFDA3BFB,0xC8A12FB8,
1066
+ 0x1718E069,0x0063F42A,0x39EEC8EF,0x2E95DCAC,0x4AF4B165,0x5D8FA526,0x640299E3,0x73798DA0,
1067
+ 0x82F182A3,0x958A96E0,0xAC07AA25,0xBB7CBE66,0xDF1DD3AF,0xC866C7EC,0xF1EBFB29,0xE690EF6A,
1068
+ 0x392920BB,0x2E5234F8,0x17DF083D,0x00A41C7E,0x64C571B7,0x73BE65F4,0x4A335931,0x5D484D72,
1069
+ 0x2E31C0D2,0x394AD491,0x00C7E854,0x17BCFC17,0x73DD91DE,0x64A6859D,0x5D2BB958,0x4A50AD1B,
1070
+ 0x95E962CA,0x82927689,0xBB1F4A4C,0xAC645E0F,0xC80533C6,0xDF7E2785,0xE6F31B40,0xF1880F03,
1071
+ 0xDE920307,0xC9E91744,0xF0642B81,0xE71F3FC2,0x837E520B,0x94054648,0xAD887A8D,0xBAF36ECE,
1072
+ 0x654AA11F,0x7231B55C,0x4BBC8999,0x5CC79DDA,0x38A6F013,0x2FDDE450,0x1650D895,0x012BCCD6,
1073
+ 0x72524176,0x65295535,0x5CA469F0,0x4BDF7DB3,0x2FBE107A,0x38C50439,0x014838FC,0x16332CBF,
1074
+ 0xC98AE36E,0xDEF1F72D,0xE77CCBE8,0xF007DFAB,0x9466B262,0x831DA621,0xBA909AE4,0xADEB8EA7,
1075
+ 0x5C6381A4,0x4B1895E7,0x7295A922,0x65EEBD61,0x018FD0A8,0x16F4C4EB,0x2F79F82E,0x3802EC6D,
1076
+ 0xE7BB23BC,0xF0C037FF,0xC94D0B3A,0xDE361F79,0xBA5772B0,0xAD2C66F3,0x94A15A36,0x83DA4E75,
1077
+ 0xF0A3C3D5,0xE7D8D796,0xDE55EB53,0xC92EFF10,0xAD4F92D9,0xBA34869A,0x83B9BA5F,0x94C2AE1C,
1078
+ 0x4B7B61CD,0x5C00758E,0x658D494B,0x72F65D08,0x169730C1,0x01EC2482,0x38611847,0x2F1A0C04,
1079
+ 0x6655004F,0x712E140C,0x48A328C9,0x5FD83C8A,0x3BB95143,0x2CC24500,0x154F79C5,0x02346D86,
1080
+ 0xDD8DA257,0xCAF6B614,0xF37B8AD1,0xE4009E92,0x8061F35B,0x971AE718,0xAE97DBDD,0xB9ECCF9E,
1081
+ 0xCA95423E,0xDDEE567D,0xE4636AB8,0xF3187EFB,0x97791332,0x80020771,0xB98F3BB4,0xAEF42FF7,
1082
+ 0x714DE026,0x6636F465,0x5FBBC8A0,0x48C0DCE3,0x2CA1B12A,0x3BDAA569,0x025799AC,0x152C8DEF,
1083
+ 0xE4A482EC,0xF3DF96AF,0xCA52AA6A,0xDD29BE29,0xB948D3E0,0xAE33C7A3,0x97BEFB66,0x80C5EF25,
1084
+ 0x5F7C20F4,0x480734B7,0x718A0872,0x66F11C31,0x029071F8,0x15EB65BB,0x2C66597E,0x3B1D4D3D,
1085
+ 0x4864C09D,0x5F1FD4DE,0x6692E81B,0x71E9FC58,0x15889191,0x02F385D2,0x3B7EB917,0x2C05AD54,
1086
+ 0xF3BC6285,0xE4C776C6,0xDD4A4A03,0xCA315E40,0xAE503389,0xB92B27CA,0x80A61B0F,0x97DD0F4C,
1087
+ 0xB8C70348,0xAFBC170B,0x96312BCE,0x814A3F8D,0xE52B5244,0xF2504607,0xCBDD7AC2,0xDCA66E81,
1088
+ 0x031FA150,0x1464B513,0x2DE989D6,0x3A929D95,0x5EF3F05C,0x4988E41F,0x7005D8DA,0x677ECC99,
1089
+ 0x14074139,0x037C557A,0x3AF169BF,0x2D8A7DFC,0x49EB1035,0x5E900476,0x671D38B3,0x70662CF0,
1090
+ 0xAFDFE321,0xB8A4F762,0x8129CBA7,0x9652DFE4,0xF233B22D,0xE548A66E,0xDCC59AAB,0xCBBE8EE8,
1091
+ 0x3A3681EB,0x2D4D95A8,0x14C0A96D,0x03BBBD2E,0x67DAD0E7,0x70A1C4A4,0x492CF861,0x5E57EC22,
1092
+ 0x81EE23F3,0x969537B0,0xAF180B75,0xB8631F36,0xDC0272FF,0xCB7966BC,0xF2F45A79,0xE58F4E3A,
1093
+ 0x96F6C39A,0x818DD7D9,0xB800EB1C,0xAF7BFF5F,0xCB1A9296,0xDC6186D5,0xE5ECBA10,0xF297AE53,
1094
+ 0x2D2E6182,0x3A5575C1,0x03D84904,0x14A35D47,0x70C2308E,0x67B924CD,0x5E341808,0x494F0C4B,
1095
+ },
1096
+
1097
+ {
1098
+ 0x00000000,0xEFC26B3E,0x04F5D03D,0xEB37BB03,0x09EBA07A,0xE629CB44,0x0D1E7047,0xE2DC1B79,
1099
+ 0x13D740F4,0xFC152BCA,0x172290C9,0xF8E0FBF7,0x1A3CE08E,0xF5FE8BB0,0x1EC930B3,0xF10B5B8D,
1100
+ 0x27AE81E8,0xC86CEAD6,0x235B51D5,0xCC993AEB,0x2E452192,0xC1874AAC,0x2AB0F1AF,0xC5729A91,
1101
+ 0x3479C11C,0xDBBBAA22,0x308C1121,0xDF4E7A1F,0x3D926166,0xD2500A58,0x3967B15B,0xD6A5DA65,
1102
+ 0x4F5D03D0,0xA09F68EE,0x4BA8D3ED,0xA46AB8D3,0x46B6A3AA,0xA974C894,0x42437397,0xAD8118A9,
1103
+ 0x5C8A4324,0xB348281A,0x587F9319,0xB7BDF827,0x5561E35E,0xBAA38860,0x51943363,0xBE56585D,
1104
+ 0x68F38238,0x8731E906,0x6C065205,0x83C4393B,0x61182242,0x8EDA497C,0x65EDF27F,0x8A2F9941,
1105
+ 0x7B24C2CC,0x94E6A9F2,0x7FD112F1,0x901379CF,0x72CF62B6,0x9D0D0988,0x763AB28B,0x99F8D9B5,
1106
+ 0x9EBA07A0,0x71786C9E,0x9A4FD79D,0x758DBCA3,0x9751A7DA,0x7893CCE4,0x93A477E7,0x7C661CD9,
1107
+ 0x8D6D4754,0x62AF2C6A,0x89989769,0x665AFC57,0x8486E72E,0x6B448C10,0x80733713,0x6FB15C2D,
1108
+ 0xB9148648,0x56D6ED76,0xBDE15675,0x52233D4B,0xB0FF2632,0x5F3D4D0C,0xB40AF60F,0x5BC89D31,
1109
+ 0xAAC3C6BC,0x4501AD82,0xAE361681,0x41F47DBF,0xA32866C6,0x4CEA0DF8,0xA7DDB6FB,0x481FDDC5,
1110
+ 0xD1E70470,0x3E256F4E,0xD512D44D,0x3AD0BF73,0xD80CA40A,0x37CECF34,0xDCF97437,0x333B1F09,
1111
+ 0xC2304484,0x2DF22FBA,0xC6C594B9,0x2907FF87,0xCBDBE4FE,0x24198FC0,0xCF2E34C3,0x20EC5FFD,
1112
+ 0xF6498598,0x198BEEA6,0xF2BC55A5,0x1D7E3E9B,0xFFA225E2,0x10604EDC,0xFB57F5DF,0x14959EE1,
1113
+ 0xE59EC56C,0x0A5CAE52,0xE16B1551,0x0EA97E6F,0xEC756516,0x03B70E28,0xE880B52B,0x0742DE15,
1114
+ 0xE6050901,0x09C7623F,0xE2F0D93C,0x0D32B202,0xEFEEA97B,0x002CC245,0xEB1B7946,0x04D91278,
1115
+ 0xF5D249F5,0x1A1022CB,0xF12799C8,0x1EE5F2F6,0xFC39E98F,0x13FB82B1,0xF8CC39B2,0x170E528C,
1116
+ 0xC1AB88E9,0x2E69E3D7,0xC55E58D4,0x2A9C33EA,0xC8402893,0x278243AD,0xCCB5F8AE,0x23779390,
1117
+ 0xD27CC81D,0x3DBEA323,0xD6891820,0x394B731E,0xDB976867,0x34550359,0xDF62B85A,0x30A0D364,
1118
+ 0xA9580AD1,0x469A61EF,0xADADDAEC,0x426FB1D2,0xA0B3AAAB,0x4F71C195,0xA4467A96,0x4B8411A8,
1119
+ 0xBA8F4A25,0x554D211B,0xBE7A9A18,0x51B8F126,0xB364EA5F,0x5CA68161,0xB7913A62,0x5853515C,
1120
+ 0x8EF68B39,0x6134E007,0x8A035B04,0x65C1303A,0x871D2B43,0x68DF407D,0x83E8FB7E,0x6C2A9040,
1121
+ 0x9D21CBCD,0x72E3A0F3,0x99D41BF0,0x761670CE,0x94CA6BB7,0x7B080089,0x903FBB8A,0x7FFDD0B4,
1122
+ 0x78BF0EA1,0x977D659F,0x7C4ADE9C,0x9388B5A2,0x7154AEDB,0x9E96C5E5,0x75A17EE6,0x9A6315D8,
1123
+ 0x6B684E55,0x84AA256B,0x6F9D9E68,0x805FF556,0x6283EE2F,0x8D418511,0x66763E12,0x89B4552C,
1124
+ 0x5F118F49,0xB0D3E477,0x5BE45F74,0xB426344A,0x56FA2F33,0xB938440D,0x520FFF0E,0xBDCD9430,
1125
+ 0x4CC6CFBD,0xA304A483,0x48331F80,0xA7F174BE,0x452D6FC7,0xAAEF04F9,0x41D8BFFA,0xAE1AD4C4,
1126
+ 0x37E20D71,0xD820664F,0x3317DD4C,0xDCD5B672,0x3E09AD0B,0xD1CBC635,0x3AFC7D36,0xD53E1608,
1127
+ 0x24354D85,0xCBF726BB,0x20C09DB8,0xCF02F686,0x2DDEEDFF,0xC21C86C1,0x292B3DC2,0xC6E956FC,
1128
+ 0x104C8C99,0xFF8EE7A7,0x14B95CA4,0xFB7B379A,0x19A72CE3,0xF66547DD,0x1D52FCDE,0xF29097E0,
1129
+ 0x039BCC6D,0xEC59A753,0x076E1C50,0xE8AC776E,0x0A706C17,0xE5B20729,0x0E85BC2A,0xE147D714,
1130
+ },
1131
+
1132
+ {
1133
+ 0x00000000,0xC18EDFC0,0x586CB9C1,0x99E26601,0xB0D97382,0x7157AC42,0xE8B5CA43,0x293B1583,
1134
+ 0xBAC3E145,0x7B4D3E85,0xE2AF5884,0x23218744,0x0A1A92C7,0xCB944D07,0x52762B06,0x93F8F4C6,
1135
+ 0xAEF6C4CB,0x6F781B0B,0xF69A7D0A,0x3714A2CA,0x1E2FB749,0xDFA16889,0x46430E88,0x87CDD148,
1136
+ 0x1435258E,0xD5BBFA4E,0x4C599C4F,0x8DD7438F,0xA4EC560C,0x656289CC,0xFC80EFCD,0x3D0E300D,
1137
+ 0x869C8FD7,0x47125017,0xDEF03616,0x1F7EE9D6,0x3645FC55,0xF7CB2395,0x6E294594,0xAFA79A54,
1138
+ 0x3C5F6E92,0xFDD1B152,0x6433D753,0xA5BD0893,0x8C861D10,0x4D08C2D0,0xD4EAA4D1,0x15647B11,
1139
+ 0x286A4B1C,0xE9E494DC,0x7006F2DD,0xB1882D1D,0x98B3389E,0x593DE75E,0xC0DF815F,0x01515E9F,
1140
+ 0x92A9AA59,0x53277599,0xCAC51398,0x0B4BCC58,0x2270D9DB,0xE3FE061B,0x7A1C601A,0xBB92BFDA,
1141
+ 0xD64819EF,0x17C6C62F,0x8E24A02E,0x4FAA7FEE,0x66916A6D,0xA71FB5AD,0x3EFDD3AC,0xFF730C6C,
1142
+ 0x6C8BF8AA,0xAD05276A,0x34E7416B,0xF5699EAB,0xDC528B28,0x1DDC54E8,0x843E32E9,0x45B0ED29,
1143
+ 0x78BEDD24,0xB93002E4,0x20D264E5,0xE15CBB25,0xC867AEA6,0x09E97166,0x900B1767,0x5185C8A7,
1144
+ 0xC27D3C61,0x03F3E3A1,0x9A1185A0,0x5B9F5A60,0x72A44FE3,0xB32A9023,0x2AC8F622,0xEB4629E2,
1145
+ 0x50D49638,0x915A49F8,0x08B82FF9,0xC936F039,0xE00DE5BA,0x21833A7A,0xB8615C7B,0x79EF83BB,
1146
+ 0xEA17777D,0x2B99A8BD,0xB27BCEBC,0x73F5117C,0x5ACE04FF,0x9B40DB3F,0x02A2BD3E,0xC32C62FE,
1147
+ 0xFE2252F3,0x3FAC8D33,0xA64EEB32,0x67C034F2,0x4EFB2171,0x8F75FEB1,0x169798B0,0xD7194770,
1148
+ 0x44E1B3B6,0x856F6C76,0x1C8D0A77,0xDD03D5B7,0xF438C034,0x35B61FF4,0xAC5479F5,0x6DDAA635,
1149
+ 0x77E1359F,0xB66FEA5F,0x2F8D8C5E,0xEE03539E,0xC738461D,0x06B699DD,0x9F54FFDC,0x5EDA201C,
1150
+ 0xCD22D4DA,0x0CAC0B1A,0x954E6D1B,0x54C0B2DB,0x7DFBA758,0xBC757898,0x25971E99,0xE419C159,
1151
+ 0xD917F154,0x18992E94,0x817B4895,0x40F59755,0x69CE82D6,0xA8405D16,0x31A23B17,0xF02CE4D7,
1152
+ 0x63D41011,0xA25ACFD1,0x3BB8A9D0,0xFA367610,0xD30D6393,0x1283BC53,0x8B61DA52,0x4AEF0592,
1153
+ 0xF17DBA48,0x30F36588,0xA9110389,0x689FDC49,0x41A4C9CA,0x802A160A,0x19C8700B,0xD846AFCB,
1154
+ 0x4BBE5B0D,0x8A3084CD,0x13D2E2CC,0xD25C3D0C,0xFB67288F,0x3AE9F74F,0xA30B914E,0x62854E8E,
1155
+ 0x5F8B7E83,0x9E05A143,0x07E7C742,0xC6691882,0xEF520D01,0x2EDCD2C1,0xB73EB4C0,0x76B06B00,
1156
+ 0xE5489FC6,0x24C64006,0xBD242607,0x7CAAF9C7,0x5591EC44,0x941F3384,0x0DFD5585,0xCC738A45,
1157
+ 0xA1A92C70,0x6027F3B0,0xF9C595B1,0x384B4A71,0x11705FF2,0xD0FE8032,0x491CE633,0x889239F3,
1158
+ 0x1B6ACD35,0xDAE412F5,0x430674F4,0x8288AB34,0xABB3BEB7,0x6A3D6177,0xF3DF0776,0x3251D8B6,
1159
+ 0x0F5FE8BB,0xCED1377B,0x5733517A,0x96BD8EBA,0xBF869B39,0x7E0844F9,0xE7EA22F8,0x2664FD38,
1160
+ 0xB59C09FE,0x7412D63E,0xEDF0B03F,0x2C7E6FFF,0x05457A7C,0xC4CBA5BC,0x5D29C3BD,0x9CA71C7D,
1161
+ 0x2735A3A7,0xE6BB7C67,0x7F591A66,0xBED7C5A6,0x97ECD025,0x56620FE5,0xCF8069E4,0x0E0EB624,
1162
+ 0x9DF642E2,0x5C789D22,0xC59AFB23,0x041424E3,0x2D2F3160,0xECA1EEA0,0x754388A1,0xB4CD5761,
1163
+ 0x89C3676C,0x484DB8AC,0xD1AFDEAD,0x1021016D,0x391A14EE,0xF894CB2E,0x6176AD2F,0xA0F872EF,
1164
+ 0x33008629,0xF28E59E9,0x6B6C3FE8,0xAAE2E028,0x83D9F5AB,0x42572A6B,0xDBB54C6A,0x1A3B93AA,
1165
+ },
1166
+
1167
+ {
1168
+ 0x00000000,0x9BA54C6F,0xEC3B9E9F,0x779ED2F0,0x03063B7F,0x98A37710,0xEF3DA5E0,0x7498E98F,
1169
+ 0x060C76FE,0x9DA93A91,0xEA37E861,0x7192A40E,0x050A4D81,0x9EAF01EE,0xE931D31E,0x72949F71,
1170
+ 0x0C18EDFC,0x97BDA193,0xE0237363,0x7B863F0C,0x0F1ED683,0x94BB9AEC,0xE325481C,0x78800473,
1171
+ 0x0A149B02,0x91B1D76D,0xE62F059D,0x7D8A49F2,0x0912A07D,0x92B7EC12,0xE5293EE2,0x7E8C728D,
1172
+ 0x1831DBF8,0x83949797,0xF40A4567,0x6FAF0908,0x1B37E087,0x8092ACE8,0xF70C7E18,0x6CA93277,
1173
+ 0x1E3DAD06,0x8598E169,0xF2063399,0x69A37FF6,0x1D3B9679,0x869EDA16,0xF10008E6,0x6AA54489,
1174
+ 0x14293604,0x8F8C7A6B,0xF812A89B,0x63B7E4F4,0x172F0D7B,0x8C8A4114,0xFB1493E4,0x60B1DF8B,
1175
+ 0x122540FA,0x89800C95,0xFE1EDE65,0x65BB920A,0x11237B85,0x8A8637EA,0xFD18E51A,0x66BDA975,
1176
+ 0x3063B7F0,0xABC6FB9F,0xDC58296F,0x47FD6500,0x33658C8F,0xA8C0C0E0,0xDF5E1210,0x44FB5E7F,
1177
+ 0x366FC10E,0xADCA8D61,0xDA545F91,0x41F113FE,0x3569FA71,0xAECCB61E,0xD95264EE,0x42F72881,
1178
+ 0x3C7B5A0C,0xA7DE1663,0xD040C493,0x4BE588FC,0x3F7D6173,0xA4D82D1C,0xD346FFEC,0x48E3B383,
1179
+ 0x3A772CF2,0xA1D2609D,0xD64CB26D,0x4DE9FE02,0x3971178D,0xA2D45BE2,0xD54A8912,0x4EEFC57D,
1180
+ 0x28526C08,0xB3F72067,0xC469F297,0x5FCCBEF8,0x2B545777,0xB0F11B18,0xC76FC9E8,0x5CCA8587,
1181
+ 0x2E5E1AF6,0xB5FB5699,0xC2658469,0x59C0C806,0x2D582189,0xB6FD6DE6,0xC163BF16,0x5AC6F379,
1182
+ 0x244A81F4,0xBFEFCD9B,0xC8711F6B,0x53D45304,0x274CBA8B,0xBCE9F6E4,0xCB772414,0x50D2687B,
1183
+ 0x2246F70A,0xB9E3BB65,0xCE7D6995,0x55D825FA,0x2140CC75,0xBAE5801A,0xCD7B52EA,0x56DE1E85,
1184
+ 0x60C76FE0,0xFB62238F,0x8CFCF17F,0x1759BD10,0x63C1549F,0xF86418F0,0x8FFACA00,0x145F866F,
1185
+ 0x66CB191E,0xFD6E5571,0x8AF08781,0x1155CBEE,0x65CD2261,0xFE686E0E,0x89F6BCFE,0x1253F091,
1186
+ 0x6CDF821C,0xF77ACE73,0x80E41C83,0x1B4150EC,0x6FD9B963,0xF47CF50C,0x83E227FC,0x18476B93,
1187
+ 0x6AD3F4E2,0xF176B88D,0x86E86A7D,0x1D4D2612,0x69D5CF9D,0xF27083F2,0x85EE5102,0x1E4B1D6D,
1188
+ 0x78F6B418,0xE353F877,0x94CD2A87,0x0F6866E8,0x7BF08F67,0xE055C308,0x97CB11F8,0x0C6E5D97,
1189
+ 0x7EFAC2E6,0xE55F8E89,0x92C15C79,0x09641016,0x7DFCF999,0xE659B5F6,0x91C76706,0x0A622B69,
1190
+ 0x74EE59E4,0xEF4B158B,0x98D5C77B,0x03708B14,0x77E8629B,0xEC4D2EF4,0x9BD3FC04,0x0076B06B,
1191
+ 0x72E22F1A,0xE9476375,0x9ED9B185,0x057CFDEA,0x71E41465,0xEA41580A,0x9DDF8AFA,0x067AC695,
1192
+ 0x50A4D810,0xCB01947F,0xBC9F468F,0x273A0AE0,0x53A2E36F,0xC807AF00,0xBF997DF0,0x243C319F,
1193
+ 0x56A8AEEE,0xCD0DE281,0xBA933071,0x21367C1E,0x55AE9591,0xCE0BD9FE,0xB9950B0E,0x22304761,
1194
+ 0x5CBC35EC,0xC7197983,0xB087AB73,0x2B22E71C,0x5FBA0E93,0xC41F42FC,0xB381900C,0x2824DC63,
1195
+ 0x5AB04312,0xC1150F7D,0xB68BDD8D,0x2D2E91E2,0x59B6786D,0xC2133402,0xB58DE6F2,0x2E28AA9D,
1196
+ 0x489503E8,0xD3304F87,0xA4AE9D77,0x3F0BD118,0x4B933897,0xD03674F8,0xA7A8A608,0x3C0DEA67,
1197
+ 0x4E997516,0xD53C3979,0xA2A2EB89,0x3907A7E6,0x4D9F4E69,0xD63A0206,0xA1A4D0F6,0x3A019C99,
1198
+ 0x448DEE14,0xDF28A27B,0xA8B6708B,0x33133CE4,0x478BD56B,0xDC2E9904,0xABB04BF4,0x3015079B,
1199
+ 0x428198EA,0xD924D485,0xAEBA0675,0x351F4A1A,0x4187A395,0xDA22EFFA,0xADBC3D0A,0x36197165,
1200
+ },
1201
+
1202
+ {
1203
+ 0x00000000,0xDD96D985,0x605CB54B,0xBDCA6CCE,0xC0B96A96,0x1D2FB313,0xA0E5DFDD,0x7D730658,
1204
+ 0x5A03D36D,0x87950AE8,0x3A5F6626,0xE7C9BFA3,0x9ABAB9FB,0x472C607E,0xFAE60CB0,0x2770D535,
1205
+ 0xB407A6DA,0x69917F5F,0xD45B1391,0x09CDCA14,0x74BECC4C,0xA92815C9,0x14E27907,0xC974A082,
1206
+ 0xEE0475B7,0x3392AC32,0x8E58C0FC,0x53CE1979,0x2EBD1F21,0xF32BC6A4,0x4EE1AA6A,0x937773EF,
1207
+ 0xB37E4BF5,0x6EE89270,0xD322FEBE,0x0EB4273B,0x73C72163,0xAE51F8E6,0x139B9428,0xCE0D4DAD,
1208
+ 0xE97D9898,0x34EB411D,0x89212DD3,0x54B7F456,0x29C4F20E,0xF4522B8B,0x49984745,0x940E9EC0,
1209
+ 0x0779ED2F,0xDAEF34AA,0x67255864,0xBAB381E1,0xC7C087B9,0x1A565E3C,0xA79C32F2,0x7A0AEB77,
1210
+ 0x5D7A3E42,0x80ECE7C7,0x3D268B09,0xE0B0528C,0x9DC354D4,0x40558D51,0xFD9FE19F,0x2009381A,
1211
+ 0xBD8D91AB,0x601B482E,0xDDD124E0,0x0047FD65,0x7D34FB3D,0xA0A222B8,0x1D684E76,0xC0FE97F3,
1212
+ 0xE78E42C6,0x3A189B43,0x87D2F78D,0x5A442E08,0x27372850,0xFAA1F1D5,0x476B9D1B,0x9AFD449E,
1213
+ 0x098A3771,0xD41CEEF4,0x69D6823A,0xB4405BBF,0xC9335DE7,0x14A58462,0xA96FE8AC,0x74F93129,
1214
+ 0x5389E41C,0x8E1F3D99,0x33D55157,0xEE4388D2,0x93308E8A,0x4EA6570F,0xF36C3BC1,0x2EFAE244,
1215
+ 0x0EF3DA5E,0xD36503DB,0x6EAF6F15,0xB339B690,0xCE4AB0C8,0x13DC694D,0xAE160583,0x7380DC06,
1216
+ 0x54F00933,0x8966D0B6,0x34ACBC78,0xE93A65FD,0x944963A5,0x49DFBA20,0xF415D6EE,0x29830F6B,
1217
+ 0xBAF47C84,0x6762A501,0xDAA8C9CF,0x073E104A,0x7A4D1612,0xA7DBCF97,0x1A11A359,0xC7877ADC,
1218
+ 0xE0F7AFE9,0x3D61766C,0x80AB1AA2,0x5D3DC327,0x204EC57F,0xFDD81CFA,0x40127034,0x9D84A9B1,
1219
+ 0xA06A2517,0x7DFCFC92,0xC036905C,0x1DA049D9,0x60D34F81,0xBD459604,0x008FFACA,0xDD19234F,
1220
+ 0xFA69F67A,0x27FF2FFF,0x9A354331,0x47A39AB4,0x3AD09CEC,0xE7464569,0x5A8C29A7,0x871AF022,
1221
+ 0x146D83CD,0xC9FB5A48,0x74313686,0xA9A7EF03,0xD4D4E95B,0x094230DE,0xB4885C10,0x691E8595,
1222
+ 0x4E6E50A0,0x93F88925,0x2E32E5EB,0xF3A43C6E,0x8ED73A36,0x5341E3B3,0xEE8B8F7D,0x331D56F8,
1223
+ 0x13146EE2,0xCE82B767,0x7348DBA9,0xAEDE022C,0xD3AD0474,0x0E3BDDF1,0xB3F1B13F,0x6E6768BA,
1224
+ 0x4917BD8F,0x9481640A,0x294B08C4,0xF4DDD141,0x89AED719,0x54380E9C,0xE9F26252,0x3464BBD7,
1225
+ 0xA713C838,0x7A8511BD,0xC74F7D73,0x1AD9A4F6,0x67AAA2AE,0xBA3C7B2B,0x07F617E5,0xDA60CE60,
1226
+ 0xFD101B55,0x2086C2D0,0x9D4CAE1E,0x40DA779B,0x3DA971C3,0xE03FA846,0x5DF5C488,0x80631D0D,
1227
+ 0x1DE7B4BC,0xC0716D39,0x7DBB01F7,0xA02DD872,0xDD5EDE2A,0x00C807AF,0xBD026B61,0x6094B2E4,
1228
+ 0x47E467D1,0x9A72BE54,0x27B8D29A,0xFA2E0B1F,0x875D0D47,0x5ACBD4C2,0xE701B80C,0x3A976189,
1229
+ 0xA9E01266,0x7476CBE3,0xC9BCA72D,0x142A7EA8,0x695978F0,0xB4CFA175,0x0905CDBB,0xD493143E,
1230
+ 0xF3E3C10B,0x2E75188E,0x93BF7440,0x4E29ADC5,0x335AAB9D,0xEECC7218,0x53061ED6,0x8E90C753,
1231
+ 0xAE99FF49,0x730F26CC,0xCEC54A02,0x13539387,0x6E2095DF,0xB3B64C5A,0x0E7C2094,0xD3EAF911,
1232
+ 0xF49A2C24,0x290CF5A1,0x94C6996F,0x495040EA,0x342346B2,0xE9B59F37,0x547FF3F9,0x89E92A7C,
1233
+ 0x1A9E5993,0xC7088016,0x7AC2ECD8,0xA754355D,0xDA273305,0x07B1EA80,0xBA7B864E,0x67ED5FCB,
1234
+ 0x409D8AFE,0x9D0B537B,0x20C13FB5,0xFD57E630,0x8024E068,0x5DB239ED,0xE0785523,0x3DEE8CA6,
1235
+ },
1236
+
1237
+ {
1238
+ 0x00000000,0x9D0FE176,0xE16EC4AD,0x7C6125DB,0x19AC8F1B,0x84A36E6D,0xF8C24BB6,0x65CDAAC0,
1239
+ 0x33591E36,0xAE56FF40,0xD237DA9B,0x4F383BED,0x2AF5912D,0xB7FA705B,0xCB9B5580,0x5694B4F6,
1240
+ 0x66B23C6C,0xFBBDDD1A,0x87DCF8C1,0x1AD319B7,0x7F1EB377,0xE2115201,0x9E7077DA,0x037F96AC,
1241
+ 0x55EB225A,0xC8E4C32C,0xB485E6F7,0x298A0781,0x4C47AD41,0xD1484C37,0xAD2969EC,0x3026889A,
1242
+ 0xCD6478D8,0x506B99AE,0x2C0ABC75,0xB1055D03,0xD4C8F7C3,0x49C716B5,0x35A6336E,0xA8A9D218,
1243
+ 0xFE3D66EE,0x63328798,0x1F53A243,0x825C4335,0xE791E9F5,0x7A9E0883,0x06FF2D58,0x9BF0CC2E,
1244
+ 0xABD644B4,0x36D9A5C2,0x4AB88019,0xD7B7616F,0xB27ACBAF,0x2F752AD9,0x53140F02,0xCE1BEE74,
1245
+ 0x988F5A82,0x0580BBF4,0x79E19E2F,0xE4EE7F59,0x8123D599,0x1C2C34EF,0x604D1134,0xFD42F042,
1246
+ 0x41B9F7F1,0xDCB61687,0xA0D7335C,0x3DD8D22A,0x581578EA,0xC51A999C,0xB97BBC47,0x24745D31,
1247
+ 0x72E0E9C7,0xEFEF08B1,0x938E2D6A,0x0E81CC1C,0x6B4C66DC,0xF64387AA,0x8A22A271,0x172D4307,
1248
+ 0x270BCB9D,0xBA042AEB,0xC6650F30,0x5B6AEE46,0x3EA74486,0xA3A8A5F0,0xDFC9802B,0x42C6615D,
1249
+ 0x1452D5AB,0x895D34DD,0xF53C1106,0x6833F070,0x0DFE5AB0,0x90F1BBC6,0xEC909E1D,0x719F7F6B,
1250
+ 0x8CDD8F29,0x11D26E5F,0x6DB34B84,0xF0BCAAF2,0x95710032,0x087EE144,0x741FC49F,0xE91025E9,
1251
+ 0xBF84911F,0x228B7069,0x5EEA55B2,0xC3E5B4C4,0xA6281E04,0x3B27FF72,0x4746DAA9,0xDA493BDF,
1252
+ 0xEA6FB345,0x77605233,0x0B0177E8,0x960E969E,0xF3C33C5E,0x6ECCDD28,0x12ADF8F3,0x8FA21985,
1253
+ 0xD936AD73,0x44394C05,0x385869DE,0xA55788A8,0xC09A2268,0x5D95C31E,0x21F4E6C5,0xBCFB07B3,
1254
+ 0x8373EFE2,0x1E7C0E94,0x621D2B4F,0xFF12CA39,0x9ADF60F9,0x07D0818F,0x7BB1A454,0xE6BE4522,
1255
+ 0xB02AF1D4,0x2D2510A2,0x51443579,0xCC4BD40F,0xA9867ECF,0x34899FB9,0x48E8BA62,0xD5E75B14,
1256
+ 0xE5C1D38E,0x78CE32F8,0x04AF1723,0x99A0F655,0xFC6D5C95,0x6162BDE3,0x1D039838,0x800C794E,
1257
+ 0xD698CDB8,0x4B972CCE,0x37F60915,0xAAF9E863,0xCF3442A3,0x523BA3D5,0x2E5A860E,0xB3556778,
1258
+ 0x4E17973A,0xD318764C,0xAF795397,0x3276B2E1,0x57BB1821,0xCAB4F957,0xB6D5DC8C,0x2BDA3DFA,
1259
+ 0x7D4E890C,0xE041687A,0x9C204DA1,0x012FACD7,0x64E20617,0xF9EDE761,0x858CC2BA,0x188323CC,
1260
+ 0x28A5AB56,0xB5AA4A20,0xC9CB6FFB,0x54C48E8D,0x3109244D,0xAC06C53B,0xD067E0E0,0x4D680196,
1261
+ 0x1BFCB560,0x86F35416,0xFA9271CD,0x679D90BB,0x02503A7B,0x9F5FDB0D,0xE33EFED6,0x7E311FA0,
1262
+ 0xC2CA1813,0x5FC5F965,0x23A4DCBE,0xBEAB3DC8,0xDB669708,0x4669767E,0x3A0853A5,0xA707B2D3,
1263
+ 0xF1930625,0x6C9CE753,0x10FDC288,0x8DF223FE,0xE83F893E,0x75306848,0x09514D93,0x945EACE5,
1264
+ 0xA478247F,0x3977C509,0x4516E0D2,0xD81901A4,0xBDD4AB64,0x20DB4A12,0x5CBA6FC9,0xC1B58EBF,
1265
+ 0x97213A49,0x0A2EDB3F,0x764FFEE4,0xEB401F92,0x8E8DB552,0x13825424,0x6FE371FF,0xF2EC9089,
1266
+ 0x0FAE60CB,0x92A181BD,0xEEC0A466,0x73CF4510,0x1602EFD0,0x8B0D0EA6,0xF76C2B7D,0x6A63CA0B,
1267
+ 0x3CF77EFD,0xA1F89F8B,0xDD99BA50,0x40965B26,0x255BF1E6,0xB8541090,0xC435354B,0x593AD43D,
1268
+ 0x691C5CA7,0xF413BDD1,0x8872980A,0x157D797C,0x70B0D3BC,0xEDBF32CA,0x91DE1711,0x0CD1F667,
1269
+ 0x5A454291,0xC74AA3E7,0xBB2B863C,0x2624674A,0x43E9CD8A,0xDEE62CFC,0xA2870927,0x3F88E851,
1270
+ },
1271
+
1272
+ {
1273
+ 0x00000000,0xB9FBDBE8,0xA886B191,0x117D6A79,0x8A7C6563,0x3387BE8B,0x22FAD4F2,0x9B010F1A,
1274
+ 0xCF89CC87,0x7672176F,0x670F7D16,0xDEF4A6FE,0x45F5A9E4,0xFC0E720C,0xED731875,0x5488C39D,
1275
+ 0x44629F4F,0xFD9944A7,0xECE42EDE,0x551FF536,0xCE1EFA2C,0x77E521C4,0x66984BBD,0xDF639055,
1276
+ 0x8BEB53C8,0x32108820,0x236DE259,0x9A9639B1,0x019736AB,0xB86CED43,0xA911873A,0x10EA5CD2,
1277
+ 0x88C53E9E,0x313EE576,0x20438F0F,0x99B854E7,0x02B95BFD,0xBB428015,0xAA3FEA6C,0x13C43184,
1278
+ 0x474CF219,0xFEB729F1,0xEFCA4388,0x56319860,0xCD30977A,0x74CB4C92,0x65B626EB,0xDC4DFD03,
1279
+ 0xCCA7A1D1,0x755C7A39,0x64211040,0xDDDACBA8,0x46DBC4B2,0xFF201F5A,0xEE5D7523,0x57A6AECB,
1280
+ 0x032E6D56,0xBAD5B6BE,0xABA8DCC7,0x1253072F,0x89520835,0x30A9D3DD,0x21D4B9A4,0x982F624C,
1281
+ 0xCAFB7B7D,0x7300A095,0x627DCAEC,0xDB861104,0x40871E1E,0xF97CC5F6,0xE801AF8F,0x51FA7467,
1282
+ 0x0572B7FA,0xBC896C12,0xADF4066B,0x140FDD83,0x8F0ED299,0x36F50971,0x27886308,0x9E73B8E0,
1283
+ 0x8E99E432,0x37623FDA,0x261F55A3,0x9FE48E4B,0x04E58151,0xBD1E5AB9,0xAC6330C0,0x1598EB28,
1284
+ 0x411028B5,0xF8EBF35D,0xE9969924,0x506D42CC,0xCB6C4DD6,0x7297963E,0x63EAFC47,0xDA1127AF,
1285
+ 0x423E45E3,0xFBC59E0B,0xEAB8F472,0x53432F9A,0xC8422080,0x71B9FB68,0x60C49111,0xD93F4AF9,
1286
+ 0x8DB78964,0x344C528C,0x253138F5,0x9CCAE31D,0x07CBEC07,0xBE3037EF,0xAF4D5D96,0x16B6867E,
1287
+ 0x065CDAAC,0xBFA70144,0xAEDA6B3D,0x1721B0D5,0x8C20BFCF,0x35DB6427,0x24A60E5E,0x9D5DD5B6,
1288
+ 0xC9D5162B,0x702ECDC3,0x6153A7BA,0xD8A87C52,0x43A97348,0xFA52A8A0,0xEB2FC2D9,0x52D41931,
1289
+ 0x4E87F0BB,0xF77C2B53,0xE601412A,0x5FFA9AC2,0xC4FB95D8,0x7D004E30,0x6C7D2449,0xD586FFA1,
1290
+ 0x810E3C3C,0x38F5E7D4,0x29888DAD,0x90735645,0x0B72595F,0xB28982B7,0xA3F4E8CE,0x1A0F3326,
1291
+ 0x0AE56FF4,0xB31EB41C,0xA263DE65,0x1B98058D,0x80990A97,0x3962D17F,0x281FBB06,0x91E460EE,
1292
+ 0xC56CA373,0x7C97789B,0x6DEA12E2,0xD411C90A,0x4F10C610,0xF6EB1DF8,0xE7967781,0x5E6DAC69,
1293
+ 0xC642CE25,0x7FB915CD,0x6EC47FB4,0xD73FA45C,0x4C3EAB46,0xF5C570AE,0xE4B81AD7,0x5D43C13F,
1294
+ 0x09CB02A2,0xB030D94A,0xA14DB333,0x18B668DB,0x83B767C1,0x3A4CBC29,0x2B31D650,0x92CA0DB8,
1295
+ 0x8220516A,0x3BDB8A82,0x2AA6E0FB,0x935D3B13,0x085C3409,0xB1A7EFE1,0xA0DA8598,0x19215E70,
1296
+ 0x4DA99DED,0xF4524605,0xE52F2C7C,0x5CD4F794,0xC7D5F88E,0x7E2E2366,0x6F53491F,0xD6A892F7,
1297
+ 0x847C8BC6,0x3D87502E,0x2CFA3A57,0x9501E1BF,0x0E00EEA5,0xB7FB354D,0xA6865F34,0x1F7D84DC,
1298
+ 0x4BF54741,0xF20E9CA9,0xE373F6D0,0x5A882D38,0xC1892222,0x7872F9CA,0x690F93B3,0xD0F4485B,
1299
+ 0xC01E1489,0x79E5CF61,0x6898A518,0xD1637EF0,0x4A6271EA,0xF399AA02,0xE2E4C07B,0x5B1F1B93,
1300
+ 0x0F97D80E,0xB66C03E6,0xA711699F,0x1EEAB277,0x85EBBD6D,0x3C106685,0x2D6D0CFC,0x9496D714,
1301
+ 0x0CB9B558,0xB5426EB0,0xA43F04C9,0x1DC4DF21,0x86C5D03B,0x3F3E0BD3,0x2E4361AA,0x97B8BA42,
1302
+ 0xC33079DF,0x7ACBA237,0x6BB6C84E,0xD24D13A6,0x494C1CBC,0xF0B7C754,0xE1CAAD2D,0x583176C5,
1303
+ 0x48DB2A17,0xF120F1FF,0xE05D9B86,0x59A6406E,0xC2A74F74,0x7B5C949C,0x6A21FEE5,0xD3DA250D,
1304
+ 0x8752E690,0x3EA93D78,0x2FD45701,0x962F8CE9,0x0D2E83F3,0xB4D5581B,0xA5A83262,0x1C53E98A,
1305
+ },
1306
+
1307
+ {
1308
+ 0x00000000,0xAE689191,0x87A02563,0x29C8B4F2,0xD4314C87,0x7A59DD16,0x539169E4,0xFDF9F875,
1309
+ 0x73139F4F,0xDD7B0EDE,0xF4B3BA2C,0x5ADB2BBD,0xA722D3C8,0x094A4259,0x2082F6AB,0x8EEA673A,
1310
+ 0xE6273E9E,0x484FAF0F,0x61871BFD,0xCFEF8A6C,0x32167219,0x9C7EE388,0xB5B6577A,0x1BDEC6EB,
1311
+ 0x9534A1D1,0x3B5C3040,0x129484B2,0xBCFC1523,0x4105ED56,0xEF6D7CC7,0xC6A5C835,0x68CD59A4,
1312
+ 0x173F7B7D,0xB957EAEC,0x909F5E1E,0x3EF7CF8F,0xC30E37FA,0x6D66A66B,0x44AE1299,0xEAC68308,
1313
+ 0x642CE432,0xCA4475A3,0xE38CC151,0x4DE450C0,0xB01DA8B5,0x1E753924,0x37BD8DD6,0x99D51C47,
1314
+ 0xF11845E3,0x5F70D472,0x76B86080,0xD8D0F111,0x25290964,0x8B4198F5,0xA2892C07,0x0CE1BD96,
1315
+ 0x820BDAAC,0x2C634B3D,0x05ABFFCF,0xABC36E5E,0x563A962B,0xF85207BA,0xD19AB348,0x7FF222D9,
1316
+ 0x2E7EF6FA,0x8016676B,0xA9DED399,0x07B64208,0xFA4FBA7D,0x54272BEC,0x7DEF9F1E,0xD3870E8F,
1317
+ 0x5D6D69B5,0xF305F824,0xDACD4CD6,0x74A5DD47,0x895C2532,0x2734B4A3,0x0EFC0051,0xA09491C0,
1318
+ 0xC859C864,0x663159F5,0x4FF9ED07,0xE1917C96,0x1C6884E3,0xB2001572,0x9BC8A180,0x35A03011,
1319
+ 0xBB4A572B,0x1522C6BA,0x3CEA7248,0x9282E3D9,0x6F7B1BAC,0xC1138A3D,0xE8DB3ECF,0x46B3AF5E,
1320
+ 0x39418D87,0x97291C16,0xBEE1A8E4,0x10893975,0xED70C100,0x43185091,0x6AD0E463,0xC4B875F2,
1321
+ 0x4A5212C8,0xE43A8359,0xCDF237AB,0x639AA63A,0x9E635E4F,0x300BCFDE,0x19C37B2C,0xB7ABEABD,
1322
+ 0xDF66B319,0x710E2288,0x58C6967A,0xF6AE07EB,0x0B57FF9E,0xA53F6E0F,0x8CF7DAFD,0x229F4B6C,
1323
+ 0xAC752C56,0x021DBDC7,0x2BD50935,0x85BD98A4,0x784460D1,0xD62CF140,0xFFE445B2,0x518CD423,
1324
+ 0x5CFDEDF4,0xF2957C65,0xDB5DC897,0x75355906,0x88CCA173,0x26A430E2,0x0F6C8410,0xA1041581,
1325
+ 0x2FEE72BB,0x8186E32A,0xA84E57D8,0x0626C649,0xFBDF3E3C,0x55B7AFAD,0x7C7F1B5F,0xD2178ACE,
1326
+ 0xBADAD36A,0x14B242FB,0x3D7AF609,0x93126798,0x6EEB9FED,0xC0830E7C,0xE94BBA8E,0x47232B1F,
1327
+ 0xC9C94C25,0x67A1DDB4,0x4E696946,0xE001F8D7,0x1DF800A2,0xB3909133,0x9A5825C1,0x3430B450,
1328
+ 0x4BC29689,0xE5AA0718,0xCC62B3EA,0x620A227B,0x9FF3DA0E,0x319B4B9F,0x1853FF6D,0xB63B6EFC,
1329
+ 0x38D109C6,0x96B99857,0xBF712CA5,0x1119BD34,0xECE04541,0x4288D4D0,0x6B406022,0xC528F1B3,
1330
+ 0xADE5A817,0x038D3986,0x2A458D74,0x842D1CE5,0x79D4E490,0xD7BC7501,0xFE74C1F3,0x501C5062,
1331
+ 0xDEF63758,0x709EA6C9,0x5956123B,0xF73E83AA,0x0AC77BDF,0xA4AFEA4E,0x8D675EBC,0x230FCF2D,
1332
+ 0x72831B0E,0xDCEB8A9F,0xF5233E6D,0x5B4BAFFC,0xA6B25789,0x08DAC618,0x211272EA,0x8F7AE37B,
1333
+ 0x01908441,0xAFF815D0,0x8630A122,0x285830B3,0xD5A1C8C6,0x7BC95957,0x5201EDA5,0xFC697C34,
1334
+ 0x94A42590,0x3ACCB401,0x130400F3,0xBD6C9162,0x40956917,0xEEFDF886,0xC7354C74,0x695DDDE5,
1335
+ 0xE7B7BADF,0x49DF2B4E,0x60179FBC,0xCE7F0E2D,0x3386F658,0x9DEE67C9,0xB426D33B,0x1A4E42AA,
1336
+ 0x65BC6073,0xCBD4F1E2,0xE21C4510,0x4C74D481,0xB18D2CF4,0x1FE5BD65,0x362D0997,0x98459806,
1337
+ 0x16AFFF3C,0xB8C76EAD,0x910FDA5F,0x3F674BCE,0xC29EB3BB,0x6CF6222A,0x453E96D8,0xEB560749,
1338
+ 0x839B5EED,0x2DF3CF7C,0x043B7B8E,0xAA53EA1F,0x57AA126A,0xF9C283FB,0xD00A3709,0x7E62A698,
1339
+ 0xF088C1A2,0x5EE05033,0x7728E4C1,0xD9407550,0x24B98D25,0x8AD11CB4,0xA319A846,0x0D7139D7,
1340
+ }
1341
+ #endif // CRC32_USE_LOOKUP_TABLE_SLICING_BY_16
1342
+ };
1343
+ #endif
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/file_adapter.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <fstream>
4
+ #include <memory>
5
+ #include <c10/macros/Macros.h>
6
+
7
+ #include "caffe2/serialize/istream_adapter.h"
8
+ #include "caffe2/serialize/read_adapter_interface.h"
9
+
10
+ namespace caffe2 {
11
+ namespace serialize {
12
+
13
+ class TORCH_API FileAdapter final : public ReadAdapterInterface {
14
+ public:
15
+ C10_DISABLE_COPY_AND_ASSIGN(FileAdapter);
16
+ explicit FileAdapter(const std::string& file_name);
17
+ size_t size() const override;
18
+ size_t read(uint64_t pos, void* buf, size_t n, const char* what = "")
19
+ const override;
20
+ ~FileAdapter() override;
21
+
22
+ private:
23
+ // An RAII Wrapper for a FILE pointer. Closes on destruction.
24
+ struct RAIIFile {
25
+ FILE* fp_;
26
+ explicit RAIIFile(const std::string& file_name);
27
+ ~RAIIFile();
28
+ };
29
+
30
+ RAIIFile file_;
31
+ // The size of the opened file in bytes
32
+ uint64_t size_;
33
+ };
34
+
35
+ } // namespace serialize
36
+ } // namespace caffe2
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/in_memory_adapter.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <cstring>
3
+ #include <caffe2/serialize/read_adapter_interface.h>
4
+
5
+
6
+ namespace caffe2 {
7
+ namespace serialize {
8
+
9
+ class MemoryReadAdapter final : public caffe2::serialize::ReadAdapterInterface {
10
+ public:
11
+ explicit MemoryReadAdapter(const void* data, off_t size)
12
+ : data_(data), size_(size) {}
13
+
14
+ size_t size() const override {
15
+ return size_;
16
+ }
17
+
18
+ size_t read(uint64_t pos, void* buf, size_t n, const char* what = "")
19
+ const override {
20
+ (void) what;
21
+ memcpy(buf, (int8_t*)(data_) + pos, n);
22
+ return n;
23
+ }
24
+
25
+ private:
26
+ const void* data_;
27
+ off_t size_;
28
+ };
29
+
30
+
31
+ } // namespace serialize
32
+ } // namespace caffe2
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/inline_container.h ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cerrno>
4
+ #include <cstdio>
5
+ #include <cstring>
6
+ #include <fstream>
7
+ #include <istream>
8
+ #include <mutex>
9
+ #include <ostream>
10
+ #include <unordered_set>
11
+
12
+ #include <c10/core/Allocator.h>
13
+ #include <c10/core/Backend.h>
14
+
15
+ #include "caffe2/serialize/istream_adapter.h"
16
+ #include "caffe2/serialize/read_adapter_interface.h"
17
+ #include "caffe2/serialize/versions.h"
18
+
19
+
20
+ extern "C" {
21
+ typedef struct mz_zip_archive mz_zip_archive;
22
+ }
23
+
24
+ // PyTorch containers are a special zip archive with the following layout
25
+ // archive_name.zip contains:
26
+ // archive_name/
27
+ // version # a file with a single decimal number written in ascii,
28
+ // # used to establish the version of the archive format
29
+ // model.json # overall model description, this is a json output of
30
+ // # ModelDef from torch.proto
31
+ // # the following names are by convention only, model.json will
32
+ // # refer to these files by full names
33
+ // tensors/
34
+ // 0 # flat storage for tensor data, meta-data about shapes, etc. is
35
+ // # in model.json
36
+ // 1
37
+ // ...
38
+ // # code entries will only exist for modules that have methods attached
39
+ // code/
40
+ // archive_name.py # serialized torch script code (python syntax, using
41
+ // PythonPrint) archive_name_my_submodule.py # submodules have separate
42
+ // files
43
+ //
44
+ // The PyTorchStreamWriter also ensures additional useful properties for these
45
+ // files
46
+ // 1. All files are stored uncompressed.
47
+ // 2. All files in the archive are aligned to 64 byte boundaries such that
48
+ // it is possible to mmap the entire file and get an aligned pointer to
49
+ // tensor data.
50
+ // 3. We universally write in ZIP64 format for consistency.
51
+
52
+ // The PyTorchStreamReader also provides additional properties:
53
+ // 1. It can read zip files that are created with common
54
+ // zip tools. This means that even though our writer doesn't compress files,
55
+ // the reader can still read files that were compressed.
56
+ // 2. It provides a getRecordOffset function which returns the offset into the
57
+ // raw file where file data lives. If the file was written with
58
+ // PyTorchStreamWriter it is guaranteed to be 64 byte aligned.
59
+
60
+ // PyTorchReader/Writer handle checking the version number on the archive format
61
+ // and ensure that all files are written to a archive_name directory so they
62
+ // unzip cleanly.
63
+
64
+ // When developing this format we want to pay particular attention to the
65
+ // following use cases:
66
+ //
67
+ // -- Reading --
68
+ // 1) Reading with full random access
69
+ // a) Reading with file api's such as fread()
70
+ // b) mmaping the file and jumping around the mapped region
71
+ // 2) Reading with 1-pass sequential access
72
+ // -> A reader will need to build up a data structure of parsed structures
73
+ // as it reads
74
+ //
75
+ // -- Writing --
76
+ // 1) Writing with full random access
77
+ // 2) Writing with 1-pass sequential access
78
+ // -> We must take care not to require updating values that have already
79
+ // been written. We place the variable-length index at the end and do
80
+ // not put any indicies into the header to fulfill this constraint.
81
+
82
+ // The model.json, which contains all the metadata information,
83
+ // should be written as the last file. One reason is that the size of tensor
84
+ // data is usually stable. As long as the shape and type of the tensor do not
85
+ // change, the size of the data won't change. On the other sied, the size of the
86
+ // serialized model is likely to change, so we store it as the last record, and
87
+ // we don't need to move previous records when updating the model data.
88
+
89
+ // The zip format is sufficiently flexible to handle the above use-case.
90
+ // it puts its central directory at the end of the archive and we write
91
+ // model.json as the last file when writing after we have accumulated all
92
+ // other information.
93
+
94
+ namespace caffe2 {
95
+ namespace serialize {
96
+
97
+ static constexpr const char* kSerializationIdRecordName = ".data/serialization_id";
98
+
99
+ struct MzZipReaderIterWrapper;
100
+
101
+ class TORCH_API ChunkRecordIterator {
102
+ public:
103
+ ~ChunkRecordIterator();
104
+
105
+ // Read at most `chunkSize` into `buf`. Return the number of actual bytes read.
106
+ size_t next(void* buf);
107
+
108
+ private:
109
+ ChunkRecordIterator(
110
+ size_t recordSize,
111
+ size_t chunkSize,
112
+ std::unique_ptr<MzZipReaderIterWrapper> iter);
113
+
114
+ const size_t recordSize_;
115
+ const size_t chunkSize_;
116
+ size_t offset_;
117
+ std::unique_ptr<MzZipReaderIterWrapper> iter_;
118
+
119
+ friend class PyTorchStreamReader;
120
+ };
121
+
122
+ class TORCH_API PyTorchStreamReader final {
123
+ public:
124
+ explicit PyTorchStreamReader(const std::string& file_name);
125
+ explicit PyTorchStreamReader(std::istream* in);
126
+ explicit PyTorchStreamReader(std::shared_ptr<ReadAdapterInterface> in);
127
+
128
+ // return dataptr, size
129
+ std::tuple<at::DataPtr, size_t> getRecord(const std::string& name);
130
+ // multi-thread getRecord
131
+ std::tuple<at::DataPtr, size_t> getRecord(const std::string& name, std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders);
132
+ // inplace memory writing
133
+ size_t getRecord(const std::string& name, void* dst, size_t n);
134
+ // inplace memory writing, multi-threads.
135
+ // When additionalReaders is empty, the default behavior is call getRecord(name, dst, n) with default reader
136
+ // This approach can be used for reading large tensors.
137
+ size_t getRecord(const std::string& name, void* dst, size_t n,
138
+ std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders);
139
+ size_t getRecord(
140
+ const std::string& name,
141
+ void* dst,
142
+ size_t n,
143
+ size_t chunk_size,
144
+ void* buf,
145
+ const std::function<void(void*, const void*, size_t)>& memcpy_func = nullptr);
146
+
147
+ // Concurrent reading records with multiple readers.
148
+ // additionalReaders are additional clients to access the underlying record at different offsets
149
+ // and write to different trunks of buffers.
150
+ // If the overall size of the tensor is 10, and size of additionalReader is 2.
151
+ // The default thread will read [0,4), the additional reader will read [4,8).
152
+ // The default reader will read [8,10).
153
+ // The default reader will write to buffer[0,4), the additional reader will write to buffer[4,8),
154
+ // the additional reader will write to buffer[8,10).
155
+ // When additionalReaders is empty, the default behavior is call getRecord(name) with default reader
156
+ // This approach can be used for reading large tensors.
157
+ size_t getRecordMultiReaders(const std::string& name,
158
+ std::vector<std::shared_ptr<ReadAdapterInterface>>& additionalReaders,
159
+ void *dst, size_t n);
160
+
161
+ size_t getRecordSize(const std::string& name);
162
+
163
+ size_t getRecordOffset(const std::string& name);
164
+ bool hasRecord(const std::string& name);
165
+ std::vector<std::string> getAllRecords();
166
+
167
+ ChunkRecordIterator createChunkReaderIter(
168
+ const std::string& name,
169
+ const size_t recordSize,
170
+ const size_t chunkSize);
171
+
172
+ ~PyTorchStreamReader();
173
+ uint64_t version() const {
174
+ return version_;
175
+ }
176
+ const std::string& serializationId() {
177
+ return serialization_id_;
178
+ }
179
+
180
+ void setShouldLoadDebugSymbol(bool should_load_debug_symbol) {
181
+ load_debug_symbol_ = should_load_debug_symbol;
182
+ }
183
+ void setAdditionalReaderSizeThreshold(const size_t& size){
184
+ additional_reader_size_threshold_ = size;
185
+ }
186
+ private:
187
+ void init();
188
+ size_t read(uint64_t pos, char* buf, size_t n);
189
+ void valid(const char* what, const char* info = "");
190
+ size_t getRecordID(const std::string& name);
191
+
192
+ friend size_t
193
+ istream_read_func(void* pOpaque, uint64_t file_ofs, void* pBuf, size_t n);
194
+ std::unique_ptr<mz_zip_archive> ar_;
195
+ std::string archive_name_;
196
+ std::string archive_name_plus_slash_;
197
+ std::shared_ptr<ReadAdapterInterface> in_;
198
+ int64_t version_;
199
+ std::mutex reader_lock_;
200
+ bool load_debug_symbol_ = true;
201
+ std::string serialization_id_;
202
+ size_t additional_reader_size_threshold_;
203
+ };
204
+
205
+ class TORCH_API PyTorchStreamWriter final {
206
+ public:
207
+ explicit PyTorchStreamWriter(const std::string& archive_name);
208
+ explicit PyTorchStreamWriter(
209
+ const std::function<size_t(const void*, size_t)> writer_func);
210
+
211
+ void setMinVersion(const uint64_t version);
212
+
213
+ void writeRecord(
214
+ const std::string& name,
215
+ const void* data,
216
+ size_t size,
217
+ bool compress = false);
218
+ void writeEndOfFile();
219
+
220
+ const std::unordered_set<std::string>& getAllWrittenRecords();
221
+
222
+ bool finalized() const {
223
+ return finalized_;
224
+ }
225
+
226
+ const std::string& archiveName() {
227
+ return archive_name_;
228
+ }
229
+
230
+ const std::string& serializationId() {
231
+ return serialization_id_;
232
+ }
233
+
234
+ ~PyTorchStreamWriter();
235
+
236
+ private:
237
+ void setup(const std::string& file_name);
238
+ void valid(const char* what, const char* info = "");
239
+ void writeSerializationId();
240
+ size_t current_pos_ = 0;
241
+ std::unordered_set<std::string> files_written_;
242
+ std::unique_ptr<mz_zip_archive> ar_;
243
+ std::string archive_name_;
244
+ std::string archive_name_plus_slash_;
245
+ std::string padding_;
246
+ std::ofstream file_stream_;
247
+ std::function<size_t(const void*, size_t)> writer_func_;
248
+ uint64_t combined_uncomp_crc32_ = 0;
249
+ std::string serialization_id_;
250
+
251
+ // This number will be updated when the model has operators
252
+ // that have valid upgraders.
253
+ uint64_t version_ = kMinProducedFileFormatVersion;
254
+ bool finalized_ = false;
255
+ bool err_seen_ = false;
256
+ friend size_t ostream_write_func(
257
+ void* pOpaque,
258
+ uint64_t file_ofs,
259
+ const void* pBuf,
260
+ size_t n);
261
+ };
262
+
263
+ namespace detail {
264
+ // Writer-specific constants
265
+ constexpr uint64_t kFieldAlignment = 64;
266
+
267
+ // Returns a record to be appended to the local user extra data entry in order
268
+ // to make data beginning aligned at kFieldAlignment bytes boundary.
269
+ size_t getPadding(
270
+ size_t cursor,
271
+ size_t filename_size,
272
+ size_t size,
273
+ std::string& padding_buf);
274
+ } // namespace detail
275
+
276
+ } // namespace serialize
277
+ } // namespace caffe2
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/istream_adapter.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <istream>
4
+
5
+ #include "c10/macros/Macros.h"
6
+ #include "caffe2/serialize/read_adapter_interface.h"
7
+
8
+ namespace caffe2 {
9
+ namespace serialize {
10
+
11
+ // this is a reader implemented by std::istream
12
+ class TORCH_API IStreamAdapter final : public ReadAdapterInterface {
13
+ public:
14
+ C10_DISABLE_COPY_AND_ASSIGN(IStreamAdapter);
15
+ explicit IStreamAdapter(std::istream* istream);
16
+ size_t size() const override;
17
+ size_t read(uint64_t pos, void* buf, size_t n, const char* what = "")
18
+ const override;
19
+ ~IStreamAdapter() override;
20
+
21
+ private:
22
+ std::istream* istream_;
23
+ void validate(const char* what) const;
24
+ };
25
+
26
+ } // namespace serialize
27
+ } // namespace caffe2
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/read_adapter_interface.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <cstdint>
5
+
6
+ #include "c10/macros/Macros.h"
7
+
8
+ namespace caffe2 {
9
+ namespace serialize {
10
+
11
+ // this is the interface for the (file/stream/memory) reader in
12
+ // PyTorchStreamReader. with this interface, we can extend the support
13
+ // besides standard istream
14
+ class TORCH_API ReadAdapterInterface {
15
+ public:
16
+ virtual size_t size() const = 0;
17
+ virtual size_t read(uint64_t pos, void* buf, size_t n, const char* what = "")
18
+ const = 0;
19
+ virtual ~ReadAdapterInterface();
20
+ };
21
+
22
+ } // namespace serialize
23
+ } // namespace caffe2
videollama2/lib/python3.10/site-packages/torch/include/caffe2/serialize/versions.h ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <cstdint>
3
+
4
+ namespace caffe2 {
5
+ namespace serialize {
6
+
7
+ constexpr uint64_t kMinSupportedFileFormatVersion = 0x1L;
8
+
9
+ constexpr uint64_t kMaxSupportedFileFormatVersion = 0xAL;
10
+
11
+ // Versions (i.e. why was the version number bumped?)
12
+
13
+ // Note [Dynamic Versions and torch.jit.save vs. torch.save]
14
+ //
15
+ // Our versioning scheme has a "produced file format version" which
16
+ // describes how an archive is to be read. The version written in an archive
17
+ // is at least this current produced file format version, but may be greater
18
+ // if it includes certain symbols. We refer to these conditional versions
19
+ // as "dynamic," since they are identified at runtime.
20
+ //
21
+ // Dynamic versioning is useful when an operator's semantics are updated.
22
+ // When using torch.jit.save we want those semantics to be preserved. If
23
+ // we bumped the produced file format version on every change, however,
24
+ // then older versions of PyTorch couldn't read even simple archives, like
25
+ // a single tensor, from newer versions of PyTorch. Instead, we
26
+ // assign dynamic versions to these changes that override the
27
+ // produced file format version as needed. That is, when the semantics
28
+ // of torch.div changed it was assigned dynamic version 4, and when
29
+ // torch.jit.saving modules that use torch.div those archives also have
30
+ // (at least) version 4. This prevents earlier versions of PyTorch
31
+ // from accidentally performing the wrong kind of division. Modules
32
+ // that don't use torch.div or other operators with dynamic versions
33
+ // can write the produced file format version, and these programs will
34
+ // run as expected on earlier versions of PyTorch.
35
+ //
36
+ // While torch.jit.save attempts to preserve operator semantics,
37
+ // torch.save does not. torch.save is analogous to pickling Python, so
38
+ // a function that uses torch.div will have different behavior if torch.saved
39
+ // and torch.loaded across PyTorch versions. From a technical perspective,
40
+ // torch.save ignores dynamic versioning.
41
+
42
+ // 1. Initial version
43
+ // 2. Removed op_version_set version numbers
44
+ // 3. Added type tags to pickle serialization of container types
45
+ // 4. (Dynamic) Stopped integer division using torch.div
46
+ // (a versioned symbol preserves the historic behavior of versions 1--3)
47
+ // 5. (Dynamic) Stops torch.full inferring a floating point dtype
48
+ // when given bool or integer fill values.
49
+ // 6. Write version string to `./data/version` instead of `version`.
50
+
51
+ // [12/15/2021]
52
+ // kProducedFileFormatVersion is set to 7 from 3 due to a different
53
+ // interpretation of what file format version is.
54
+ // Whenever there is new upgrader introduced,
55
+ // this number should be bumped.
56
+ // The reasons that version is bumped in the past:
57
+ // 1. aten::div is changed at version 4
58
+ // 2. aten::full is changed at version 5
59
+ // 3. torch.package uses version 6
60
+ // 4. Introduce new upgrader design and set the version number to 7
61
+ // mark this change
62
+ // --------------------------------------------------
63
+ // We describe new operator version bump reasons here:
64
+ // 1) [01/24/2022]
65
+ // We bump the version number to 8 to update aten::linspace
66
+ // and aten::linspace.out to error out when steps is not
67
+ // provided. (see: https://github.com/pytorch/pytorch/issues/55951)
68
+ // 2) [01/30/2022]
69
+ // Bump the version number to 9 to update aten::logspace and
70
+ // and aten::logspace.out to error out when steps is not
71
+ // provided. (see: https://github.com/pytorch/pytorch/issues/55951)
72
+ // 3) [02/11/2022]
73
+ // Bump the version number to 10 to update aten::gelu and
74
+ // and aten::gelu.out to support the new approximate kwarg.
75
+ // (see: https://github.com/pytorch/pytorch/pull/61439)
76
+ constexpr uint64_t kProducedFileFormatVersion = 0xAL;
77
+
78
+ // Absolute minimum version we will write packages. This
79
+ // means that every package from now on will always be
80
+ // greater than this number.
81
+ constexpr uint64_t kMinProducedFileFormatVersion = 0x3L;
82
+
83
+ // The version we write when the archive contains bytecode.
84
+ // It must be higher or eq to kProducedFileFormatVersion.
85
+ // Because torchscript changes is likely introduce bytecode change.
86
+ // If kProducedFileFormatVersion is increased, kProducedBytecodeVersion
87
+ // should be increased too. The relationship is:
88
+ // kMaxSupportedFileFormatVersion >= (most likely ==) kProducedBytecodeVersion
89
+ // >= kProducedFileFormatVersion
90
+ // If a format change is forward compatible (still readable by older
91
+ // executables), we will not increment the version number, to minimize the
92
+ // risk of breaking existing clients. TODO: A better way would be to allow
93
+ // the caller that creates a model to specify a maximum version that its
94
+ // clients can accept.
95
+ // Versions:
96
+ // 0x1L: Initial version
97
+ // 0x2L: (Comment missing)
98
+ // 0x3L: (Comment missing)
99
+ // 0x4L: (update) Added schema to function tuple. Forward-compatible change.
100
+ // 0x5L: (update) Update bytecode is sharing constant tensor files from
101
+ // torchscript, and only serialize extra tensors that are not in the
102
+ // torchscript constant table. Also update tensor storage schema adapting to
103
+ // the unify format, the root key of tensor storage is updated from {index} to
104
+ // {the_pointer_value_the_tensor.storage}, for example:
105
+ // `140245072983168.storage` Forward-compatibility change.
106
+ // 0x6L: Implicit opereator versioning using number of specified argument.
107
+ // Refer to the summary of https://github.com/pytorch/pytorch/pull/56845 for
108
+ // details.
109
+ // 0x7L: Enable support for operators with default arguments plus out
110
+ // arguments. Refer. See https://github.com/pytorch/pytorch/pull/63651 for
111
+ // details.
112
+ // 0x8L: Emit promoted operators as instructions. See
113
+ // https://github.com/pytorch/pytorch/pull/71662 for details.
114
+ // 0x9L: Change serialization format from pickle to format This version is to
115
+ // serve migration. v8 pickle and v9 flatbuffer are the same. Refer to the
116
+ // summary of https://github.com/pytorch/pytorch/pull/75201 for more details.
117
+ constexpr uint64_t kProducedBytecodeVersion = 0x8L;
118
+
119
+ // static_assert(
120
+ // kProducedBytecodeVersion >= kProducedFileFormatVersion,
121
+ // "kProducedBytecodeVersion must be higher or equal to
122
+ // kProducedFileFormatVersion.");
123
+
124
+ // Introduce kMinSupportedBytecodeVersion and kMaxSupportedBytecodeVersion
125
+ // for limited backward/forward compatibility support of bytecode. If
126
+ // kMinSupportedBytecodeVersion <= model_version <= kMaxSupportedBytecodeVersion
127
+ // (in loader), we should support this model_version. For example, we provide a
128
+ // wrapper to handle an updated operator.
129
+ constexpr uint64_t kMinSupportedBytecodeVersion = 0x4L;
130
+ constexpr uint64_t kMaxSupportedBytecodeVersion = 0x9L;
131
+
132
+ } // namespace serialize
133
+ } // namespace caffe2
videollama2/lib/python3.10/site-packages/torch/include/pybind11/attr.h ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/attr.h: Infrastructure for processing custom
3
+ type and function attributes
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/common.h"
14
+ #include "cast.h"
15
+
16
+ #include <functional>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+
20
+ /// \addtogroup annotations
21
+ /// @{
22
+
23
+ /// Annotation for methods
24
+ struct is_method {
25
+ handle class_;
26
+ explicit is_method(const handle &c) : class_(c) {}
27
+ };
28
+
29
+ /// Annotation for setters
30
+ struct is_setter {};
31
+
32
+ /// Annotation for operators
33
+ struct is_operator {};
34
+
35
+ /// Annotation for classes that cannot be subclassed
36
+ struct is_final {};
37
+
38
+ /// Annotation for parent scope
39
+ struct scope {
40
+ handle value;
41
+ explicit scope(const handle &s) : value(s) {}
42
+ };
43
+
44
+ /// Annotation for documentation
45
+ struct doc {
46
+ const char *value;
47
+ explicit doc(const char *value) : value(value) {}
48
+ };
49
+
50
+ /// Annotation for function names
51
+ struct name {
52
+ const char *value;
53
+ explicit name(const char *value) : value(value) {}
54
+ };
55
+
56
+ /// Annotation indicating that a function is an overload associated with a given "sibling"
57
+ struct sibling {
58
+ handle value;
59
+ explicit sibling(const handle &value) : value(value.ptr()) {}
60
+ };
61
+
62
+ /// Annotation indicating that a class derives from another given type
63
+ template <typename T>
64
+ struct base {
65
+
66
+ PYBIND11_DEPRECATED(
67
+ "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
68
+ base() = default;
69
+ };
70
+
71
+ /// Keep patient alive while nurse lives
72
+ template <size_t Nurse, size_t Patient>
73
+ struct keep_alive {};
74
+
75
+ /// Annotation indicating that a class is involved in a multiple inheritance relationship
76
+ struct multiple_inheritance {};
77
+
78
+ /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
79
+ struct dynamic_attr {};
80
+
81
+ /// Annotation which enables the buffer protocol for a type
82
+ struct buffer_protocol {};
83
+
84
+ /// Annotation which requests that a special metaclass is created for a type
85
+ struct metaclass {
86
+ handle value;
87
+
88
+ PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
89
+ metaclass() = default;
90
+
91
+ /// Override pybind11's default metaclass
92
+ explicit metaclass(handle value) : value(value) {}
93
+ };
94
+
95
+ /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
96
+ /// may be used to customize the Python type.
97
+ ///
98
+ /// The callback is invoked immediately before `PyType_Ready`.
99
+ ///
100
+ /// Note: This is an advanced interface, and uses of it may require changes to
101
+ /// work with later versions of pybind11. You may wish to consult the
102
+ /// implementation of `make_new_python_type` in `detail/classes.h` to understand
103
+ /// the context in which the callback will be run.
104
+ struct custom_type_setup {
105
+ using callback = std::function<void(PyHeapTypeObject *heap_type)>;
106
+
107
+ explicit custom_type_setup(callback value) : value(std::move(value)) {}
108
+
109
+ callback value;
110
+ };
111
+
112
+ /// Annotation that marks a class as local to the module:
113
+ struct module_local {
114
+ const bool value;
115
+ constexpr explicit module_local(bool v = true) : value(v) {}
116
+ };
117
+
118
+ /// Annotation to mark enums as an arithmetic type
119
+ struct arithmetic {};
120
+
121
+ /// Mark a function for addition at the beginning of the existing overload chain instead of the end
122
+ struct prepend {};
123
+
124
+ /** \rst
125
+ A call policy which places one or more guard variables (``Ts...``) around the function call.
126
+
127
+ For example, this definition:
128
+
129
+ .. code-block:: cpp
130
+
131
+ m.def("foo", foo, py::call_guard<T>());
132
+
133
+ is equivalent to the following pseudocode:
134
+
135
+ .. code-block:: cpp
136
+
137
+ m.def("foo", [](args...) {
138
+ T scope_guard;
139
+ return foo(args...); // forwarded arguments
140
+ });
141
+ \endrst */
142
+ template <typename... Ts>
143
+ struct call_guard;
144
+
145
+ template <>
146
+ struct call_guard<> {
147
+ using type = detail::void_type;
148
+ };
149
+
150
+ template <typename T>
151
+ struct call_guard<T> {
152
+ static_assert(std::is_default_constructible<T>::value,
153
+ "The guard type must be default constructible");
154
+
155
+ using type = T;
156
+ };
157
+
158
+ template <typename T, typename... Ts>
159
+ struct call_guard<T, Ts...> {
160
+ struct type {
161
+ T guard{}; // Compose multiple guard types with left-to-right default-constructor order
162
+ typename call_guard<Ts...>::type next{};
163
+ };
164
+ };
165
+
166
+ /// @} annotations
167
+
168
+ PYBIND11_NAMESPACE_BEGIN(detail)
169
+ /* Forward declarations */
170
+ enum op_id : int;
171
+ enum op_type : int;
172
+ struct undefined_t;
173
+ template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
174
+ struct op_;
175
+ void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
176
+
177
+ /// Internal data structure which holds metadata about a keyword argument
178
+ struct argument_record {
179
+ const char *name; ///< Argument name
180
+ const char *descr; ///< Human-readable version of the argument value
181
+ handle value; ///< Associated Python object
182
+ bool convert : 1; ///< True if the argument is allowed to convert when loading
183
+ bool none : 1; ///< True if None is allowed when loading
184
+
185
+ argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
186
+ : name(name), descr(descr), value(value), convert(convert), none(none) {}
187
+ };
188
+
189
+ /// Internal data structure which holds metadata about a bound function (signature, overloads,
190
+ /// etc.)
191
+ struct function_record {
192
+ function_record()
193
+ : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
194
+ is_operator(false), is_method(false), is_setter(false), has_args(false),
195
+ has_kwargs(false), prepend(false) {}
196
+
197
+ /// Function name
198
+ char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
199
+
200
+ // User-specified documentation string
201
+ char *doc = nullptr;
202
+
203
+ /// Human-readable version of the function signature
204
+ char *signature = nullptr;
205
+
206
+ /// List of registered keyword arguments
207
+ std::vector<argument_record> args;
208
+
209
+ /// Pointer to lambda function which converts arguments and performs the actual call
210
+ handle (*impl)(function_call &) = nullptr;
211
+
212
+ /// Storage for the wrapped function pointer and captured data, if any
213
+ void *data[3] = {};
214
+
215
+ /// Pointer to custom destructor for 'data' (if needed)
216
+ void (*free_data)(function_record *ptr) = nullptr;
217
+
218
+ /// Return value policy associated with this function
219
+ return_value_policy policy = return_value_policy::automatic;
220
+
221
+ /// True if name == '__init__'
222
+ bool is_constructor : 1;
223
+
224
+ /// True if this is a new-style `__init__` defined in `detail/init.h`
225
+ bool is_new_style_constructor : 1;
226
+
227
+ /// True if this is a stateless function pointer
228
+ bool is_stateless : 1;
229
+
230
+ /// True if this is an operator (__add__), etc.
231
+ bool is_operator : 1;
232
+
233
+ /// True if this is a method
234
+ bool is_method : 1;
235
+
236
+ /// True if this is a setter
237
+ bool is_setter : 1;
238
+
239
+ /// True if the function has a '*args' argument
240
+ bool has_args : 1;
241
+
242
+ /// True if the function has a '**kwargs' argument
243
+ bool has_kwargs : 1;
244
+
245
+ /// True if this function is to be inserted at the beginning of the overload resolution chain
246
+ bool prepend : 1;
247
+
248
+ /// Number of arguments (including py::args and/or py::kwargs, if present)
249
+ std::uint16_t nargs;
250
+
251
+ /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
252
+ /// argument or by a py::kw_only annotation.
253
+ std::uint16_t nargs_pos = 0;
254
+
255
+ /// Number of leading arguments (counted in `nargs`) that are positional-only
256
+ std::uint16_t nargs_pos_only = 0;
257
+
258
+ /// Python method object
259
+ PyMethodDef *def = nullptr;
260
+
261
+ /// Python handle to the parent scope (a class or a module)
262
+ handle scope;
263
+
264
+ /// Python handle to the sibling function representing an overload chain
265
+ handle sibling;
266
+
267
+ /// Pointer to next overload
268
+ function_record *next = nullptr;
269
+ };
270
+
271
+ /// Special data structure which (temporarily) holds metadata about a bound class
272
+ struct type_record {
273
+ PYBIND11_NOINLINE type_record()
274
+ : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
275
+ default_holder(true), module_local(false), is_final(false) {}
276
+
277
+ /// Handle to the parent scope
278
+ handle scope;
279
+
280
+ /// Name of the class
281
+ const char *name = nullptr;
282
+
283
+ // Pointer to RTTI type_info data structure
284
+ const std::type_info *type = nullptr;
285
+
286
+ /// How large is the underlying C++ type?
287
+ size_t type_size = 0;
288
+
289
+ /// What is the alignment of the underlying C++ type?
290
+ size_t type_align = 0;
291
+
292
+ /// How large is the type's holder?
293
+ size_t holder_size = 0;
294
+
295
+ /// The global operator new can be overridden with a class-specific variant
296
+ void *(*operator_new)(size_t) = nullptr;
297
+
298
+ /// Function pointer to class_<..>::init_instance
299
+ void (*init_instance)(instance *, const void *) = nullptr;
300
+
301
+ /// Function pointer to class_<..>::dealloc
302
+ void (*dealloc)(detail::value_and_holder &) = nullptr;
303
+
304
+ /// List of base classes of the newly created type
305
+ list bases;
306
+
307
+ /// Optional docstring
308
+ const char *doc = nullptr;
309
+
310
+ /// Custom metaclass (optional)
311
+ handle metaclass;
312
+
313
+ /// Custom type setup.
314
+ custom_type_setup::callback custom_type_setup_callback;
315
+
316
+ /// Multiple inheritance marker
317
+ bool multiple_inheritance : 1;
318
+
319
+ /// Does the class manage a __dict__?
320
+ bool dynamic_attr : 1;
321
+
322
+ /// Does the class implement the buffer protocol?
323
+ bool buffer_protocol : 1;
324
+
325
+ /// Is the default (unique_ptr) holder type used?
326
+ bool default_holder : 1;
327
+
328
+ /// Is the class definition local to the module shared object?
329
+ bool module_local : 1;
330
+
331
+ /// Is the class inheritable from python classes?
332
+ bool is_final : 1;
333
+
334
+ PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
335
+ auto *base_info = detail::get_type_info(base, false);
336
+ if (!base_info) {
337
+ std::string tname(base.name());
338
+ detail::clean_type_id(tname);
339
+ pybind11_fail("generic_type: type \"" + std::string(name)
340
+ + "\" referenced unknown base type \"" + tname + "\"");
341
+ }
342
+
343
+ if (default_holder != base_info->default_holder) {
344
+ std::string tname(base.name());
345
+ detail::clean_type_id(tname);
346
+ pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
347
+ + (default_holder ? "does not have" : "has")
348
+ + " a non-default holder type while its base \"" + tname + "\" "
349
+ + (base_info->default_holder ? "does not" : "does"));
350
+ }
351
+
352
+ bases.append((PyObject *) base_info->type);
353
+
354
+ #if PY_VERSION_HEX < 0x030B0000
355
+ dynamic_attr |= base_info->type->tp_dictoffset != 0;
356
+ #else
357
+ dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0;
358
+ #endif
359
+
360
+ if (caster) {
361
+ base_info->implicit_casts.emplace_back(type, caster);
362
+ }
363
+ }
364
+ };
365
+
366
+ inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
367
+ args.reserve(f.nargs);
368
+ args_convert.reserve(f.nargs);
369
+ }
370
+
371
+ /// Tag for a new-style `__init__` defined in `detail/init.h`
372
+ struct is_new_style_constructor {};
373
+
374
+ /**
375
+ * Partial template specializations to process custom attributes provided to
376
+ * cpp_function_ and class_. These are either used to initialize the respective
377
+ * fields in the type_record and function_record data structures or executed at
378
+ * runtime to deal with custom call policies (e.g. keep_alive).
379
+ */
380
+ template <typename T, typename SFINAE = void>
381
+ struct process_attribute;
382
+
383
+ template <typename T>
384
+ struct process_attribute_default {
385
+ /// Default implementation: do nothing
386
+ static void init(const T &, function_record *) {}
387
+ static void init(const T &, type_record *) {}
388
+ static void precall(function_call &) {}
389
+ static void postcall(function_call &, handle) {}
390
+ };
391
+
392
+ /// Process an attribute specifying the function's name
393
+ template <>
394
+ struct process_attribute<name> : process_attribute_default<name> {
395
+ static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
396
+ };
397
+
398
+ /// Process an attribute specifying the function's docstring
399
+ template <>
400
+ struct process_attribute<doc> : process_attribute_default<doc> {
401
+ static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
402
+ };
403
+
404
+ /// Process an attribute specifying the function's docstring (provided as a C-style string)
405
+ template <>
406
+ struct process_attribute<const char *> : process_attribute_default<const char *> {
407
+ static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
408
+ static void init(const char *d, type_record *r) { r->doc = d; }
409
+ };
410
+ template <>
411
+ struct process_attribute<char *> : process_attribute<const char *> {};
412
+
413
+ /// Process an attribute indicating the function's return value policy
414
+ template <>
415
+ struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
416
+ static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
417
+ };
418
+
419
+ /// Process an attribute which indicates that this is an overloaded function associated with a
420
+ /// given sibling
421
+ template <>
422
+ struct process_attribute<sibling> : process_attribute_default<sibling> {
423
+ static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
424
+ };
425
+
426
+ /// Process an attribute which indicates that this function is a method
427
+ template <>
428
+ struct process_attribute<is_method> : process_attribute_default<is_method> {
429
+ static void init(const is_method &s, function_record *r) {
430
+ r->is_method = true;
431
+ r->scope = s.class_;
432
+ }
433
+ };
434
+
435
+ /// Process an attribute which indicates that this function is a setter
436
+ template <>
437
+ struct process_attribute<is_setter> : process_attribute_default<is_setter> {
438
+ static void init(const is_setter &, function_record *r) { r->is_setter = true; }
439
+ };
440
+
441
+ /// Process an attribute which indicates the parent scope of a method
442
+ template <>
443
+ struct process_attribute<scope> : process_attribute_default<scope> {
444
+ static void init(const scope &s, function_record *r) { r->scope = s.value; }
445
+ };
446
+
447
+ /// Process an attribute which indicates that this function is an operator
448
+ template <>
449
+ struct process_attribute<is_operator> : process_attribute_default<is_operator> {
450
+ static void init(const is_operator &, function_record *r) { r->is_operator = true; }
451
+ };
452
+
453
+ template <>
454
+ struct process_attribute<is_new_style_constructor>
455
+ : process_attribute_default<is_new_style_constructor> {
456
+ static void init(const is_new_style_constructor &, function_record *r) {
457
+ r->is_new_style_constructor = true;
458
+ }
459
+ };
460
+
461
+ inline void check_kw_only_arg(const arg &a, function_record *r) {
462
+ if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
463
+ pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
464
+ "args() argument");
465
+ }
466
+ }
467
+
468
+ inline void append_self_arg_if_needed(function_record *r) {
469
+ if (r->is_method && r->args.empty()) {
470
+ r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
471
+ }
472
+ }
473
+
474
+ /// Process a keyword argument attribute (*without* a default value)
475
+ template <>
476
+ struct process_attribute<arg> : process_attribute_default<arg> {
477
+ static void init(const arg &a, function_record *r) {
478
+ append_self_arg_if_needed(r);
479
+ r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
480
+
481
+ check_kw_only_arg(a, r);
482
+ }
483
+ };
484
+
485
+ /// Process a keyword argument attribute (*with* a default value)
486
+ template <>
487
+ struct process_attribute<arg_v> : process_attribute_default<arg_v> {
488
+ static void init(const arg_v &a, function_record *r) {
489
+ if (r->is_method && r->args.empty()) {
490
+ r->args.emplace_back(
491
+ "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
492
+ }
493
+
494
+ if (!a.value) {
495
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
496
+ std::string descr("'");
497
+ if (a.name) {
498
+ descr += std::string(a.name) + ": ";
499
+ }
500
+ descr += a.type + "'";
501
+ if (r->is_method) {
502
+ if (r->name) {
503
+ descr += " in method '" + (std::string) str(r->scope) + "."
504
+ + (std::string) r->name + "'";
505
+ } else {
506
+ descr += " in method of '" + (std::string) str(r->scope) + "'";
507
+ }
508
+ } else if (r->name) {
509
+ descr += " in function '" + (std::string) r->name + "'";
510
+ }
511
+ pybind11_fail("arg(): could not convert default argument " + descr
512
+ + " into a Python object (type not registered yet?)");
513
+ #else
514
+ pybind11_fail("arg(): could not convert default argument "
515
+ "into a Python object (type not registered yet?). "
516
+ "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
517
+ "more information.");
518
+ #endif
519
+ }
520
+ r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
521
+
522
+ check_kw_only_arg(a, r);
523
+ }
524
+ };
525
+
526
+ /// Process a keyword-only-arguments-follow pseudo argument
527
+ template <>
528
+ struct process_attribute<kw_only> : process_attribute_default<kw_only> {
529
+ static void init(const kw_only &, function_record *r) {
530
+ append_self_arg_if_needed(r);
531
+ if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
532
+ pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
533
+ "argument location (or omit kw_only() entirely)");
534
+ }
535
+ r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
536
+ }
537
+ };
538
+
539
+ /// Process a positional-only-argument maker
540
+ template <>
541
+ struct process_attribute<pos_only> : process_attribute_default<pos_only> {
542
+ static void init(const pos_only &, function_record *r) {
543
+ append_self_arg_if_needed(r);
544
+ r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
545
+ if (r->nargs_pos_only > r->nargs_pos) {
546
+ pybind11_fail("pos_only(): cannot follow a py::args() argument");
547
+ }
548
+ // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
549
+ }
550
+ };
551
+
552
+ /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
553
+ /// that)
554
+ template <typename T>
555
+ struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
556
+ : process_attribute_default<handle> {
557
+ static void init(const handle &h, type_record *r) { r->bases.append(h); }
558
+ };
559
+
560
+ /// Process a parent class attribute (deprecated, does not support multiple inheritance)
561
+ template <typename T>
562
+ struct process_attribute<base<T>> : process_attribute_default<base<T>> {
563
+ static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
564
+ };
565
+
566
+ /// Process a multiple inheritance attribute
567
+ template <>
568
+ struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
569
+ static void init(const multiple_inheritance &, type_record *r) {
570
+ r->multiple_inheritance = true;
571
+ }
572
+ };
573
+
574
+ template <>
575
+ struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
576
+ static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
577
+ };
578
+
579
+ template <>
580
+ struct process_attribute<custom_type_setup> {
581
+ static void init(const custom_type_setup &value, type_record *r) {
582
+ r->custom_type_setup_callback = value.value;
583
+ }
584
+ };
585
+
586
+ template <>
587
+ struct process_attribute<is_final> : process_attribute_default<is_final> {
588
+ static void init(const is_final &, type_record *r) { r->is_final = true; }
589
+ };
590
+
591
+ template <>
592
+ struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
593
+ static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
594
+ };
595
+
596
+ template <>
597
+ struct process_attribute<metaclass> : process_attribute_default<metaclass> {
598
+ static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
599
+ };
600
+
601
+ template <>
602
+ struct process_attribute<module_local> : process_attribute_default<module_local> {
603
+ static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
604
+ };
605
+
606
+ /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
607
+ template <>
608
+ struct process_attribute<prepend> : process_attribute_default<prepend> {
609
+ static void init(const prepend &, function_record *r) { r->prepend = true; }
610
+ };
611
+
612
+ /// Process an 'arithmetic' attribute for enums (does nothing here)
613
+ template <>
614
+ struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
615
+
616
+ template <typename... Ts>
617
+ struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
618
+
619
+ /**
620
+ * Process a keep_alive call policy -- invokes keep_alive_impl during the
621
+ * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
622
+ * otherwise
623
+ */
624
+ template <size_t Nurse, size_t Patient>
625
+ struct process_attribute<keep_alive<Nurse, Patient>>
626
+ : public process_attribute_default<keep_alive<Nurse, Patient>> {
627
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
628
+ static void precall(function_call &call) {
629
+ keep_alive_impl(Nurse, Patient, call, handle());
630
+ }
631
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
632
+ static void postcall(function_call &, handle) {}
633
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
634
+ static void precall(function_call &) {}
635
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
636
+ static void postcall(function_call &call, handle ret) {
637
+ keep_alive_impl(Nurse, Patient, call, ret);
638
+ }
639
+ };
640
+
641
+ /// Recursively iterate over variadic template arguments
642
+ template <typename... Args>
643
+ struct process_attributes {
644
+ static void init(const Args &...args, function_record *r) {
645
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
646
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
647
+ using expander = int[];
648
+ (void) expander{
649
+ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
650
+ }
651
+ static void init(const Args &...args, type_record *r) {
652
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
653
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
654
+ using expander = int[];
655
+ (void) expander{0,
656
+ (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
657
+ }
658
+ static void precall(function_call &call) {
659
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
660
+ using expander = int[];
661
+ (void) expander{0,
662
+ (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
663
+ }
664
+ static void postcall(function_call &call, handle fn_ret) {
665
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
666
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
667
+ using expander = int[];
668
+ (void) expander{
669
+ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
670
+ }
671
+ };
672
+
673
+ template <typename T>
674
+ using is_call_guard = is_instantiation<call_guard, T>;
675
+
676
+ /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
677
+ template <typename... Extra>
678
+ using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
679
+
680
+ /// Check the number of named arguments at compile time
681
+ template <typename... Extra,
682
+ size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
683
+ size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
684
+ constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
685
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
686
+ return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
687
+ }
688
+
689
+ PYBIND11_NAMESPACE_END(detail)
690
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/buffer_info.h ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/buffer_info.h: Python buffer object interface
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ // Default, C-style strides
19
+ inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
20
+ auto ndim = shape.size();
21
+ std::vector<ssize_t> strides(ndim, itemsize);
22
+ if (ndim > 0) {
23
+ for (size_t i = ndim - 1; i > 0; --i) {
24
+ strides[i - 1] = strides[i] * shape[i];
25
+ }
26
+ }
27
+ return strides;
28
+ }
29
+
30
+ // F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
31
+ inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
32
+ auto ndim = shape.size();
33
+ std::vector<ssize_t> strides(ndim, itemsize);
34
+ for (size_t i = 1; i < ndim; ++i) {
35
+ strides[i] = strides[i - 1] * shape[i - 1];
36
+ }
37
+ return strides;
38
+ }
39
+
40
+ template <typename T, typename SFINAE = void>
41
+ struct compare_buffer_info;
42
+
43
+ PYBIND11_NAMESPACE_END(detail)
44
+
45
+ /// Information record describing a Python buffer object
46
+ struct buffer_info {
47
+ void *ptr = nullptr; // Pointer to the underlying storage
48
+ ssize_t itemsize = 0; // Size of individual items in bytes
49
+ ssize_t size = 0; // Total number of entries
50
+ std::string format; // For homogeneous buffers, this should be set to
51
+ // format_descriptor<T>::format()
52
+ ssize_t ndim = 0; // Number of dimensions
53
+ std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension)
54
+ std::vector<ssize_t> strides; // Number of bytes between adjacent entries
55
+ // (for each per dimension)
56
+ bool readonly = false; // flag to indicate if the underlying storage may be written to
57
+
58
+ buffer_info() = default;
59
+
60
+ buffer_info(void *ptr,
61
+ ssize_t itemsize,
62
+ const std::string &format,
63
+ ssize_t ndim,
64
+ detail::any_container<ssize_t> shape_in,
65
+ detail::any_container<ssize_t> strides_in,
66
+ bool readonly = false)
67
+ : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
68
+ shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
69
+ if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) {
70
+ pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
71
+ }
72
+ for (size_t i = 0; i < (size_t) ndim; ++i) {
73
+ size *= shape[i];
74
+ }
75
+ }
76
+
77
+ template <typename T>
78
+ buffer_info(T *ptr,
79
+ detail::any_container<ssize_t> shape_in,
80
+ detail::any_container<ssize_t> strides_in,
81
+ bool readonly = false)
82
+ : buffer_info(private_ctr_tag(),
83
+ ptr,
84
+ sizeof(T),
85
+ format_descriptor<T>::format(),
86
+ static_cast<ssize_t>(shape_in->size()),
87
+ std::move(shape_in),
88
+ std::move(strides_in),
89
+ readonly) {}
90
+
91
+ buffer_info(void *ptr,
92
+ ssize_t itemsize,
93
+ const std::string &format,
94
+ ssize_t size,
95
+ bool readonly = false)
96
+ : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}
97
+
98
+ template <typename T>
99
+ buffer_info(T *ptr, ssize_t size, bool readonly = false)
100
+ : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}
101
+
102
+ template <typename T>
103
+ buffer_info(const T *ptr, ssize_t size, bool readonly = true)
104
+ : buffer_info(
105
+ const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}
106
+
107
+ explicit buffer_info(Py_buffer *view, bool ownview = true)
108
+ : buffer_info(
109
+ view->buf,
110
+ view->itemsize,
111
+ view->format,
112
+ view->ndim,
113
+ {view->shape, view->shape + view->ndim},
114
+ /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
115
+ * ignore this flag and return a view with NULL strides.
116
+ * When strides are NULL, build them manually. */
117
+ view->strides
118
+ ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
119
+ : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
120
+ (view->readonly != 0)) {
121
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
122
+ this->m_view = view;
123
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
124
+ this->ownview = ownview;
125
+ }
126
+
127
+ buffer_info(const buffer_info &) = delete;
128
+ buffer_info &operator=(const buffer_info &) = delete;
129
+
130
+ buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
131
+
132
+ buffer_info &operator=(buffer_info &&rhs) noexcept {
133
+ ptr = rhs.ptr;
134
+ itemsize = rhs.itemsize;
135
+ size = rhs.size;
136
+ format = std::move(rhs.format);
137
+ ndim = rhs.ndim;
138
+ shape = std::move(rhs.shape);
139
+ strides = std::move(rhs.strides);
140
+ std::swap(m_view, rhs.m_view);
141
+ std::swap(ownview, rhs.ownview);
142
+ readonly = rhs.readonly;
143
+ return *this;
144
+ }
145
+
146
+ ~buffer_info() {
147
+ if (m_view && ownview) {
148
+ PyBuffer_Release(m_view);
149
+ delete m_view;
150
+ }
151
+ }
152
+
153
+ Py_buffer *view() const { return m_view; }
154
+ Py_buffer *&view() { return m_view; }
155
+
156
+ /* True if the buffer item type is equivalent to `T`. */
157
+ // To define "equivalent" by example:
158
+ // `buffer_info::item_type_is_equivalent_to<int>(b)` and
159
+ // `buffer_info::item_type_is_equivalent_to<long>(b)` may both be true
160
+ // on some platforms, but `int` and `unsigned` will never be equivalent.
161
+ // For the ground truth, please inspect `detail::compare_buffer_info<>`.
162
+ template <typename T>
163
+ bool item_type_is_equivalent_to() const {
164
+ return detail::compare_buffer_info<T>::compare(*this);
165
+ }
166
+
167
+ private:
168
+ struct private_ctr_tag {};
169
+
170
+ buffer_info(private_ctr_tag,
171
+ void *ptr,
172
+ ssize_t itemsize,
173
+ const std::string &format,
174
+ ssize_t ndim,
175
+ detail::any_container<ssize_t> &&shape_in,
176
+ detail::any_container<ssize_t> &&strides_in,
177
+ bool readonly)
178
+ : buffer_info(
179
+ ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}
180
+
181
+ Py_buffer *m_view = nullptr;
182
+ bool ownview = false;
183
+ };
184
+
185
+ PYBIND11_NAMESPACE_BEGIN(detail)
186
+
187
+ template <typename T, typename SFINAE>
188
+ struct compare_buffer_info {
189
+ static bool compare(const buffer_info &b) {
190
+ // NOLINTNEXTLINE(bugprone-sizeof-expression) Needed for `PyObject *`
191
+ return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
192
+ }
193
+ };
194
+
195
+ template <typename T>
196
+ struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
197
+ static bool compare(const buffer_info &b) {
198
+ return (size_t) b.itemsize == sizeof(T)
199
+ && (b.format == format_descriptor<T>::value
200
+ || ((sizeof(T) == sizeof(long))
201
+ && b.format == (std::is_unsigned<T>::value ? "L" : "l"))
202
+ || ((sizeof(T) == sizeof(size_t))
203
+ && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
204
+ }
205
+ };
206
+
207
+ PYBIND11_NAMESPACE_END(detail)
208
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/cast.h ADDED
@@ -0,0 +1,1704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/cast.h: Partial template specializations to cast between
3
+ C++ and Python types
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/common.h"
14
+ #include "detail/descr.h"
15
+ #include "detail/type_caster_base.h"
16
+ #include "detail/typeid.h"
17
+ #include "pytypes.h"
18
+
19
+ #include <array>
20
+ #include <cstring>
21
+ #include <functional>
22
+ #include <iosfwd>
23
+ #include <iterator>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <tuple>
27
+ #include <type_traits>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
32
+
33
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
34
+
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ template <typename type, typename SFINAE = void>
38
+ class type_caster : public type_caster_base<type> {};
39
+ template <typename type>
40
+ using make_caster = type_caster<intrinsic_t<type>>;
41
+
42
+ // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
43
+ template <typename T>
44
+ typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
45
+ return caster.operator typename make_caster<T>::template cast_op_type<T>();
46
+ }
47
+ template <typename T>
48
+ typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
49
+ cast_op(make_caster<T> &&caster) {
50
+ return std::move(caster).operator typename make_caster<T>::
51
+ template cast_op_type<typename std::add_rvalue_reference<T>::type>();
52
+ }
53
+
54
+ template <typename type>
55
+ class type_caster<std::reference_wrapper<type>> {
56
+ private:
57
+ using caster_t = make_caster<type>;
58
+ caster_t subcaster;
59
+ using reference_t = type &;
60
+ using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
61
+
62
+ static_assert(
63
+ std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
64
+ || std::is_same<reference_t, subcaster_cast_op_type>::value,
65
+ "std::reference_wrapper<T> caster requires T to have a caster with an "
66
+ "`operator T &()` or `operator const T &()`");
67
+
68
+ public:
69
+ bool load(handle src, bool convert) { return subcaster.load(src, convert); }
70
+ static constexpr auto name = caster_t::name;
71
+ static handle
72
+ cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
73
+ // It is definitely wrong to take ownership of this pointer, so mask that rvp
74
+ if (policy == return_value_policy::take_ownership
75
+ || policy == return_value_policy::automatic) {
76
+ policy = return_value_policy::automatic_reference;
77
+ }
78
+ return caster_t::cast(&src.get(), policy, parent);
79
+ }
80
+ template <typename T>
81
+ using cast_op_type = std::reference_wrapper<type>;
82
+ explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
83
+ };
84
+
85
+ #define PYBIND11_TYPE_CASTER(type, py_name) \
86
+ protected: \
87
+ type value; \
88
+ \
89
+ public: \
90
+ static constexpr auto name = py_name; \
91
+ template <typename T_, \
92
+ ::pybind11::detail::enable_if_t< \
93
+ std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
94
+ int> \
95
+ = 0> \
96
+ static ::pybind11::handle cast( \
97
+ T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
98
+ if (!src) \
99
+ return ::pybind11::none().release(); \
100
+ if (policy == ::pybind11::return_value_policy::take_ownership) { \
101
+ auto h = cast(std::move(*src), policy, parent); \
102
+ delete src; \
103
+ return h; \
104
+ } \
105
+ return cast(*src, policy, parent); \
106
+ } \
107
+ operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
108
+ operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
109
+ operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
110
+ template <typename T_> \
111
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
112
+
113
+ template <typename CharT>
114
+ using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
115
+ #if defined(PYBIND11_HAS_U8STRING)
116
+ std::is_same<CharT, char8_t>, /* std::u8string */
117
+ #endif
118
+ std::is_same<CharT, char16_t>, /* std::u16string */
119
+ std::is_same<CharT, char32_t>, /* std::u32string */
120
+ std::is_same<CharT, wchar_t> /* std::wstring */
121
+ >;
122
+
123
+ template <typename T>
124
+ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
125
+ using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
126
+ using _py_type_1 = conditional_t<std::is_signed<T>::value,
127
+ _py_type_0,
128
+ typename std::make_unsigned<_py_type_0>::type>;
129
+ using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
130
+
131
+ public:
132
+ bool load(handle src, bool convert) {
133
+ py_type py_value;
134
+
135
+ if (!src) {
136
+ return false;
137
+ }
138
+
139
+ #if !defined(PYPY_VERSION)
140
+ auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
141
+ #else
142
+ // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
143
+ // while CPython only considers the existence of `nb_index`/`__index__`.
144
+ auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
145
+ #endif
146
+
147
+ if (std::is_floating_point<T>::value) {
148
+ if (convert || PyFloat_Check(src.ptr())) {
149
+ py_value = (py_type) PyFloat_AsDouble(src.ptr());
150
+ } else {
151
+ return false;
152
+ }
153
+ } else if (PyFloat_Check(src.ptr())
154
+ || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
155
+ return false;
156
+ } else {
157
+ handle src_or_index = src;
158
+ // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
159
+ #if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
160
+ object index;
161
+ if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
162
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
163
+ if (!index) {
164
+ PyErr_Clear();
165
+ if (!convert)
166
+ return false;
167
+ } else {
168
+ src_or_index = index;
169
+ }
170
+ }
171
+ #endif
172
+ if (std::is_unsigned<py_type>::value) {
173
+ py_value = as_unsigned<py_type>(src_or_index.ptr());
174
+ } else { // signed integer:
175
+ py_value = sizeof(T) <= sizeof(long)
176
+ ? (py_type) PyLong_AsLong(src_or_index.ptr())
177
+ : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
178
+ }
179
+ }
180
+
181
+ // Python API reported an error
182
+ bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
183
+
184
+ // Check to see if the conversion is valid (integers should match exactly)
185
+ // Signed/unsigned checks happen elsewhere
186
+ if (py_err
187
+ || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
188
+ && py_value != (py_type) (T) py_value)) {
189
+ PyErr_Clear();
190
+ if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
191
+ auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
192
+ ? PyNumber_Float(src.ptr())
193
+ : PyNumber_Long(src.ptr()));
194
+ PyErr_Clear();
195
+ return load(tmp, false);
196
+ }
197
+ return false;
198
+ }
199
+
200
+ value = (T) py_value;
201
+ return true;
202
+ }
203
+
204
+ template <typename U = T>
205
+ static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
206
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
207
+ return PyFloat_FromDouble((double) src);
208
+ }
209
+
210
+ template <typename U = T>
211
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
212
+ && (sizeof(U) <= sizeof(long)),
213
+ handle>::type
214
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
215
+ return PYBIND11_LONG_FROM_SIGNED((long) src);
216
+ }
217
+
218
+ template <typename U = T>
219
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
220
+ && (sizeof(U) <= sizeof(unsigned long)),
221
+ handle>::type
222
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
223
+ return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
224
+ }
225
+
226
+ template <typename U = T>
227
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
228
+ && (sizeof(U) > sizeof(long)),
229
+ handle>::type
230
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
231
+ return PyLong_FromLongLong((long long) src);
232
+ }
233
+
234
+ template <typename U = T>
235
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
236
+ && (sizeof(U) > sizeof(unsigned long)),
237
+ handle>::type
238
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
239
+ return PyLong_FromUnsignedLongLong((unsigned long long) src);
240
+ }
241
+
242
+ PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
243
+ };
244
+
245
+ template <typename T>
246
+ struct void_caster {
247
+ public:
248
+ bool load(handle src, bool) {
249
+ if (src && src.is_none()) {
250
+ return true;
251
+ }
252
+ return false;
253
+ }
254
+ static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
255
+ return none().release();
256
+ }
257
+ PYBIND11_TYPE_CASTER(T, const_name("None"));
258
+ };
259
+
260
+ template <>
261
+ class type_caster<void_type> : public void_caster<void_type> {};
262
+
263
+ template <>
264
+ class type_caster<void> : public type_caster<void_type> {
265
+ public:
266
+ using type_caster<void_type>::cast;
267
+
268
+ bool load(handle h, bool) {
269
+ if (!h) {
270
+ return false;
271
+ }
272
+ if (h.is_none()) {
273
+ value = nullptr;
274
+ return true;
275
+ }
276
+
277
+ /* Check if this is a capsule */
278
+ if (isinstance<capsule>(h)) {
279
+ value = reinterpret_borrow<capsule>(h);
280
+ return true;
281
+ }
282
+
283
+ /* Check if this is a C++ type */
284
+ const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
285
+ if (bases.size() == 1) { // Only allowing loading from a single-value type
286
+ value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
287
+ return true;
288
+ }
289
+
290
+ /* Fail */
291
+ return false;
292
+ }
293
+
294
+ static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
295
+ if (ptr) {
296
+ return capsule(ptr).release();
297
+ }
298
+ return none().release();
299
+ }
300
+
301
+ template <typename T>
302
+ using cast_op_type = void *&;
303
+ explicit operator void *&() { return value; }
304
+ static constexpr auto name = const_name("capsule");
305
+
306
+ private:
307
+ void *value = nullptr;
308
+ };
309
+
310
+ template <>
311
+ class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
312
+
313
+ template <>
314
+ class type_caster<bool> {
315
+ public:
316
+ bool load(handle src, bool convert) {
317
+ if (!src) {
318
+ return false;
319
+ }
320
+ if (src.ptr() == Py_True) {
321
+ value = true;
322
+ return true;
323
+ }
324
+ if (src.ptr() == Py_False) {
325
+ value = false;
326
+ return true;
327
+ }
328
+ if (convert || (std::strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name) == 0)) {
329
+ // (allow non-implicit conversion for numpy booleans)
330
+
331
+ Py_ssize_t res = -1;
332
+ if (src.is_none()) {
333
+ res = 0; // None is implicitly converted to False
334
+ }
335
+ #if defined(PYPY_VERSION)
336
+ // On PyPy, check that "__bool__" attr exists
337
+ else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
338
+ res = PyObject_IsTrue(src.ptr());
339
+ }
340
+ #else
341
+ // Alternate approach for CPython: this does the same as the above, but optimized
342
+ // using the CPython API so as to avoid an unneeded attribute lookup.
343
+ else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
344
+ if (PYBIND11_NB_BOOL(tp_as_number)) {
345
+ res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
346
+ }
347
+ }
348
+ #endif
349
+ if (res == 0 || res == 1) {
350
+ value = (res != 0);
351
+ return true;
352
+ }
353
+ PyErr_Clear();
354
+ }
355
+ return false;
356
+ }
357
+ static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
358
+ return handle(src ? Py_True : Py_False).inc_ref();
359
+ }
360
+ PYBIND11_TYPE_CASTER(bool, const_name("bool"));
361
+ };
362
+
363
+ // Helper class for UTF-{8,16,32} C++ stl strings:
364
+ template <typename StringType, bool IsView = false>
365
+ struct string_caster {
366
+ using CharT = typename StringType::value_type;
367
+
368
+ // Simplify life by being able to assume standard char sizes (the standard only guarantees
369
+ // minimums, but Python requires exact sizes)
370
+ static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
371
+ "Unsupported char size != 1");
372
+ #if defined(PYBIND11_HAS_U8STRING)
373
+ static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
374
+ "Unsupported char8_t size != 1");
375
+ #endif
376
+ static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
377
+ "Unsupported char16_t size != 2");
378
+ static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
379
+ "Unsupported char32_t size != 4");
380
+ // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
381
+ static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
382
+ "Unsupported wchar_t size != 2/4");
383
+ static constexpr size_t UTF_N = 8 * sizeof(CharT);
384
+
385
+ bool load(handle src, bool) {
386
+ handle load_src = src;
387
+ if (!src) {
388
+ return false;
389
+ }
390
+ if (!PyUnicode_Check(load_src.ptr())) {
391
+ return load_raw(load_src);
392
+ }
393
+
394
+ // For UTF-8 we avoid the need for a temporary `bytes` object by using
395
+ // `PyUnicode_AsUTF8AndSize`.
396
+ if (UTF_N == 8) {
397
+ Py_ssize_t size = -1;
398
+ const auto *buffer
399
+ = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
400
+ if (!buffer) {
401
+ PyErr_Clear();
402
+ return false;
403
+ }
404
+ value = StringType(buffer, static_cast<size_t>(size));
405
+ return true;
406
+ }
407
+
408
+ auto utfNbytes
409
+ = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
410
+ UTF_N == 8 ? "utf-8"
411
+ : UTF_N == 16 ? "utf-16"
412
+ : "utf-32",
413
+ nullptr));
414
+ if (!utfNbytes) {
415
+ PyErr_Clear();
416
+ return false;
417
+ }
418
+
419
+ const auto *buffer
420
+ = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
421
+ size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
422
+ // Skip BOM for UTF-16/32
423
+ if (UTF_N > 8) {
424
+ buffer++;
425
+ length--;
426
+ }
427
+ value = StringType(buffer, length);
428
+
429
+ // If we're loading a string_view we need to keep the encoded Python object alive:
430
+ if (IsView) {
431
+ loader_life_support::add_patient(utfNbytes);
432
+ }
433
+
434
+ return true;
435
+ }
436
+
437
+ static handle
438
+ cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
439
+ const char *buffer = reinterpret_cast<const char *>(src.data());
440
+ auto nbytes = ssize_t(src.size() * sizeof(CharT));
441
+ handle s = decode_utfN(buffer, nbytes);
442
+ if (!s) {
443
+ throw error_already_set();
444
+ }
445
+ return s;
446
+ }
447
+
448
+ PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
449
+
450
+ private:
451
+ static handle decode_utfN(const char *buffer, ssize_t nbytes) {
452
+ #if !defined(PYPY_VERSION)
453
+ return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
454
+ : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
455
+ : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
456
+ #else
457
+ // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
458
+ // well), so bypass the whole thing by just passing the encoding as a string value, which
459
+ // works properly:
460
+ return PyUnicode_Decode(buffer,
461
+ nbytes,
462
+ UTF_N == 8 ? "utf-8"
463
+ : UTF_N == 16 ? "utf-16"
464
+ : "utf-32",
465
+ nullptr);
466
+ #endif
467
+ }
468
+
469
+ // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
470
+ // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
471
+ // which supports loading a unicode from a str, doesn't take this path.
472
+ template <typename C = CharT>
473
+ bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
474
+ if (PYBIND11_BYTES_CHECK(src.ptr())) {
475
+ // We were passed raw bytes; accept it into a std::string or char*
476
+ // without any encoding attempt.
477
+ const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
478
+ if (!bytes) {
479
+ pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
480
+ }
481
+ value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
482
+ return true;
483
+ }
484
+ if (PyByteArray_Check(src.ptr())) {
485
+ // We were passed a bytearray; accept it into a std::string or char*
486
+ // without any encoding attempt.
487
+ const char *bytearray = PyByteArray_AsString(src.ptr());
488
+ if (!bytearray) {
489
+ pybind11_fail("Unexpected PyByteArray_AsString() failure.");
490
+ }
491
+ value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
492
+ return true;
493
+ }
494
+
495
+ return false;
496
+ }
497
+
498
+ template <typename C = CharT>
499
+ bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
500
+ return false;
501
+ }
502
+ };
503
+
504
+ template <typename CharT, class Traits, class Allocator>
505
+ struct type_caster<std::basic_string<CharT, Traits, Allocator>,
506
+ enable_if_t<is_std_char_type<CharT>::value>>
507
+ : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
508
+
509
+ #ifdef PYBIND11_HAS_STRING_VIEW
510
+ template <typename CharT, class Traits>
511
+ struct type_caster<std::basic_string_view<CharT, Traits>,
512
+ enable_if_t<is_std_char_type<CharT>::value>>
513
+ : string_caster<std::basic_string_view<CharT, Traits>, true> {};
514
+ #endif
515
+
516
+ // Type caster for C-style strings. We basically use a std::string type caster, but also add the
517
+ // ability to use None as a nullptr char* (which the string caster doesn't allow).
518
+ template <typename CharT>
519
+ struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
520
+ using StringType = std::basic_string<CharT>;
521
+ using StringCaster = make_caster<StringType>;
522
+ StringCaster str_caster;
523
+ bool none = false;
524
+ CharT one_char = 0;
525
+
526
+ public:
527
+ bool load(handle src, bool convert) {
528
+ if (!src) {
529
+ return false;
530
+ }
531
+ if (src.is_none()) {
532
+ // Defer accepting None to other overloads (if we aren't in convert mode):
533
+ if (!convert) {
534
+ return false;
535
+ }
536
+ none = true;
537
+ return true;
538
+ }
539
+ return str_caster.load(src, convert);
540
+ }
541
+
542
+ static handle cast(const CharT *src, return_value_policy policy, handle parent) {
543
+ if (src == nullptr) {
544
+ return pybind11::none().release();
545
+ }
546
+ return StringCaster::cast(StringType(src), policy, parent);
547
+ }
548
+
549
+ static handle cast(CharT src, return_value_policy policy, handle parent) {
550
+ if (std::is_same<char, CharT>::value) {
551
+ handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
552
+ if (!s) {
553
+ throw error_already_set();
554
+ }
555
+ return s;
556
+ }
557
+ return StringCaster::cast(StringType(1, src), policy, parent);
558
+ }
559
+
560
+ explicit operator CharT *() {
561
+ return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
562
+ }
563
+ explicit operator CharT &() {
564
+ if (none) {
565
+ throw value_error("Cannot convert None to a character");
566
+ }
567
+
568
+ auto &value = static_cast<StringType &>(str_caster);
569
+ size_t str_len = value.size();
570
+ if (str_len == 0) {
571
+ throw value_error("Cannot convert empty string to a character");
572
+ }
573
+
574
+ // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
575
+ // is too high, and one for multiple unicode characters (caught later), so we need to
576
+ // figure out how long the first encoded character is in bytes to distinguish between these
577
+ // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
578
+ // those can fit into a single char value.
579
+ if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
580
+ auto v0 = static_cast<unsigned char>(value[0]);
581
+ // low bits only: 0-127
582
+ // 0b110xxxxx - start of 2-byte sequence
583
+ // 0b1110xxxx - start of 3-byte sequence
584
+ // 0b11110xxx - start of 4-byte sequence
585
+ size_t char0_bytes = (v0 & 0x80) == 0 ? 1
586
+ : (v0 & 0xE0) == 0xC0 ? 2
587
+ : (v0 & 0xF0) == 0xE0 ? 3
588
+ : 4;
589
+
590
+ if (char0_bytes == str_len) {
591
+ // If we have a 128-255 value, we can decode it into a single char:
592
+ if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
593
+ one_char = static_cast<CharT>(((v0 & 3) << 6)
594
+ + (static_cast<unsigned char>(value[1]) & 0x3F));
595
+ return one_char;
596
+ }
597
+ // Otherwise we have a single character, but it's > U+00FF
598
+ throw value_error("Character code point not in range(0x100)");
599
+ }
600
+ }
601
+
602
+ // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
603
+ // surrogate pair with total length 2 instantly indicates a range error (but not a "your
604
+ // string was too long" error).
605
+ else if (StringCaster::UTF_N == 16 && str_len == 2) {
606
+ one_char = static_cast<CharT>(value[0]);
607
+ if (one_char >= 0xD800 && one_char < 0xE000) {
608
+ throw value_error("Character code point not in range(0x10000)");
609
+ }
610
+ }
611
+
612
+ if (str_len != 1) {
613
+ throw value_error("Expected a character, but multi-character string found");
614
+ }
615
+
616
+ one_char = value[0];
617
+ return one_char;
618
+ }
619
+
620
+ static constexpr auto name = const_name(PYBIND11_STRING_NAME);
621
+ template <typename _T>
622
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
623
+ };
624
+
625
+ // Base implementation for std::tuple and std::pair
626
+ template <template <typename...> class Tuple, typename... Ts>
627
+ class tuple_caster {
628
+ using type = Tuple<Ts...>;
629
+ static constexpr auto size = sizeof...(Ts);
630
+ using indices = make_index_sequence<size>;
631
+
632
+ public:
633
+ bool load(handle src, bool convert) {
634
+ if (!isinstance<sequence>(src)) {
635
+ return false;
636
+ }
637
+ const auto seq = reinterpret_borrow<sequence>(src);
638
+ if (seq.size() != size) {
639
+ return false;
640
+ }
641
+ return load_impl(seq, convert, indices{});
642
+ }
643
+
644
+ template <typename T>
645
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
646
+ return cast_impl(std::forward<T>(src), policy, parent, indices{});
647
+ }
648
+
649
+ // copied from the PYBIND11_TYPE_CASTER macro
650
+ template <typename T>
651
+ static handle cast(T *src, return_value_policy policy, handle parent) {
652
+ if (!src) {
653
+ return none().release();
654
+ }
655
+ if (policy == return_value_policy::take_ownership) {
656
+ auto h = cast(std::move(*src), policy, parent);
657
+ delete src;
658
+ return h;
659
+ }
660
+ return cast(*src, policy, parent);
661
+ }
662
+
663
+ static constexpr auto name
664
+ = const_name("Tuple[") + concat(make_caster<Ts>::name...) + const_name("]");
665
+
666
+ template <typename T>
667
+ using cast_op_type = type;
668
+
669
+ explicit operator type() & { return implicit_cast(indices{}); }
670
+ explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
671
+
672
+ protected:
673
+ template <size_t... Is>
674
+ type implicit_cast(index_sequence<Is...>) & {
675
+ return type(cast_op<Ts>(std::get<Is>(subcasters))...);
676
+ }
677
+ template <size_t... Is>
678
+ type implicit_cast(index_sequence<Is...>) && {
679
+ return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
680
+ }
681
+
682
+ static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
683
+
684
+ template <size_t... Is>
685
+ bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
686
+ #ifdef __cpp_fold_expressions
687
+ if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
688
+ return false;
689
+ }
690
+ #else
691
+ for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
692
+ if (!r) {
693
+ return false;
694
+ }
695
+ }
696
+ #endif
697
+ return true;
698
+ }
699
+
700
+ /* Implementation: Convert a C++ tuple into a Python tuple */
701
+ template <typename T, size_t... Is>
702
+ static handle
703
+ cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
704
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
705
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
706
+ std::array<object, size> entries{{reinterpret_steal<object>(
707
+ make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
708
+ for (const auto &entry : entries) {
709
+ if (!entry) {
710
+ return handle();
711
+ }
712
+ }
713
+ tuple result(size);
714
+ int counter = 0;
715
+ for (auto &entry : entries) {
716
+ PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
717
+ }
718
+ return result.release();
719
+ }
720
+
721
+ Tuple<make_caster<Ts>...> subcasters;
722
+ };
723
+
724
+ template <typename T1, typename T2>
725
+ class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
726
+
727
+ template <typename... Ts>
728
+ class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
729
+
730
+ /// Helper class which abstracts away certain actions. Users can provide specializations for
731
+ /// custom holders, but it's only necessary if the type has a non-standard interface.
732
+ template <typename T>
733
+ struct holder_helper {
734
+ static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
735
+ };
736
+
737
+ /// Type caster for holder types like std::shared_ptr, etc.
738
+ /// The SFINAE hook is provided to help work around the current lack of support
739
+ /// for smart-pointer interoperability. Please consider it an implementation
740
+ /// detail that may change in the future, as formal support for smart-pointer
741
+ /// interoperability is added into pybind11.
742
+ template <typename type, typename holder_type, typename SFINAE = void>
743
+ struct copyable_holder_caster : public type_caster_base<type> {
744
+ public:
745
+ using base = type_caster_base<type>;
746
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
747
+ "Holder classes are only supported for custom types");
748
+ using base::base;
749
+ using base::cast;
750
+ using base::typeinfo;
751
+ using base::value;
752
+
753
+ bool load(handle src, bool convert) {
754
+ return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
755
+ }
756
+
757
+ explicit operator type *() { return this->value; }
758
+ // static_cast works around compiler error with MSVC 17 and CUDA 10.2
759
+ // see issue #2180
760
+ explicit operator type &() { return *(static_cast<type *>(this->value)); }
761
+ explicit operator holder_type *() { return std::addressof(holder); }
762
+ explicit operator holder_type &() { return holder; }
763
+
764
+ static handle cast(const holder_type &src, return_value_policy, handle) {
765
+ const auto *ptr = holder_helper<holder_type>::get(src);
766
+ return type_caster_base<type>::cast_holder(ptr, &src);
767
+ }
768
+
769
+ protected:
770
+ friend class type_caster_generic;
771
+ void check_holder_compat() {
772
+ if (typeinfo->default_holder) {
773
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
774
+ }
775
+ }
776
+
777
+ bool load_value(value_and_holder &&v_h) {
778
+ if (v_h.holder_constructed()) {
779
+ value = v_h.value_ptr();
780
+ holder = v_h.template holder<holder_type>();
781
+ return true;
782
+ }
783
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
784
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
785
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
786
+ "type information)");
787
+ #else
788
+ "of type '"
789
+ + type_id<holder_type>() + "''");
790
+ #endif
791
+ }
792
+
793
+ template <typename T = holder_type,
794
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
795
+ bool try_implicit_casts(handle, bool) {
796
+ return false;
797
+ }
798
+
799
+ template <typename T = holder_type,
800
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
801
+ bool try_implicit_casts(handle src, bool convert) {
802
+ for (auto &cast : typeinfo->implicit_casts) {
803
+ copyable_holder_caster sub_caster(*cast.first);
804
+ if (sub_caster.load(src, convert)) {
805
+ value = cast.second(sub_caster.value);
806
+ holder = holder_type(sub_caster.holder, (type *) value);
807
+ return true;
808
+ }
809
+ }
810
+ return false;
811
+ }
812
+
813
+ static bool try_direct_conversions(handle) { return false; }
814
+
815
+ holder_type holder;
816
+ };
817
+
818
+ /// Specialize for the common std::shared_ptr, so users don't need to
819
+ template <typename T>
820
+ class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
821
+
822
+ /// Type caster for holder types like std::unique_ptr.
823
+ /// Please consider the SFINAE hook an implementation detail, as explained
824
+ /// in the comment for the copyable_holder_caster.
825
+ template <typename type, typename holder_type, typename SFINAE = void>
826
+ struct move_only_holder_caster {
827
+ static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
828
+ "Holder classes are only supported for custom types");
829
+
830
+ static handle cast(holder_type &&src, return_value_policy, handle) {
831
+ auto *ptr = holder_helper<holder_type>::get(src);
832
+ return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
833
+ }
834
+ static constexpr auto name = type_caster_base<type>::name;
835
+ };
836
+
837
+ template <typename type, typename deleter>
838
+ class type_caster<std::unique_ptr<type, deleter>>
839
+ : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
840
+
841
+ template <typename type, typename holder_type>
842
+ using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
843
+ copyable_holder_caster<type, holder_type>,
844
+ move_only_holder_caster<type, holder_type>>;
845
+
846
+ template <typename T, bool Value = false>
847
+ struct always_construct_holder {
848
+ static constexpr bool value = Value;
849
+ };
850
+
851
+ /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
852
+ #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
853
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
854
+ namespace detail { \
855
+ template <typename type> \
856
+ struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
857
+ }; \
858
+ template <typename type> \
859
+ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
860
+ : public type_caster_holder<type, holder_type> {}; \
861
+ } \
862
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
863
+
864
+ // PYBIND11_DECLARE_HOLDER_TYPE holder types:
865
+ template <typename base, typename holder>
866
+ struct is_holder_type
867
+ : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
868
+ // Specialization for always-supported unique_ptr holders:
869
+ template <typename base, typename deleter>
870
+ struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
871
+
872
+ template <typename T>
873
+ struct handle_type_name {
874
+ static constexpr auto name = const_name<T>();
875
+ };
876
+ template <>
877
+ struct handle_type_name<bool_> {
878
+ static constexpr auto name = const_name("bool");
879
+ };
880
+ template <>
881
+ struct handle_type_name<bytes> {
882
+ static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
883
+ };
884
+ template <>
885
+ struct handle_type_name<int_> {
886
+ static constexpr auto name = const_name("int");
887
+ };
888
+ template <>
889
+ struct handle_type_name<iterable> {
890
+ static constexpr auto name = const_name("Iterable");
891
+ };
892
+ template <>
893
+ struct handle_type_name<iterator> {
894
+ static constexpr auto name = const_name("Iterator");
895
+ };
896
+ template <>
897
+ struct handle_type_name<float_> {
898
+ static constexpr auto name = const_name("float");
899
+ };
900
+ template <>
901
+ struct handle_type_name<none> {
902
+ static constexpr auto name = const_name("None");
903
+ };
904
+ template <>
905
+ struct handle_type_name<args> {
906
+ static constexpr auto name = const_name("*args");
907
+ };
908
+ template <>
909
+ struct handle_type_name<kwargs> {
910
+ static constexpr auto name = const_name("**kwargs");
911
+ };
912
+
913
+ template <typename type>
914
+ struct pyobject_caster {
915
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
916
+ pyobject_caster() : value() {}
917
+
918
+ // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
919
+ // to a nil handle is safe since it will only be accessed if `load` succeeds.
920
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
921
+ pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
922
+
923
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
924
+ bool load(handle src, bool /* convert */) {
925
+ value = src;
926
+ return static_cast<bool>(value);
927
+ }
928
+
929
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
930
+ bool load(handle src, bool /* convert */) {
931
+ if (!isinstance<type>(src)) {
932
+ return false;
933
+ }
934
+ value = reinterpret_borrow<type>(src);
935
+ return true;
936
+ }
937
+
938
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
939
+ return src.inc_ref();
940
+ }
941
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
942
+ };
943
+
944
+ template <typename T>
945
+ class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
946
+
947
+ // Our conditions for enabling moving are quite restrictive:
948
+ // At compile time:
949
+ // - T needs to be a non-const, non-pointer, non-reference type
950
+ // - type_caster<T>::operator T&() must exist
951
+ // - the type must be move constructible (obviously)
952
+ // At run-time:
953
+ // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
954
+ // must have ref_count() == 1)h
955
+ // If any of the above are not satisfied, we fall back to copying.
956
+ template <typename T>
957
+ using move_is_plain_type
958
+ = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
959
+ template <typename T, typename SFINAE = void>
960
+ struct move_always : std::false_type {};
961
+ template <typename T>
962
+ struct move_always<
963
+ T,
964
+ enable_if_t<
965
+ all_of<move_is_plain_type<T>,
966
+ negation<is_copy_constructible<T>>,
967
+ is_move_constructible<T>,
968
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
969
+ : std::true_type {};
970
+ template <typename T, typename SFINAE = void>
971
+ struct move_if_unreferenced : std::false_type {};
972
+ template <typename T>
973
+ struct move_if_unreferenced<
974
+ T,
975
+ enable_if_t<
976
+ all_of<move_is_plain_type<T>,
977
+ negation<move_always<T>>,
978
+ is_move_constructible<T>,
979
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
980
+ : std::true_type {};
981
+ template <typename T>
982
+ using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
983
+
984
+ // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
985
+ // reference or pointer to a local variable of the type_caster. Basically, only
986
+ // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
987
+ // everything else returns a reference/pointer to a local variable.
988
+ template <typename type>
989
+ using cast_is_temporary_value_reference
990
+ = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
991
+ && !std::is_base_of<type_caster_generic, make_caster<type>>::value
992
+ && !std::is_same<intrinsic_t<type>, void>::value>;
993
+
994
+ // When a value returned from a C++ function is being cast back to Python, we almost always want to
995
+ // force `policy = move`, regardless of the return value policy the function/method was declared
996
+ // with.
997
+ template <typename Return, typename SFINAE = void>
998
+ struct return_value_policy_override {
999
+ static return_value_policy policy(return_value_policy p) { return p; }
1000
+ };
1001
+
1002
+ template <typename Return>
1003
+ struct return_value_policy_override<
1004
+ Return,
1005
+ detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1006
+ static return_value_policy policy(return_value_policy p) {
1007
+ return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1008
+ ? return_value_policy::move
1009
+ : p;
1010
+ }
1011
+ };
1012
+
1013
+ // Basic python -> C++ casting; throws if casting fails
1014
+ template <typename T, typename SFINAE>
1015
+ type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1016
+ static_assert(!detail::is_pyobject<T>::value,
1017
+ "Internal error: type_caster should only be used for C++ types");
1018
+ if (!conv.load(handle, true)) {
1019
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1020
+ throw cast_error(
1021
+ "Unable to cast Python instance of type "
1022
+ + str(type::handle_of(handle)).cast<std::string>()
1023
+ + " to C++ type '?' (#define "
1024
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1025
+ #else
1026
+ throw cast_error("Unable to cast Python instance of type "
1027
+ + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
1028
+ + type_id<T>() + "'");
1029
+ #endif
1030
+ }
1031
+ return conv;
1032
+ }
1033
+ // Wrapper around the above that also constructs and returns a type_caster
1034
+ template <typename T>
1035
+ make_caster<T> load_type(const handle &handle) {
1036
+ make_caster<T> conv;
1037
+ load_type(conv, handle);
1038
+ return conv;
1039
+ }
1040
+
1041
+ PYBIND11_NAMESPACE_END(detail)
1042
+
1043
+ // pytype -> C++ type
1044
+ template <typename T,
1045
+ detail::enable_if_t<!detail::is_pyobject<T>::value
1046
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1047
+ int>
1048
+ = 0>
1049
+ T cast(const handle &handle) {
1050
+ using namespace detail;
1051
+ static_assert(!cast_is_temporary_value_reference<T>::value,
1052
+ "Unable to cast type to reference: value is local to type caster");
1053
+ return cast_op<T>(load_type<T>(handle));
1054
+ }
1055
+
1056
+ // pytype -> pytype (calls converting constructor)
1057
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1058
+ T cast(const handle &handle) {
1059
+ return T(reinterpret_borrow<object>(handle));
1060
+ }
1061
+
1062
+ // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
1063
+ // This is necessary for the case that `obj` is a temporary, and could
1064
+ // not possibly be different, given
1065
+ // 1. the established convention that the passed `handle` is borrowed, and
1066
+ // 2. we don't want to force all generic code using `cast<T>()` to special-case
1067
+ // handling of `T` = `PyObject *` (to increment the reference count there).
1068
+ // It is the responsibility of the caller to ensure that the reference count
1069
+ // is decremented.
1070
+ template <typename T,
1071
+ typename Handle,
1072
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1073
+ && detail::is_same_ignoring_cvref<Handle, handle>::value,
1074
+ int>
1075
+ = 0>
1076
+ T cast(Handle &&handle) {
1077
+ return handle.inc_ref().ptr();
1078
+ }
1079
+ // To optimize way an inc_ref/dec_ref cycle:
1080
+ template <typename T,
1081
+ typename Object,
1082
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1083
+ && detail::is_same_ignoring_cvref<Object, object>::value,
1084
+ int>
1085
+ = 0>
1086
+ T cast(Object &&obj) {
1087
+ return obj.release().ptr();
1088
+ }
1089
+
1090
+ // C++ type -> py::object
1091
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1092
+ object cast(T &&value,
1093
+ return_value_policy policy = return_value_policy::automatic_reference,
1094
+ handle parent = handle()) {
1095
+ using no_ref_T = typename std::remove_reference<T>::type;
1096
+ if (policy == return_value_policy::automatic) {
1097
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1098
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1099
+ : return_value_policy::move;
1100
+ } else if (policy == return_value_policy::automatic_reference) {
1101
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1102
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1103
+ : return_value_policy::move;
1104
+ }
1105
+ return reinterpret_steal<object>(
1106
+ detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1107
+ }
1108
+
1109
+ template <typename T>
1110
+ T handle::cast() const {
1111
+ return pybind11::cast<T>(*this);
1112
+ }
1113
+ template <>
1114
+ inline void handle::cast() const {
1115
+ return;
1116
+ }
1117
+
1118
+ template <typename T>
1119
+ detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1120
+ if (obj.ref_count() > 1) {
1121
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1122
+ throw cast_error(
1123
+ "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
1124
+ + " instance to C++ rvalue: instance has multiple references"
1125
+ " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1126
+ #else
1127
+ throw cast_error("Unable to move from Python "
1128
+ + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
1129
+ + type_id<T>() + " instance: instance has multiple references");
1130
+ #endif
1131
+ }
1132
+
1133
+ // Move into a temporary and return that, because the reference may be a local value of `conv`
1134
+ T ret = std::move(detail::load_type<T>(obj).operator T &());
1135
+ return ret;
1136
+ }
1137
+
1138
+ // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1139
+ // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1140
+ // object has multiple references, but trying to copy will fail to compile.
1141
+ // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1142
+ // - Otherwise (not movable), copy.
1143
+ template <typename T>
1144
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1145
+ cast(object &&object) {
1146
+ return move<T>(std::move(object));
1147
+ }
1148
+ template <typename T>
1149
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1150
+ cast(object &&object) {
1151
+ if (object.ref_count() > 1) {
1152
+ return cast<T>(object);
1153
+ }
1154
+ return move<T>(std::move(object));
1155
+ }
1156
+ template <typename T>
1157
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1158
+ cast(object &&object) {
1159
+ return cast<T>(object);
1160
+ }
1161
+
1162
+ // pytype rvalue -> pytype (calls converting constructor)
1163
+ template <typename T>
1164
+ detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1165
+ return T(std::move(object));
1166
+ }
1167
+
1168
+ template <typename T>
1169
+ T object::cast() const & {
1170
+ return pybind11::cast<T>(*this);
1171
+ }
1172
+ template <typename T>
1173
+ T object::cast() && {
1174
+ return pybind11::cast<T>(std::move(*this));
1175
+ }
1176
+ template <>
1177
+ inline void object::cast() const & {
1178
+ return;
1179
+ }
1180
+ template <>
1181
+ inline void object::cast() && {
1182
+ return;
1183
+ }
1184
+
1185
+ PYBIND11_NAMESPACE_BEGIN(detail)
1186
+
1187
+ // Declared in pytypes.h:
1188
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1189
+ object object_or_cast(T &&o) {
1190
+ return pybind11::cast(std::forward<T>(o));
1191
+ }
1192
+
1193
+ // Placeholder type for the unneeded (and dead code) static variable in the
1194
+ // PYBIND11_OVERRIDE_OVERRIDE macro
1195
+ struct override_unused {};
1196
+ template <typename ret_type>
1197
+ using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1198
+ make_caster<ret_type>,
1199
+ override_unused>;
1200
+
1201
+ // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1202
+ // store the result in the given variable. For other types, this is a no-op.
1203
+ template <typename T>
1204
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1205
+ make_caster<T> &caster) {
1206
+ return cast_op<T>(load_type(caster, o));
1207
+ }
1208
+ template <typename T>
1209
+ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1210
+ override_unused &) {
1211
+ pybind11_fail("Internal error: cast_ref fallback invoked");
1212
+ }
1213
+
1214
+ // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1215
+ // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1216
+ // that only does anything in cases where pybind11::cast is valid.
1217
+ template <typename T>
1218
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
1219
+ pybind11_fail("Internal error: cast_safe fallback invoked");
1220
+ }
1221
+ template <typename T>
1222
+ enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1223
+ template <typename T>
1224
+ enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>, std::is_void<T>>::value, T>
1225
+ cast_safe(object &&o) {
1226
+ return pybind11::cast<T>(std::move(o));
1227
+ }
1228
+
1229
+ PYBIND11_NAMESPACE_END(detail)
1230
+
1231
+ // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1232
+ // but it is an easy minor optimization.
1233
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1234
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
1235
+ return cast_error("Unable to convert call argument '" + name
1236
+ + "' to Python object (#define "
1237
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1238
+ }
1239
+ #else
1240
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1241
+ const std::string &type) {
1242
+ return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1243
+ + "' to Python object");
1244
+ }
1245
+ #endif
1246
+
1247
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1248
+ tuple make_tuple() {
1249
+ return tuple(0);
1250
+ }
1251
+
1252
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1253
+ tuple make_tuple(Args &&...args_) {
1254
+ constexpr size_t size = sizeof...(Args);
1255
+ std::array<object, size> args{{reinterpret_steal<object>(
1256
+ detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1257
+ for (size_t i = 0; i < args.size(); i++) {
1258
+ if (!args[i]) {
1259
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1260
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i));
1261
+ #else
1262
+ std::array<std::string, size> argtypes{{type_id<Args>()...}};
1263
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1264
+ #endif
1265
+ }
1266
+ }
1267
+ tuple result(size);
1268
+ int counter = 0;
1269
+ for (auto &arg_value : args) {
1270
+ PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1271
+ }
1272
+ return result;
1273
+ }
1274
+
1275
+ /// \ingroup annotations
1276
+ /// Annotation for arguments
1277
+ struct arg {
1278
+ /// Constructs an argument with the name of the argument; if null or omitted, this is a
1279
+ /// positional argument.
1280
+ constexpr explicit arg(const char *name = nullptr)
1281
+ : name(name), flag_noconvert(false), flag_none(true) {}
1282
+ /// Assign a value to this argument
1283
+ template <typename T>
1284
+ arg_v operator=(T &&value) const;
1285
+ /// Indicate that the type should not be converted in the type caster
1286
+ arg &noconvert(bool flag = true) {
1287
+ flag_noconvert = flag;
1288
+ return *this;
1289
+ }
1290
+ /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1291
+ arg &none(bool flag = true) {
1292
+ flag_none = flag;
1293
+ return *this;
1294
+ }
1295
+
1296
+ const char *name; ///< If non-null, this is a named kwargs argument
1297
+ bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1298
+ ///< caster!)
1299
+ bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1300
+ };
1301
+
1302
+ /// \ingroup annotations
1303
+ /// Annotation for arguments with values
1304
+ struct arg_v : arg {
1305
+ private:
1306
+ template <typename T>
1307
+ arg_v(arg &&base, T &&x, const char *descr = nullptr)
1308
+ : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1309
+ std::forward<T>(x), return_value_policy::automatic, {}))),
1310
+ descr(descr)
1311
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1312
+ ,
1313
+ type(type_id<T>())
1314
+ #endif
1315
+ {
1316
+ // Workaround! See:
1317
+ // https://github.com/pybind/pybind11/issues/2336
1318
+ // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1319
+ if (PyErr_Occurred()) {
1320
+ PyErr_Clear();
1321
+ }
1322
+ }
1323
+
1324
+ public:
1325
+ /// Direct construction with name, default, and description
1326
+ template <typename T>
1327
+ arg_v(const char *name, T &&x, const char *descr = nullptr)
1328
+ : arg_v(arg(name), std::forward<T>(x), descr) {}
1329
+
1330
+ /// Called internally when invoking `py::arg("a") = value`
1331
+ template <typename T>
1332
+ arg_v(const arg &base, T &&x, const char *descr = nullptr)
1333
+ : arg_v(arg(base), std::forward<T>(x), descr) {}
1334
+
1335
+ /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1336
+ arg_v &noconvert(bool flag = true) {
1337
+ arg::noconvert(flag);
1338
+ return *this;
1339
+ }
1340
+
1341
+ /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1342
+ arg_v &none(bool flag = true) {
1343
+ arg::none(flag);
1344
+ return *this;
1345
+ }
1346
+
1347
+ /// The default value
1348
+ object value;
1349
+ /// The (optional) description of the default value
1350
+ const char *descr;
1351
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1352
+ /// The C++ type name of the default value (only available when compiled in debug mode)
1353
+ std::string type;
1354
+ #endif
1355
+ };
1356
+
1357
+ /// \ingroup annotations
1358
+ /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
1359
+ /// an unnamed '*' argument
1360
+ struct kw_only {};
1361
+
1362
+ /// \ingroup annotations
1363
+ /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
1364
+ /// an unnamed '/' argument (in Python 3.8)
1365
+ struct pos_only {};
1366
+
1367
+ template <typename T>
1368
+ arg_v arg::operator=(T &&value) const {
1369
+ return {*this, std::forward<T>(value)};
1370
+ }
1371
+
1372
+ /// Alias for backward compatibility -- to be removed in version 2.0
1373
+ template <typename /*unused*/>
1374
+ using arg_t = arg_v;
1375
+
1376
+ inline namespace literals {
1377
+ /** \rst
1378
+ String literal version of `arg`
1379
+ \endrst */
1380
+ constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1381
+ } // namespace literals
1382
+
1383
+ PYBIND11_NAMESPACE_BEGIN(detail)
1384
+
1385
+ template <typename T>
1386
+ using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
1387
+ template <typename T>
1388
+ using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
1389
+
1390
+ // forward declaration (definition in attr.h)
1391
+ struct function_record;
1392
+
1393
+ /// Internal data associated with a single function call
1394
+ struct function_call {
1395
+ function_call(const function_record &f, handle p); // Implementation in attr.h
1396
+
1397
+ /// The function data:
1398
+ const function_record &func;
1399
+
1400
+ /// Arguments passed to the function:
1401
+ std::vector<handle> args;
1402
+
1403
+ /// The `convert` value the arguments should be loaded with
1404
+ std::vector<bool> args_convert;
1405
+
1406
+ /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
1407
+ /// present, are also in `args` but without a reference).
1408
+ object args_ref, kwargs_ref;
1409
+
1410
+ /// The parent, if any
1411
+ handle parent;
1412
+
1413
+ /// If this is a call to an initializer, this argument contains `self`
1414
+ handle init_self;
1415
+ };
1416
+
1417
+ /// Helper class which loads arguments for C++ functions called from Python
1418
+ template <typename... Args>
1419
+ class argument_loader {
1420
+ using indices = make_index_sequence<sizeof...(Args)>;
1421
+
1422
+ template <typename Arg>
1423
+ using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1424
+ template <typename Arg>
1425
+ using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1426
+ // Get kwargs argument position, or -1 if not present:
1427
+ static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
1428
+
1429
+ static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
1430
+ "py::kwargs is only permitted as the last argument of a function");
1431
+
1432
+ public:
1433
+ static constexpr bool has_kwargs = kwargs_pos != -1;
1434
+
1435
+ // py::args argument position; -1 if not present.
1436
+ static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
1437
+
1438
+ static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
1439
+ "py::args cannot be specified more than once");
1440
+
1441
+ static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
1442
+
1443
+ bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
1444
+
1445
+ template <typename Return, typename Guard, typename Func>
1446
+ // NOLINTNEXTLINE(readability-const-return-type)
1447
+ enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1448
+ return std::move(*this).template call_impl<remove_cv_t<Return>>(
1449
+ std::forward<Func>(f), indices{}, Guard{});
1450
+ }
1451
+
1452
+ template <typename Return, typename Guard, typename Func>
1453
+ enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1454
+ std::move(*this).template call_impl<remove_cv_t<Return>>(
1455
+ std::forward<Func>(f), indices{}, Guard{});
1456
+ return void_type();
1457
+ }
1458
+
1459
+ private:
1460
+ static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1461
+
1462
+ template <size_t... Is>
1463
+ bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1464
+ #ifdef __cpp_fold_expressions
1465
+ if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
1466
+ return false;
1467
+ }
1468
+ #else
1469
+ for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
1470
+ if (!r) {
1471
+ return false;
1472
+ }
1473
+ }
1474
+ #endif
1475
+ return true;
1476
+ }
1477
+
1478
+ template <typename Return, typename Func, size_t... Is, typename Guard>
1479
+ Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1480
+ return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1481
+ }
1482
+
1483
+ std::tuple<make_caster<Args>...> argcasters;
1484
+ };
1485
+
1486
+ /// Helper class which collects only positional arguments for a Python function call.
1487
+ /// A fancier version below can collect any argument, but this one is optimal for simple calls.
1488
+ template <return_value_policy policy>
1489
+ class simple_collector {
1490
+ public:
1491
+ template <typename... Ts>
1492
+ explicit simple_collector(Ts &&...values)
1493
+ : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
1494
+
1495
+ const tuple &args() const & { return m_args; }
1496
+ dict kwargs() const { return {}; }
1497
+
1498
+ tuple args() && { return std::move(m_args); }
1499
+
1500
+ /// Call a Python function and pass the collected arguments
1501
+ object call(PyObject *ptr) const {
1502
+ PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1503
+ if (!result) {
1504
+ throw error_already_set();
1505
+ }
1506
+ return reinterpret_steal<object>(result);
1507
+ }
1508
+
1509
+ private:
1510
+ tuple m_args;
1511
+ };
1512
+
1513
+ /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
1514
+ template <return_value_policy policy>
1515
+ class unpacking_collector {
1516
+ public:
1517
+ template <typename... Ts>
1518
+ explicit unpacking_collector(Ts &&...values) {
1519
+ // Tuples aren't (easily) resizable so a list is needed for collection,
1520
+ // but the actual function call strictly requires a tuple.
1521
+ auto args_list = list();
1522
+ using expander = int[];
1523
+ (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
1524
+
1525
+ m_args = std::move(args_list);
1526
+ }
1527
+
1528
+ const tuple &args() const & { return m_args; }
1529
+ const dict &kwargs() const & { return m_kwargs; }
1530
+
1531
+ tuple args() && { return std::move(m_args); }
1532
+ dict kwargs() && { return std::move(m_kwargs); }
1533
+
1534
+ /// Call a Python function and pass the collected arguments
1535
+ object call(PyObject *ptr) const {
1536
+ PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1537
+ if (!result) {
1538
+ throw error_already_set();
1539
+ }
1540
+ return reinterpret_steal<object>(result);
1541
+ }
1542
+
1543
+ private:
1544
+ template <typename T>
1545
+ void process(list &args_list, T &&x) {
1546
+ auto o = reinterpret_steal<object>(
1547
+ detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1548
+ if (!o) {
1549
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1550
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
1551
+ #else
1552
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
1553
+ type_id<T>());
1554
+ #endif
1555
+ }
1556
+ args_list.append(std::move(o));
1557
+ }
1558
+
1559
+ void process(list &args_list, detail::args_proxy ap) {
1560
+ for (auto a : ap) {
1561
+ args_list.append(a);
1562
+ }
1563
+ }
1564
+
1565
+ void process(list & /*args_list*/, arg_v a) {
1566
+ if (!a.name) {
1567
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1568
+ nameless_argument_error();
1569
+ #else
1570
+ nameless_argument_error(a.type);
1571
+ #endif
1572
+ }
1573
+ if (m_kwargs.contains(a.name)) {
1574
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1575
+ multiple_values_error();
1576
+ #else
1577
+ multiple_values_error(a.name);
1578
+ #endif
1579
+ }
1580
+ if (!a.value) {
1581
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1582
+ throw cast_error_unable_to_convert_call_arg(a.name);
1583
+ #else
1584
+ throw cast_error_unable_to_convert_call_arg(a.name, a.type);
1585
+ #endif
1586
+ }
1587
+ m_kwargs[a.name] = std::move(a.value);
1588
+ }
1589
+
1590
+ void process(list & /*args_list*/, detail::kwargs_proxy kp) {
1591
+ if (!kp) {
1592
+ return;
1593
+ }
1594
+ for (auto k : reinterpret_borrow<dict>(kp)) {
1595
+ if (m_kwargs.contains(k.first)) {
1596
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1597
+ multiple_values_error();
1598
+ #else
1599
+ multiple_values_error(str(k.first));
1600
+ #endif
1601
+ }
1602
+ m_kwargs[k.first] = k.second;
1603
+ }
1604
+ }
1605
+
1606
+ [[noreturn]] static void nameless_argument_error() {
1607
+ throw type_error(
1608
+ "Got kwargs without a name; only named arguments "
1609
+ "may be passed via py::arg() to a python function call. "
1610
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1611
+ }
1612
+ [[noreturn]] static void nameless_argument_error(const std::string &type) {
1613
+ throw type_error("Got kwargs without a name of type '" + type
1614
+ + "'; only named "
1615
+ "arguments may be passed via py::arg() to a python function call. ");
1616
+ }
1617
+ [[noreturn]] static void multiple_values_error() {
1618
+ throw type_error(
1619
+ "Got multiple values for keyword argument "
1620
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1621
+ }
1622
+
1623
+ [[noreturn]] static void multiple_values_error(const std::string &name) {
1624
+ throw type_error("Got multiple values for keyword argument '" + name + "'");
1625
+ }
1626
+
1627
+ private:
1628
+ tuple m_args;
1629
+ dict m_kwargs;
1630
+ };
1631
+
1632
+ // [workaround(intel)] Separate function required here
1633
+ // We need to put this into a separate function because the Intel compiler
1634
+ // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
1635
+ // (tested with ICC 2021.1 Beta 20200827).
1636
+ template <typename... Args>
1637
+ constexpr bool args_are_all_positional() {
1638
+ return all_of<is_positional<Args>...>::value;
1639
+ }
1640
+
1641
+ /// Collect only positional arguments for a Python function call
1642
+ template <return_value_policy policy,
1643
+ typename... Args,
1644
+ typename = enable_if_t<args_are_all_positional<Args...>()>>
1645
+ simple_collector<policy> collect_arguments(Args &&...args) {
1646
+ return simple_collector<policy>(std::forward<Args>(args)...);
1647
+ }
1648
+
1649
+ /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
1650
+ template <return_value_policy policy,
1651
+ typename... Args,
1652
+ typename = enable_if_t<!args_are_all_positional<Args...>()>>
1653
+ unpacking_collector<policy> collect_arguments(Args &&...args) {
1654
+ // Following argument order rules for generalized unpacking according to PEP 448
1655
+ static_assert(constexpr_last<is_positional, Args...>()
1656
+ < constexpr_first<is_keyword_or_ds, Args...>()
1657
+ && constexpr_last<is_s_unpacking, Args...>()
1658
+ < constexpr_first<is_ds_unpacking, Args...>(),
1659
+ "Invalid function call: positional args must precede keywords and ** unpacking; "
1660
+ "* unpacking must precede ** unpacking");
1661
+ return unpacking_collector<policy>(std::forward<Args>(args)...);
1662
+ }
1663
+
1664
+ template <typename Derived>
1665
+ template <return_value_policy policy, typename... Args>
1666
+ object object_api<Derived>::operator()(Args &&...args) const {
1667
+ #ifndef NDEBUG
1668
+ if (!PyGILState_Check()) {
1669
+ pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1670
+ }
1671
+ #endif
1672
+ return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1673
+ }
1674
+
1675
+ template <typename Derived>
1676
+ template <return_value_policy policy, typename... Args>
1677
+ object object_api<Derived>::call(Args &&...args) const {
1678
+ return operator()<policy>(std::forward<Args>(args)...);
1679
+ }
1680
+
1681
+ PYBIND11_NAMESPACE_END(detail)
1682
+
1683
+ template <typename T>
1684
+ handle type::handle_of() {
1685
+ static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1686
+ "py::type::of<T> only supports the case where T is a registered C++ types.");
1687
+
1688
+ return detail::get_type_handle(typeid(T), true);
1689
+ }
1690
+
1691
+ #define PYBIND11_MAKE_OPAQUE(...) \
1692
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
1693
+ namespace detail { \
1694
+ template <> \
1695
+ class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
1696
+ } \
1697
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1698
+
1699
+ /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
1700
+ /// typedef, e.g.:
1701
+ /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
1702
+ #define PYBIND11_TYPE(...) __VA_ARGS__
1703
+
1704
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/chrono.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
3
+
4
+ Copyright (c) 2016 Trent Houliston <trent@houliston.me> and
5
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "pybind11.h"
14
+
15
+ #include <chrono>
16
+ #include <cmath>
17
+ #include <ctime>
18
+ #include <datetime.h>
19
+ #include <mutex>
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+
24
+ template <typename type>
25
+ class duration_caster {
26
+ public:
27
+ using rep = typename type::rep;
28
+ using period = typename type::period;
29
+
30
+ // signed 25 bits required by the standard.
31
+ using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
32
+
33
+ bool load(handle src, bool) {
34
+ using namespace std::chrono;
35
+
36
+ // Lazy initialise the PyDateTime import
37
+ if (!PyDateTimeAPI) {
38
+ PyDateTime_IMPORT;
39
+ }
40
+
41
+ if (!src) {
42
+ return false;
43
+ }
44
+ // If invoked with datetime.delta object
45
+ if (PyDelta_Check(src.ptr())) {
46
+ value = type(duration_cast<duration<rep, period>>(
47
+ days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
48
+ + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
49
+ + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
50
+ return true;
51
+ }
52
+ // If invoked with a float we assume it is seconds and convert
53
+ if (PyFloat_Check(src.ptr())) {
54
+ value = type(duration_cast<duration<rep, period>>(
55
+ duration<double>(PyFloat_AsDouble(src.ptr()))));
56
+ return true;
57
+ }
58
+ return false;
59
+ }
60
+
61
+ // If this is a duration just return it back
62
+ static const std::chrono::duration<rep, period> &
63
+ get_duration(const std::chrono::duration<rep, period> &src) {
64
+ return src;
65
+ }
66
+
67
+ // If this is a time_point get the time_since_epoch
68
+ template <typename Clock>
69
+ static std::chrono::duration<rep, period>
70
+ get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
71
+ return src.time_since_epoch();
72
+ }
73
+
74
+ static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
75
+ using namespace std::chrono;
76
+
77
+ // Use overloaded function to get our duration from our source
78
+ // Works out if it is a duration or time_point and get the duration
79
+ auto d = get_duration(src);
80
+
81
+ // Lazy initialise the PyDateTime import
82
+ if (!PyDateTimeAPI) {
83
+ PyDateTime_IMPORT;
84
+ }
85
+
86
+ // Declare these special duration types so the conversions happen with the correct
87
+ // primitive types (int)
88
+ using dd_t = duration<int, std::ratio<86400>>;
89
+ using ss_t = duration<int, std::ratio<1>>;
90
+ using us_t = duration<int, std::micro>;
91
+
92
+ auto dd = duration_cast<dd_t>(d);
93
+ auto subd = d - dd;
94
+ auto ss = duration_cast<ss_t>(subd);
95
+ auto us = duration_cast<us_t>(subd - ss);
96
+ return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
97
+ }
98
+
99
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
100
+ };
101
+
102
+ inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
103
+ #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
104
+ if (localtime_s(buf, time))
105
+ return nullptr;
106
+ return buf;
107
+ #else
108
+ static std::mutex mtx;
109
+ std::lock_guard<std::mutex> lock(mtx);
110
+ std::tm *tm_ptr = std::localtime(time);
111
+ if (tm_ptr != nullptr) {
112
+ *buf = *tm_ptr;
113
+ }
114
+ return tm_ptr;
115
+ #endif
116
+ }
117
+
118
+ // This is for casting times on the system clock into datetime.datetime instances
119
+ template <typename Duration>
120
+ class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
121
+ public:
122
+ using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
123
+ bool load(handle src, bool) {
124
+ using namespace std::chrono;
125
+
126
+ // Lazy initialise the PyDateTime import
127
+ if (!PyDateTimeAPI) {
128
+ PyDateTime_IMPORT;
129
+ }
130
+
131
+ if (!src) {
132
+ return false;
133
+ }
134
+
135
+ std::tm cal;
136
+ microseconds msecs;
137
+
138
+ if (PyDateTime_Check(src.ptr())) {
139
+ cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
140
+ cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
141
+ cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
142
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
143
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
144
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
145
+ cal.tm_isdst = -1;
146
+ msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
147
+ } else if (PyDate_Check(src.ptr())) {
148
+ cal.tm_sec = 0;
149
+ cal.tm_min = 0;
150
+ cal.tm_hour = 0;
151
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
152
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
153
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
154
+ cal.tm_isdst = -1;
155
+ msecs = microseconds(0);
156
+ } else if (PyTime_Check(src.ptr())) {
157
+ cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
158
+ cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
159
+ cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
160
+ cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
161
+ cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
162
+ cal.tm_year = 70; // earliest available date for Python's datetime
163
+ cal.tm_isdst = -1;
164
+ msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
165
+ } else {
166
+ return false;
167
+ }
168
+
169
+ value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
170
+ return true;
171
+ }
172
+
173
+ static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
174
+ return_value_policy /* policy */,
175
+ handle /* parent */) {
176
+ using namespace std::chrono;
177
+
178
+ // Lazy initialise the PyDateTime import
179
+ if (!PyDateTimeAPI) {
180
+ PyDateTime_IMPORT;
181
+ }
182
+
183
+ // Get out microseconds, and make sure they are positive, to avoid bug in eastern
184
+ // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
185
+ using us_t = duration<int, std::micro>;
186
+ auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
187
+ if (us.count() < 0) {
188
+ us += seconds(1);
189
+ }
190
+
191
+ // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
192
+ // > If std::time_t has lower precision, it is implementation-defined whether the value is
193
+ // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
194
+ std::time_t tt
195
+ = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
196
+
197
+ std::tm localtime;
198
+ std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
199
+ if (!localtime_ptr) {
200
+ throw cast_error("Unable to represent system_clock in local time");
201
+ }
202
+ return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
203
+ localtime.tm_mon + 1,
204
+ localtime.tm_mday,
205
+ localtime.tm_hour,
206
+ localtime.tm_min,
207
+ localtime.tm_sec,
208
+ us.count());
209
+ }
210
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
211
+ };
212
+
213
+ // Other clocks that are not the system clock are not measured as datetime.datetime objects
214
+ // since they are not measured on calendar time. So instead we just make them timedeltas
215
+ // Or if they have passed us a time as a float we convert that
216
+ template <typename Clock, typename Duration>
217
+ class type_caster<std::chrono::time_point<Clock, Duration>>
218
+ : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
219
+
220
+ template <typename Rep, typename Period>
221
+ class type_caster<std::chrono::duration<Rep, Period>>
222
+ : public duration_caster<std::chrono::duration<Rep, Period>> {};
223
+
224
+ PYBIND11_NAMESPACE_END(detail)
225
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/common.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #include "detail/common.h"
2
+ #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
videollama2/lib/python3.10/site-packages/torch/include/pybind11/complex.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/complex.h: Complex number support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ #include <complex>
15
+
16
+ /// glibc defines I as a macro which breaks things, e.g., boost template names
17
+ #ifdef I
18
+ # undef I
19
+ #endif
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+
23
+ template <typename T>
24
+ struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
25
+ static constexpr const char c = format_descriptor<T>::c;
26
+ static constexpr const char value[3] = {'Z', c, '\0'};
27
+ static std::string format() { return std::string(value); }
28
+ };
29
+
30
+ #ifndef PYBIND11_CPP17
31
+
32
+ template <typename T>
33
+ constexpr const char
34
+ format_descriptor<std::complex<T>,
35
+ detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
36
+
37
+ #endif
38
+
39
+ PYBIND11_NAMESPACE_BEGIN(detail)
40
+
41
+ template <typename T>
42
+ struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
43
+ static constexpr bool value = true;
44
+ static constexpr int index = is_fmt_numeric<T>::index + 3;
45
+ };
46
+
47
+ template <typename T>
48
+ class type_caster<std::complex<T>> {
49
+ public:
50
+ bool load(handle src, bool convert) {
51
+ if (!src) {
52
+ return false;
53
+ }
54
+ if (!convert && !PyComplex_Check(src.ptr())) {
55
+ return false;
56
+ }
57
+ Py_complex result = PyComplex_AsCComplex(src.ptr());
58
+ if (result.real == -1.0 && PyErr_Occurred()) {
59
+ PyErr_Clear();
60
+ return false;
61
+ }
62
+ value = std::complex<T>((T) result.real, (T) result.imag);
63
+ return true;
64
+ }
65
+
66
+ static handle
67
+ cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
68
+ return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
69
+ }
70
+
71
+ PYBIND11_TYPE_CASTER(std::complex<T>, const_name("complex"));
72
+ };
73
+ PYBIND11_NAMESPACE_END(detail)
74
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/class.h ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/class.h: Python C API implementation details for py::class_
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../attr.h"
13
+ #include "../options.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ #if !defined(PYPY_VERSION)
19
+ # define PYBIND11_BUILTIN_QUALNAME
20
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
21
+ #else
22
+ // In PyPy, we still set __qualname__ so that we can produce reliable function type
23
+ // signatures; in CPython this macro expands to nothing:
24
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
25
+ setattr((PyObject *) obj, "__qualname__", nameobj)
26
+ #endif
27
+
28
+ inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
29
+ #if !defined(PYPY_VERSION)
30
+ return type->tp_name;
31
+ #else
32
+ auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
33
+ if (module_name == PYBIND11_BUILTINS_MODULE)
34
+ return type->tp_name;
35
+ else
36
+ return std::move(module_name) + "." + type->tp_name;
37
+ #endif
38
+ }
39
+
40
+ inline PyTypeObject *type_incref(PyTypeObject *type) {
41
+ Py_INCREF(type);
42
+ return type;
43
+ }
44
+
45
+ #if !defined(PYPY_VERSION)
46
+
47
+ /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
48
+ extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
49
+ return PyProperty_Type.tp_descr_get(self, cls, cls);
50
+ }
51
+
52
+ /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
53
+ extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
54
+ PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
55
+ return PyProperty_Type.tp_descr_set(self, cls, value);
56
+ }
57
+
58
+ // Forward declaration to use in `make_static_property_type()`
59
+ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
60
+
61
+ /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
62
+ methods are modified to always use the object type instead of a concrete instance.
63
+ Return value: New reference. */
64
+ inline PyTypeObject *make_static_property_type() {
65
+ constexpr auto *name = "pybind11_static_property";
66
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
67
+
68
+ /* Danger zone: from now (and until PyType_Ready), make sure to
69
+ issue no Python C API calls which could potentially invoke the
70
+ garbage collector (the GC will call type_traverse(), which will in
71
+ turn find the newly constructed type in an invalid state) */
72
+ auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
73
+ if (!heap_type) {
74
+ pybind11_fail("make_static_property_type(): error allocating type!");
75
+ }
76
+
77
+ heap_type->ht_name = name_obj.inc_ref().ptr();
78
+ # ifdef PYBIND11_BUILTIN_QUALNAME
79
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
80
+ # endif
81
+
82
+ auto *type = &heap_type->ht_type;
83
+ type->tp_name = name;
84
+ type->tp_base = type_incref(&PyProperty_Type);
85
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
86
+ type->tp_descr_get = pybind11_static_get;
87
+ type->tp_descr_set = pybind11_static_set;
88
+
89
+ if (PyType_Ready(type) < 0) {
90
+ pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
91
+ }
92
+
93
+ # if PY_VERSION_HEX >= 0x030C0000
94
+ // PRE 3.12 FEATURE FREEZE. PLEASE REVIEW AFTER FREEZE.
95
+ // Since Python-3.12 property-derived types are required to
96
+ // have dynamic attributes (to set `__doc__`)
97
+ enable_dynamic_attributes(heap_type);
98
+ # endif
99
+
100
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
101
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
102
+
103
+ return type;
104
+ }
105
+
106
+ #else // PYPY
107
+
108
+ /** PyPy has some issues with the above C API, so we evaluate Python code instead.
109
+ This function will only be called once so performance isn't really a concern.
110
+ Return value: New reference. */
111
+ inline PyTypeObject *make_static_property_type() {
112
+ auto d = dict();
113
+ PyObject *result = PyRun_String(R"(\
114
+ class pybind11_static_property(property):
115
+ def __get__(self, obj, cls):
116
+ return property.__get__(self, cls, cls)
117
+
118
+ def __set__(self, obj, value):
119
+ cls = obj if isinstance(obj, type) else type(obj)
120
+ property.__set__(self, cls, value)
121
+ )",
122
+ Py_file_input,
123
+ d.ptr(),
124
+ d.ptr());
125
+ if (result == nullptr)
126
+ throw error_already_set();
127
+ Py_DECREF(result);
128
+ return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
129
+ }
130
+
131
+ #endif // PYPY
132
+
133
+ /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
134
+ By default, Python replaces the `static_property` itself, but for wrapped C++ types
135
+ we need to call `static_property.__set__()` in order to propagate the new value to
136
+ the underlying C++ data structure. */
137
+ extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
138
+ // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
139
+ // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
140
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
141
+
142
+ // The following assignment combinations are possible:
143
+ // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
144
+ // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
145
+ // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
146
+ auto *const static_prop = (PyObject *) get_internals().static_property_type;
147
+ const auto call_descr_set = (descr != nullptr) && (value != nullptr)
148
+ && (PyObject_IsInstance(descr, static_prop) != 0)
149
+ && (PyObject_IsInstance(value, static_prop) == 0);
150
+ if (call_descr_set) {
151
+ // Call `static_property.__set__()` instead of replacing the `static_property`.
152
+ #if !defined(PYPY_VERSION)
153
+ return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
154
+ #else
155
+ if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
156
+ Py_DECREF(result);
157
+ return 0;
158
+ } else {
159
+ return -1;
160
+ }
161
+ #endif
162
+ } else {
163
+ // Replace existing attribute.
164
+ return PyType_Type.tp_setattro(obj, name, value);
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
170
+ * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
171
+ * when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
172
+ * to do a special case bypass for PyInstanceMethod_Types.
173
+ */
174
+ extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
175
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
176
+ if (descr && PyInstanceMethod_Check(descr)) {
177
+ Py_INCREF(descr);
178
+ return descr;
179
+ }
180
+ return PyType_Type.tp_getattro(obj, name);
181
+ }
182
+
183
+ /// metaclass `__call__` function that is used to create all pybind11 objects.
184
+ extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
185
+
186
+ // use the default metaclass call to create/initialize the object
187
+ PyObject *self = PyType_Type.tp_call(type, args, kwargs);
188
+ if (self == nullptr) {
189
+ return nullptr;
190
+ }
191
+
192
+ // This must be a pybind11 instance
193
+ auto *instance = reinterpret_cast<detail::instance *>(self);
194
+
195
+ // Ensure that the base __init__ function(s) were called
196
+ for (const auto &vh : values_and_holders(instance)) {
197
+ if (!vh.holder_constructed()) {
198
+ PyErr_Format(PyExc_TypeError,
199
+ "%.200s.__init__() must be called when overriding __init__",
200
+ get_fully_qualified_tp_name(vh.type->type).c_str());
201
+ Py_DECREF(self);
202
+ return nullptr;
203
+ }
204
+ }
205
+
206
+ return self;
207
+ }
208
+
209
+ /// Cleanup the type-info for a pybind11-registered type.
210
+ extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
211
+ auto *type = (PyTypeObject *) obj;
212
+ auto &internals = get_internals();
213
+
214
+ // A pybind11-registered type will:
215
+ // 1) be found in internals.registered_types_py
216
+ // 2) have exactly one associated `detail::type_info`
217
+ auto found_type = internals.registered_types_py.find(type);
218
+ if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
219
+ && found_type->second[0]->type == type) {
220
+
221
+ auto *tinfo = found_type->second[0];
222
+ auto tindex = std::type_index(*tinfo->cpptype);
223
+ internals.direct_conversions.erase(tindex);
224
+
225
+ if (tinfo->module_local) {
226
+ get_local_internals().registered_types_cpp.erase(tindex);
227
+ } else {
228
+ internals.registered_types_cpp.erase(tindex);
229
+ }
230
+ internals.registered_types_py.erase(tinfo->type);
231
+
232
+ // Actually just `std::erase_if`, but that's only available in C++20
233
+ auto &cache = internals.inactive_override_cache;
234
+ for (auto it = cache.begin(), last = cache.end(); it != last;) {
235
+ if (it->first == (PyObject *) tinfo->type) {
236
+ it = cache.erase(it);
237
+ } else {
238
+ ++it;
239
+ }
240
+ }
241
+
242
+ delete tinfo;
243
+ }
244
+
245
+ PyType_Type.tp_dealloc(obj);
246
+ }
247
+
248
+ /** This metaclass is assigned by default to all pybind11 types and is required in order
249
+ for static properties to function correctly. Users may override this using `py::metaclass`.
250
+ Return value: New reference. */
251
+ inline PyTypeObject *make_default_metaclass() {
252
+ constexpr auto *name = "pybind11_type";
253
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
254
+
255
+ /* Danger zone: from now (and until PyType_Ready), make sure to
256
+ issue no Python C API calls which could potentially invoke the
257
+ garbage collector (the GC will call type_traverse(), which will in
258
+ turn find the newly constructed type in an invalid state) */
259
+ auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
260
+ if (!heap_type) {
261
+ pybind11_fail("make_default_metaclass(): error allocating metaclass!");
262
+ }
263
+
264
+ heap_type->ht_name = name_obj.inc_ref().ptr();
265
+ #ifdef PYBIND11_BUILTIN_QUALNAME
266
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
267
+ #endif
268
+
269
+ auto *type = &heap_type->ht_type;
270
+ type->tp_name = name;
271
+ type->tp_base = type_incref(&PyType_Type);
272
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
273
+
274
+ type->tp_call = pybind11_meta_call;
275
+
276
+ type->tp_setattro = pybind11_meta_setattro;
277
+ type->tp_getattro = pybind11_meta_getattro;
278
+
279
+ type->tp_dealloc = pybind11_meta_dealloc;
280
+
281
+ if (PyType_Ready(type) < 0) {
282
+ pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
283
+ }
284
+
285
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
286
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
287
+
288
+ return type;
289
+ }
290
+
291
+ /// For multiple inheritance types we need to recursively register/deregister base pointers for any
292
+ /// base classes with pointers that are difference from the instance value pointer so that we can
293
+ /// correctly recognize an offset base class pointer. This calls a function with any offset base
294
+ /// ptrs.
295
+ inline void traverse_offset_bases(void *valueptr,
296
+ const detail::type_info *tinfo,
297
+ instance *self,
298
+ bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
299
+ for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
300
+ if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
301
+ for (auto &c : parent_tinfo->implicit_casts) {
302
+ if (c.first == tinfo->cpptype) {
303
+ auto *parentptr = c.second(valueptr);
304
+ if (parentptr != valueptr) {
305
+ f(parentptr, self);
306
+ }
307
+ traverse_offset_bases(parentptr, parent_tinfo, self, f);
308
+ break;
309
+ }
310
+ }
311
+ }
312
+ }
313
+ }
314
+
315
+ inline bool register_instance_impl(void *ptr, instance *self) {
316
+ get_internals().registered_instances.emplace(ptr, self);
317
+ return true; // unused, but gives the same signature as the deregister func
318
+ }
319
+ inline bool deregister_instance_impl(void *ptr, instance *self) {
320
+ auto &registered_instances = get_internals().registered_instances;
321
+ auto range = registered_instances.equal_range(ptr);
322
+ for (auto it = range.first; it != range.second; ++it) {
323
+ if (self == it->second) {
324
+ registered_instances.erase(it);
325
+ return true;
326
+ }
327
+ }
328
+ return false;
329
+ }
330
+
331
+ inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
332
+ register_instance_impl(valptr, self);
333
+ if (!tinfo->simple_ancestors) {
334
+ traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
335
+ }
336
+ }
337
+
338
+ inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
339
+ bool ret = deregister_instance_impl(valptr, self);
340
+ if (!tinfo->simple_ancestors) {
341
+ traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
342
+ }
343
+ return ret;
344
+ }
345
+
346
+ /// Instance creation function for all pybind11 types. It allocates the internal instance layout
347
+ /// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
348
+ /// cast to a reference or pointer), and initialization is done by an `__init__` function.
349
+ inline PyObject *make_new_instance(PyTypeObject *type) {
350
+ #if defined(PYPY_VERSION)
351
+ // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
352
+ // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
353
+ ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
354
+ if (type->tp_basicsize < instance_size) {
355
+ type->tp_basicsize = instance_size;
356
+ }
357
+ #endif
358
+ PyObject *self = type->tp_alloc(type, 0);
359
+ auto *inst = reinterpret_cast<instance *>(self);
360
+ // Allocate the value/holder internals:
361
+ inst->allocate_layout();
362
+
363
+ return self;
364
+ }
365
+
366
+ /// Instance creation function for all pybind11 types. It only allocates space for the
367
+ /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
368
+ extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
369
+ return make_new_instance(type);
370
+ }
371
+
372
+ /// An `__init__` function constructs the C++ object. Users should provide at least one
373
+ /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
374
+ /// following default function will be used which simply throws an exception.
375
+ extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
376
+ PyTypeObject *type = Py_TYPE(self);
377
+ std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
378
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
379
+ return -1;
380
+ }
381
+
382
+ inline void add_patient(PyObject *nurse, PyObject *patient) {
383
+ auto &internals = get_internals();
384
+ auto *instance = reinterpret_cast<detail::instance *>(nurse);
385
+ instance->has_patients = true;
386
+ Py_INCREF(patient);
387
+ internals.patients[nurse].push_back(patient);
388
+ }
389
+
390
+ inline void clear_patients(PyObject *self) {
391
+ auto *instance = reinterpret_cast<detail::instance *>(self);
392
+ auto &internals = get_internals();
393
+ auto pos = internals.patients.find(self);
394
+ assert(pos != internals.patients.end());
395
+ // Clearing the patients can cause more Python code to run, which
396
+ // can invalidate the iterator. Extract the vector of patients
397
+ // from the unordered_map first.
398
+ auto patients = std::move(pos->second);
399
+ internals.patients.erase(pos);
400
+ instance->has_patients = false;
401
+ for (PyObject *&patient : patients) {
402
+ Py_CLEAR(patient);
403
+ }
404
+ }
405
+
406
+ /// Clears all internal data from the instance and removes it from registered instances in
407
+ /// preparation for deallocation.
408
+ inline void clear_instance(PyObject *self) {
409
+ auto *instance = reinterpret_cast<detail::instance *>(self);
410
+
411
+ // Deallocate any values/holders, if present:
412
+ for (auto &v_h : values_and_holders(instance)) {
413
+ if (v_h) {
414
+
415
+ // We have to deregister before we call dealloc because, for virtual MI types, we still
416
+ // need to be able to get the parent pointers.
417
+ if (v_h.instance_registered()
418
+ && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
419
+ pybind11_fail(
420
+ "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
421
+ }
422
+
423
+ if (instance->owned || v_h.holder_constructed()) {
424
+ v_h.type->dealloc(v_h);
425
+ }
426
+ }
427
+ }
428
+ // Deallocate the value/holder layout internals:
429
+ instance->deallocate_layout();
430
+
431
+ if (instance->weakrefs) {
432
+ PyObject_ClearWeakRefs(self);
433
+ }
434
+
435
+ PyObject **dict_ptr = _PyObject_GetDictPtr(self);
436
+ if (dict_ptr) {
437
+ Py_CLEAR(*dict_ptr);
438
+ }
439
+
440
+ if (instance->has_patients) {
441
+ clear_patients(self);
442
+ }
443
+ }
444
+
445
+ /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
446
+ /// to destroy the C++ object itself, while the rest is Python bookkeeping.
447
+ extern "C" inline void pybind11_object_dealloc(PyObject *self) {
448
+ auto *type = Py_TYPE(self);
449
+
450
+ // If this is a GC tracked object, untrack it first
451
+ // Note that the track call is implicitly done by the
452
+ // default tp_alloc, which we never override.
453
+ if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
454
+ PyObject_GC_UnTrack(self);
455
+ }
456
+
457
+ clear_instance(self);
458
+
459
+ type->tp_free(self);
460
+
461
+ #if PY_VERSION_HEX < 0x03080000
462
+ // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
463
+ // as part of a derived type's dealloc, in which case we're not allowed to decref
464
+ // the type here. For cross-module compatibility, we shouldn't compare directly
465
+ // with `pybind11_object_dealloc`, but with the common one stashed in internals.
466
+ auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
467
+ if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
468
+ Py_DECREF(type);
469
+ #else
470
+ // This was not needed before Python 3.8 (Python issue 35810)
471
+ // https://github.com/pybind/pybind11/issues/1946
472
+ Py_DECREF(type);
473
+ #endif
474
+ }
475
+
476
+ std::string error_string();
477
+
478
+ /** Create the type which can be used as a common base for all classes. This is
479
+ needed in order to satisfy Python's requirements for multiple inheritance.
480
+ Return value: New reference. */
481
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
482
+ constexpr auto *name = "pybind11_object";
483
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
484
+
485
+ /* Danger zone: from now (and until PyType_Ready), make sure to
486
+ issue no Python C API calls which could potentially invoke the
487
+ garbage collector (the GC will call type_traverse(), which will in
488
+ turn find the newly constructed type in an invalid state) */
489
+ auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
490
+ if (!heap_type) {
491
+ pybind11_fail("make_object_base_type(): error allocating type!");
492
+ }
493
+
494
+ heap_type->ht_name = name_obj.inc_ref().ptr();
495
+ #ifdef PYBIND11_BUILTIN_QUALNAME
496
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
497
+ #endif
498
+
499
+ auto *type = &heap_type->ht_type;
500
+ type->tp_name = name;
501
+ type->tp_base = type_incref(&PyBaseObject_Type);
502
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
503
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
504
+
505
+ type->tp_new = pybind11_object_new;
506
+ type->tp_init = pybind11_object_init;
507
+ type->tp_dealloc = pybind11_object_dealloc;
508
+
509
+ /* Support weak references (needed for the keep_alive feature) */
510
+ type->tp_weaklistoffset = offsetof(instance, weakrefs);
511
+
512
+ if (PyType_Ready(type) < 0) {
513
+ pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
514
+ }
515
+
516
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
517
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
518
+
519
+ assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
520
+ return (PyObject *) heap_type;
521
+ }
522
+
523
+ /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
524
+ extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
525
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
526
+ Py_VISIT(dict);
527
+ // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
528
+ #if PY_VERSION_HEX >= 0x03090000
529
+ Py_VISIT(Py_TYPE(self));
530
+ #endif
531
+ return 0;
532
+ }
533
+
534
+ /// dynamic_attr: Allow the GC to clear the dictionary.
535
+ extern "C" inline int pybind11_clear(PyObject *self) {
536
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
537
+ Py_CLEAR(dict);
538
+ return 0;
539
+ }
540
+
541
+ /// Give instances of this type a `__dict__` and opt into garbage collection.
542
+ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
543
+ auto *type = &heap_type->ht_type;
544
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
545
+ #if PY_VERSION_HEX < 0x030B0000
546
+ type->tp_dictoffset = type->tp_basicsize; // place dict at the end
547
+ type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
548
+ #else
549
+ type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
550
+ #endif
551
+ type->tp_traverse = pybind11_traverse;
552
+ type->tp_clear = pybind11_clear;
553
+
554
+ static PyGetSetDef getset[] = {{
555
+ #if PY_VERSION_HEX < 0x03070000
556
+ const_cast<char *>("__dict__"),
557
+ #else
558
+ "__dict__",
559
+ #endif
560
+ PyObject_GenericGetDict,
561
+ PyObject_GenericSetDict,
562
+ nullptr,
563
+ nullptr},
564
+ {nullptr, nullptr, nullptr, nullptr, nullptr}};
565
+ type->tp_getset = getset;
566
+ }
567
+
568
+ /// buffer_protocol: Fill in the view as specified by flags.
569
+ extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
570
+ // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
571
+ type_info *tinfo = nullptr;
572
+ for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
573
+ tinfo = get_type_info((PyTypeObject *) type.ptr());
574
+ if (tinfo && tinfo->get_buffer) {
575
+ break;
576
+ }
577
+ }
578
+ if (view == nullptr || !tinfo || !tinfo->get_buffer) {
579
+ if (view) {
580
+ view->obj = nullptr;
581
+ }
582
+ PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
583
+ return -1;
584
+ }
585
+ std::memset(view, 0, sizeof(Py_buffer));
586
+ buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
587
+ if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
588
+ delete info;
589
+ // view->obj = nullptr; // Was just memset to 0, so not necessary
590
+ PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
591
+ return -1;
592
+ }
593
+ view->obj = obj;
594
+ view->ndim = 1;
595
+ view->internal = info;
596
+ view->buf = info->ptr;
597
+ view->itemsize = info->itemsize;
598
+ view->len = view->itemsize;
599
+ for (auto s : info->shape) {
600
+ view->len *= s;
601
+ }
602
+ view->readonly = static_cast<int>(info->readonly);
603
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
604
+ view->format = const_cast<char *>(info->format.c_str());
605
+ }
606
+ if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
607
+ view->ndim = (int) info->ndim;
608
+ view->strides = info->strides.data();
609
+ view->shape = info->shape.data();
610
+ }
611
+ Py_INCREF(view->obj);
612
+ return 0;
613
+ }
614
+
615
+ /// buffer_protocol: Release the resources of the buffer.
616
+ extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
617
+ delete (buffer_info *) view->internal;
618
+ }
619
+
620
+ /// Give this type a buffer interface.
621
+ inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
622
+ heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
623
+
624
+ heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
625
+ heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
626
+ }
627
+
628
+ /** Create a brand new Python type according to the `type_record` specification.
629
+ Return value: New reference. */
630
+ inline PyObject *make_new_python_type(const type_record &rec) {
631
+ auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
632
+
633
+ auto qualname = name;
634
+ if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
635
+ qualname = reinterpret_steal<object>(
636
+ PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
637
+ }
638
+
639
+ object module_;
640
+ if (rec.scope) {
641
+ if (hasattr(rec.scope, "__module__")) {
642
+ module_ = rec.scope.attr("__module__");
643
+ } else if (hasattr(rec.scope, "__name__")) {
644
+ module_ = rec.scope.attr("__name__");
645
+ }
646
+ }
647
+
648
+ const auto *full_name = c_str(
649
+ #if !defined(PYPY_VERSION)
650
+ module_ ? str(module_).cast<std::string>() + "." + rec.name :
651
+ #endif
652
+ rec.name);
653
+
654
+ char *tp_doc = nullptr;
655
+ if (rec.doc && options::show_user_defined_docstrings()) {
656
+ /* Allocate memory for docstring (using PyObject_MALLOC, since
657
+ Python will free this later on) */
658
+ size_t size = std::strlen(rec.doc) + 1;
659
+ tp_doc = (char *) PyObject_MALLOC(size);
660
+ std::memcpy((void *) tp_doc, rec.doc, size);
661
+ }
662
+
663
+ auto &internals = get_internals();
664
+ auto bases = tuple(rec.bases);
665
+ auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
666
+
667
+ /* Danger zone: from now (and until PyType_Ready), make sure to
668
+ issue no Python C API calls which could potentially invoke the
669
+ garbage collector (the GC will call type_traverse(), which will in
670
+ turn find the newly constructed type in an invalid state) */
671
+ auto *metaclass
672
+ = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
673
+
674
+ auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
675
+ if (!heap_type) {
676
+ pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
677
+ }
678
+
679
+ heap_type->ht_name = name.release().ptr();
680
+ #ifdef PYBIND11_BUILTIN_QUALNAME
681
+ heap_type->ht_qualname = qualname.inc_ref().ptr();
682
+ #endif
683
+
684
+ auto *type = &heap_type->ht_type;
685
+ type->tp_name = full_name;
686
+ type->tp_doc = tp_doc;
687
+ type->tp_base = type_incref((PyTypeObject *) base);
688
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
689
+ if (!bases.empty()) {
690
+ type->tp_bases = bases.release().ptr();
691
+ }
692
+
693
+ /* Don't inherit base __init__ */
694
+ type->tp_init = pybind11_object_init;
695
+
696
+ /* Supported protocols */
697
+ type->tp_as_number = &heap_type->as_number;
698
+ type->tp_as_sequence = &heap_type->as_sequence;
699
+ type->tp_as_mapping = &heap_type->as_mapping;
700
+ type->tp_as_async = &heap_type->as_async;
701
+
702
+ /* Flags */
703
+ type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
704
+ if (!rec.is_final) {
705
+ type->tp_flags |= Py_TPFLAGS_BASETYPE;
706
+ }
707
+
708
+ if (rec.dynamic_attr) {
709
+ enable_dynamic_attributes(heap_type);
710
+ }
711
+
712
+ if (rec.buffer_protocol) {
713
+ enable_buffer_protocol(heap_type);
714
+ }
715
+
716
+ if (rec.custom_type_setup_callback) {
717
+ rec.custom_type_setup_callback(heap_type);
718
+ }
719
+
720
+ if (PyType_Ready(type) < 0) {
721
+ pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
722
+ }
723
+
724
+ assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
725
+
726
+ /* Register type with the parent scope */
727
+ if (rec.scope) {
728
+ setattr(rec.scope, rec.name, (PyObject *) type);
729
+ } else {
730
+ Py_INCREF(type); // Keep it alive forever (reference leak)
731
+ }
732
+
733
+ if (module_) { // Needed by pydoc
734
+ setattr((PyObject *) type, "__module__", module_);
735
+ }
736
+
737
+ PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
738
+
739
+ return (PyObject *) type;
740
+ }
741
+
742
+ PYBIND11_NAMESPACE_END(detail)
743
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/common.h ADDED
@@ -0,0 +1,1255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/common.h -- Basic macros
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #define PYBIND11_VERSION_MAJOR 2
13
+ #define PYBIND11_VERSION_MINOR 11
14
+ #define PYBIND11_VERSION_PATCH 1
15
+
16
+ // Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
17
+ // Additional convention: 0xD = dev
18
+ #define PYBIND11_VERSION_HEX 0x020B0100
19
+
20
+ // Define some generic pybind11 helper macros for warning management.
21
+ //
22
+ // Note that compiler-specific push/pop pairs are baked into the
23
+ // PYBIND11_NAMESPACE_BEGIN/PYBIND11_NAMESPACE_END pair of macros. Therefore manual
24
+ // PYBIND11_WARNING_PUSH/PYBIND11_WARNING_POP are usually only needed in `#include` sections.
25
+ //
26
+ // If you find you need to suppress a warning, please try to make the suppression as local as
27
+ // possible using these macros. Please also be sure to push/pop with the pybind11 macros. Please
28
+ // only use compiler specifics if you need to check specific versions, e.g. Apple Clang vs. vanilla
29
+ // Clang.
30
+ #if defined(_MSC_VER)
31
+ # define PYBIND11_COMPILER_MSVC
32
+ # define PYBIND11_PRAGMA(...) __pragma(__VA_ARGS__)
33
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning(push))
34
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning(pop))
35
+ #elif defined(__INTEL_COMPILER)
36
+ # define PYBIND11_COMPILER_INTEL
37
+ # define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
38
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning push)
39
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning pop)
40
+ #elif defined(__clang__)
41
+ # define PYBIND11_COMPILER_CLANG
42
+ # define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
43
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(clang diagnostic push)
44
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(clang diagnostic push)
45
+ #elif defined(__GNUC__)
46
+ # define PYBIND11_COMPILER_GCC
47
+ # define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
48
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(GCC diagnostic push)
49
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(GCC diagnostic pop)
50
+ #endif
51
+
52
+ #ifdef PYBIND11_COMPILER_MSVC
53
+ # define PYBIND11_WARNING_DISABLE_MSVC(name) PYBIND11_PRAGMA(warning(disable : name))
54
+ #else
55
+ # define PYBIND11_WARNING_DISABLE_MSVC(name)
56
+ #endif
57
+
58
+ #ifdef PYBIND11_COMPILER_CLANG
59
+ # define PYBIND11_WARNING_DISABLE_CLANG(name) PYBIND11_PRAGMA(clang diagnostic ignored name)
60
+ #else
61
+ # define PYBIND11_WARNING_DISABLE_CLANG(name)
62
+ #endif
63
+
64
+ #ifdef PYBIND11_COMPILER_GCC
65
+ # define PYBIND11_WARNING_DISABLE_GCC(name) PYBIND11_PRAGMA(GCC diagnostic ignored name)
66
+ #else
67
+ # define PYBIND11_WARNING_DISABLE_GCC(name)
68
+ #endif
69
+
70
+ #ifdef PYBIND11_COMPILER_INTEL
71
+ # define PYBIND11_WARNING_DISABLE_INTEL(name) PYBIND11_PRAGMA(warning disable name)
72
+ #else
73
+ # define PYBIND11_WARNING_DISABLE_INTEL(name)
74
+ #endif
75
+
76
+ #define PYBIND11_NAMESPACE_BEGIN(name) \
77
+ namespace name { \
78
+ PYBIND11_WARNING_PUSH
79
+
80
+ #define PYBIND11_NAMESPACE_END(name) \
81
+ PYBIND11_WARNING_POP \
82
+ }
83
+
84
+ // Robust support for some features and loading modules compiled against different pybind versions
85
+ // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute
86
+ // on the main `pybind11` namespace.
87
+ #if !defined(PYBIND11_NAMESPACE)
88
+ # ifdef __GNUG__
89
+ # define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
90
+ # else
91
+ # define PYBIND11_NAMESPACE pybind11
92
+ # endif
93
+ #endif
94
+
95
+ #if !(defined(_MSC_VER) && __cplusplus == 199711L)
96
+ # if __cplusplus >= 201402L
97
+ # define PYBIND11_CPP14
98
+ # if __cplusplus >= 201703L
99
+ # define PYBIND11_CPP17
100
+ # if __cplusplus >= 202002L
101
+ # define PYBIND11_CPP20
102
+ // Please update tests/pybind11_tests.cpp `cpp_std()` when adding a macro here.
103
+ # endif
104
+ # endif
105
+ # endif
106
+ #elif defined(_MSC_VER) && __cplusplus == 199711L
107
+ // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
108
+ // implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
109
+ // or newer.
110
+ # if _MSVC_LANG >= 201402L
111
+ # define PYBIND11_CPP14
112
+ # if _MSVC_LANG > 201402L
113
+ # define PYBIND11_CPP17
114
+ # if _MSVC_LANG >= 202002L
115
+ # define PYBIND11_CPP20
116
+ # endif
117
+ # endif
118
+ # endif
119
+ #endif
120
+
121
+ // Compiler version assertions
122
+ #if defined(__INTEL_COMPILER)
123
+ # if __INTEL_COMPILER < 1800
124
+ # error pybind11 requires Intel C++ compiler v18 or newer
125
+ # elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
126
+ # error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
127
+ # endif
128
+ /* The following pragma cannot be pop'ed:
129
+ https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
130
+ # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
131
+ #elif defined(__clang__) && !defined(__apple_build_version__)
132
+ # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
133
+ # error pybind11 requires clang 3.3 or newer
134
+ # endif
135
+ #elif defined(__clang__)
136
+ // Apple changes clang version macros to its Xcode version; the first Xcode release based on
137
+ // (upstream) clang 3.3 was Xcode 5:
138
+ # if __clang_major__ < 5
139
+ # error pybind11 requires Xcode/clang 5.0 or newer
140
+ # endif
141
+ #elif defined(__GNUG__)
142
+ # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
143
+ # error pybind11 requires gcc 4.8 or newer
144
+ # endif
145
+ #elif defined(_MSC_VER)
146
+ # if _MSC_VER < 1910
147
+ # error pybind11 2.10+ requires MSVC 2017 or newer
148
+ # endif
149
+ #endif
150
+
151
+ #if !defined(PYBIND11_EXPORT)
152
+ # if defined(WIN32) || defined(_WIN32)
153
+ # define PYBIND11_EXPORT __declspec(dllexport)
154
+ # else
155
+ # define PYBIND11_EXPORT __attribute__((visibility("default")))
156
+ # endif
157
+ #endif
158
+
159
+ #if !defined(PYBIND11_EXPORT_EXCEPTION)
160
+ # if defined(__apple_build_version__)
161
+ # define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
162
+ # else
163
+ # define PYBIND11_EXPORT_EXCEPTION
164
+ # endif
165
+ #endif
166
+
167
+ // For CUDA, GCC7, GCC8:
168
+ // PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
169
+ // When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
170
+ // However, the measured shared-library size saving when using noinline are only
171
+ // 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
172
+ // the default under pybind11/tests).
173
+ #if !defined(PYBIND11_NOINLINE_FORCED) \
174
+ && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
175
+ # define PYBIND11_NOINLINE_DISABLED
176
+ #endif
177
+
178
+ // The PYBIND11_NOINLINE macro is for function DEFINITIONS.
179
+ // In contrast, FORWARD DECLARATIONS should never use this macro:
180
+ // https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
181
+ #if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
182
+ # define PYBIND11_NOINLINE inline
183
+ #elif defined(_MSC_VER)
184
+ # define PYBIND11_NOINLINE __declspec(noinline) inline
185
+ #else
186
+ # define PYBIND11_NOINLINE __attribute__((noinline)) inline
187
+ #endif
188
+
189
+ #if defined(__MINGW32__)
190
+ // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
191
+ // whether it is used or not
192
+ # define PYBIND11_DEPRECATED(reason)
193
+ #elif defined(PYBIND11_CPP14)
194
+ # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
195
+ #else
196
+ # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
197
+ #endif
198
+
199
+ #if defined(PYBIND11_CPP17)
200
+ # define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
201
+ #elif defined(_MSC_VER) && !defined(__clang__)
202
+ # define PYBIND11_MAYBE_UNUSED
203
+ #else
204
+ # define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
205
+ #endif
206
+
207
+ /* Don't let Python.h #define (v)snprintf as macro because they are implemented
208
+ properly in Visual Studio since 2015. */
209
+ #if defined(_MSC_VER)
210
+ # define HAVE_SNPRINTF 1
211
+ #endif
212
+
213
+ /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
214
+ #if defined(_MSC_VER)
215
+ PYBIND11_WARNING_PUSH
216
+ PYBIND11_WARNING_DISABLE_MSVC(4505)
217
+ // C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
218
+ # if defined(_DEBUG) && !defined(Py_DEBUG)
219
+ // Workaround for a VS 2022 issue.
220
+ // NOTE: This workaround knowingly violates the Python.h include order requirement:
221
+ // https://docs.python.org/3/c-api/intro.html#include-files
222
+ // See https://github.com/pybind/pybind11/pull/3497 for full context.
223
+ # include <yvals.h>
224
+ # if _MSVC_STL_VERSION >= 143
225
+ # include <crtdefs.h>
226
+ # endif
227
+ # define PYBIND11_DEBUG_MARKER
228
+ # undef _DEBUG
229
+ # endif
230
+ #endif
231
+
232
+ // https://en.cppreference.com/w/c/chrono/localtime
233
+ #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
234
+ # define __STDC_WANT_LIB_EXT1__
235
+ #endif
236
+
237
+ #ifdef __has_include
238
+ // std::optional (but including it in c++14 mode isn't allowed)
239
+ # if defined(PYBIND11_CPP17) && __has_include(<optional>)
240
+ # define PYBIND11_HAS_OPTIONAL 1
241
+ # endif
242
+ // std::experimental::optional (but not allowed in c++11 mode)
243
+ # if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
244
+ !__has_include(<optional>))
245
+ # define PYBIND11_HAS_EXP_OPTIONAL 1
246
+ # endif
247
+ // std::variant
248
+ # if defined(PYBIND11_CPP17) && __has_include(<variant>)
249
+ # define PYBIND11_HAS_VARIANT 1
250
+ # endif
251
+ #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
252
+ # define PYBIND11_HAS_OPTIONAL 1
253
+ # define PYBIND11_HAS_VARIANT 1
254
+ #endif
255
+
256
+ #if defined(PYBIND11_CPP17)
257
+ # if defined(__has_include)
258
+ # if __has_include(<string_view>)
259
+ # define PYBIND11_HAS_STRING_VIEW
260
+ # endif
261
+ # elif defined(_MSC_VER)
262
+ # define PYBIND11_HAS_STRING_VIEW
263
+ # endif
264
+ #endif
265
+
266
+ #include <Python.h>
267
+ // Reminder: WITH_THREAD is always defined if PY_VERSION_HEX >= 0x03070000
268
+ #if PY_VERSION_HEX < 0x03060000
269
+ # error "PYTHON < 3.6 IS UNSUPPORTED. pybind11 v2.9 was the last to support Python 2 and 3.5."
270
+ #endif
271
+ #include <frameobject.h>
272
+ #include <pythread.h>
273
+
274
+ /* Python #defines overrides on all sorts of core functions, which
275
+ tends to weak havok in C++ codebases that expect these to work
276
+ like regular functions (potentially with several overloads) */
277
+ #if defined(isalnum)
278
+ # undef isalnum
279
+ # undef isalpha
280
+ # undef islower
281
+ # undef isspace
282
+ # undef isupper
283
+ # undef tolower
284
+ # undef toupper
285
+ #endif
286
+
287
+ #if defined(copysign)
288
+ # undef copysign
289
+ #endif
290
+
291
+ #if defined(PYPY_VERSION) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
292
+ # define PYBIND11_SIMPLE_GIL_MANAGEMENT
293
+ #endif
294
+
295
+ #if defined(_MSC_VER)
296
+ # if defined(PYBIND11_DEBUG_MARKER)
297
+ # define _DEBUG
298
+ # undef PYBIND11_DEBUG_MARKER
299
+ # endif
300
+ PYBIND11_WARNING_POP
301
+ #endif
302
+
303
+ #include <cstddef>
304
+ #include <cstring>
305
+ #include <exception>
306
+ #include <forward_list>
307
+ #include <memory>
308
+ #include <stdexcept>
309
+ #include <string>
310
+ #include <type_traits>
311
+ #include <typeindex>
312
+ #include <unordered_map>
313
+ #include <unordered_set>
314
+ #include <vector>
315
+ #if defined(__has_include)
316
+ # if __has_include(<version>)
317
+ # include <version>
318
+ # endif
319
+ #endif
320
+
321
+ // Must be after including <version> or one of the other headers specified by the standard
322
+ #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
323
+ # define PYBIND11_HAS_U8STRING
324
+ #endif
325
+
326
+ // See description of PR #4246:
327
+ #if !defined(PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF) && !defined(NDEBUG) \
328
+ && !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
329
+ # define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
330
+ #endif
331
+
332
+ // #define PYBIND11_STR_LEGACY_PERMISSIVE
333
+ // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
334
+ // (probably surprising and never documented, but this was the
335
+ // legacy behavior until and including v2.6.x). As a side-effect,
336
+ // pybind11::isinstance<str>() is true for both pybind11::str and
337
+ // pybind11::bytes.
338
+ // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
339
+ // pybind11::isinstance<str>() is true only for pybind11::str.
340
+ // However, for Python 2 only (!), the pybind11::str caster
341
+ // implicitly decoded bytes to PyUnicodeObject. This was to ease
342
+ // the transition from the legacy behavior to the non-permissive
343
+ // behavior.
344
+
345
+ /// Compatibility macros for Python 2 / Python 3 versions TODO: remove
346
+ #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
347
+ #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
348
+ #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
349
+ #define PYBIND11_BYTES_CHECK PyBytes_Check
350
+ #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
351
+ #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
352
+ #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
353
+ #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
354
+ #define PYBIND11_BYTES_SIZE PyBytes_Size
355
+ #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
356
+ #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
357
+ #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
358
+ #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
359
+ #define PYBIND11_BYTES_NAME "bytes"
360
+ #define PYBIND11_STRING_NAME "str"
361
+ #define PYBIND11_SLICE_OBJECT PyObject
362
+ #define PYBIND11_FROM_STRING PyUnicode_FromString
363
+ #define PYBIND11_STR_TYPE ::pybind11::str
364
+ #define PYBIND11_BOOL_ATTR "__bool__"
365
+ #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
366
+ #define PYBIND11_BUILTINS_MODULE "builtins"
367
+ // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
368
+ // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
369
+ #define PYBIND11_PLUGIN_IMPL(name) \
370
+ extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
371
+ extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
372
+
373
+ #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
374
+ #define PYBIND11_STRINGIFY(x) #x
375
+ #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
376
+ #define PYBIND11_CONCAT(first, second) first##second
377
+ #define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
378
+
379
+ #define PYBIND11_CHECK_PYTHON_VERSION \
380
+ { \
381
+ const char *compiled_ver \
382
+ = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
383
+ const char *runtime_ver = Py_GetVersion(); \
384
+ size_t len = std::strlen(compiled_ver); \
385
+ if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
386
+ || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
387
+ PyErr_Format(PyExc_ImportError, \
388
+ "Python version mismatch: module was compiled for Python %s, " \
389
+ "but the interpreter version is incompatible: %s.", \
390
+ compiled_ver, \
391
+ runtime_ver); \
392
+ return nullptr; \
393
+ } \
394
+ }
395
+
396
+ #define PYBIND11_CATCH_INIT_EXCEPTIONS \
397
+ catch (pybind11::error_already_set & e) { \
398
+ pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
399
+ return nullptr; \
400
+ } \
401
+ catch (const std::exception &e) { \
402
+ PyErr_SetString(PyExc_ImportError, e.what()); \
403
+ return nullptr; \
404
+ }
405
+
406
+ /** \rst
407
+ ***Deprecated in favor of PYBIND11_MODULE***
408
+
409
+ This macro creates the entry point that will be invoked when the Python interpreter
410
+ imports a plugin library. Please create a `module_` in the function body and return
411
+ the pointer to its underlying Python object at the end.
412
+
413
+ .. code-block:: cpp
414
+
415
+ PYBIND11_PLUGIN(example) {
416
+ pybind11::module_ m("example", "pybind11 example plugin");
417
+ /// Set up bindings here
418
+ return m.ptr();
419
+ }
420
+ \endrst */
421
+ #define PYBIND11_PLUGIN(name) \
422
+ PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
423
+ static PyObject *pybind11_init(); \
424
+ PYBIND11_PLUGIN_IMPL(name) { \
425
+ PYBIND11_CHECK_PYTHON_VERSION \
426
+ PYBIND11_ENSURE_INTERNALS_READY \
427
+ try { \
428
+ return pybind11_init(); \
429
+ } \
430
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
431
+ } \
432
+ PyObject *pybind11_init()
433
+
434
+ /** \rst
435
+ This macro creates the entry point that will be invoked when the Python interpreter
436
+ imports an extension module. The module name is given as the first argument and it
437
+ should not be in quotes. The second macro argument defines a variable of type
438
+ `py::module_` which can be used to initialize the module.
439
+
440
+ The entry point is marked as "maybe unused" to aid dead-code detection analysis:
441
+ since the entry point is typically only looked up at runtime and not referenced
442
+ during translation, it would otherwise appear as unused ("dead") code.
443
+
444
+ .. code-block:: cpp
445
+
446
+ PYBIND11_MODULE(example, m) {
447
+ m.doc() = "pybind11 example module";
448
+
449
+ // Add bindings here
450
+ m.def("foo", []() {
451
+ return "Hello, World!";
452
+ });
453
+ }
454
+ \endrst */
455
+ #define PYBIND11_MODULE(name, variable) \
456
+ static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
457
+ PYBIND11_MAYBE_UNUSED; \
458
+ PYBIND11_MAYBE_UNUSED \
459
+ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
460
+ PYBIND11_PLUGIN_IMPL(name) { \
461
+ PYBIND11_CHECK_PYTHON_VERSION \
462
+ PYBIND11_ENSURE_INTERNALS_READY \
463
+ auto m = ::pybind11::module_::create_extension_module( \
464
+ PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
465
+ try { \
466
+ PYBIND11_CONCAT(pybind11_init_, name)(m); \
467
+ return m.ptr(); \
468
+ } \
469
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
470
+ } \
471
+ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
472
+
473
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
474
+
475
+ using ssize_t = Py_ssize_t;
476
+ using size_t = std::size_t;
477
+
478
+ template <typename IntType>
479
+ inline ssize_t ssize_t_cast(const IntType &val) {
480
+ static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
481
+ return static_cast<ssize_t>(val);
482
+ }
483
+
484
+ /// Approach used to cast a previously unknown C++ instance into a Python object
485
+ enum class return_value_policy : uint8_t {
486
+ /** This is the default return value policy, which falls back to the policy
487
+ return_value_policy::take_ownership when the return value is a pointer.
488
+ Otherwise, it uses return_value::move or return_value::copy for rvalue
489
+ and lvalue references, respectively. See below for a description of what
490
+ all of these different policies do. */
491
+ automatic = 0,
492
+
493
+ /** As above, but use policy return_value_policy::reference when the return
494
+ value is a pointer. This is the default conversion policy for function
495
+ arguments when calling Python functions manually from C++ code (i.e. via
496
+ handle::operator()). You probably won't need to use this. */
497
+ automatic_reference,
498
+
499
+ /** Reference an existing object (i.e. do not create a new copy) and take
500
+ ownership. Python will call the destructor and delete operator when the
501
+ object's reference count reaches zero. Undefined behavior ensues when
502
+ the C++ side does the same.. */
503
+ take_ownership,
504
+
505
+ /** Create a new copy of the returned object, which will be owned by
506
+ Python. This policy is comparably safe because the lifetimes of the two
507
+ instances are decoupled. */
508
+ copy,
509
+
510
+ /** Use std::move to move the return value contents into a new instance
511
+ that will be owned by Python. This policy is comparably safe because the
512
+ lifetimes of the two instances (move source and destination) are
513
+ decoupled. */
514
+ move,
515
+
516
+ /** Reference an existing object, but do not take ownership. The C++ side
517
+ is responsible for managing the object's lifetime and deallocating it
518
+ when it is no longer used. Warning: undefined behavior will ensue when
519
+ the C++ side deletes an object that is still referenced and used by
520
+ Python. */
521
+ reference,
522
+
523
+ /** This policy only applies to methods and properties. It references the
524
+ object without taking ownership similar to the above
525
+ return_value_policy::reference policy. In contrast to that policy, the
526
+ function or property's implicit this argument (called the parent) is
527
+ considered to be the the owner of the return value (the child).
528
+ pybind11 then couples the lifetime of the parent to the child via a
529
+ reference relationship that ensures that the parent cannot be garbage
530
+ collected while Python is still using the child. More advanced
531
+ variations of this scheme are also possible using combinations of
532
+ return_value_policy::reference and the keep_alive call policy */
533
+ reference_internal
534
+ };
535
+
536
+ PYBIND11_NAMESPACE_BEGIN(detail)
537
+
538
+ inline static constexpr int log2(size_t n, int k = 0) {
539
+ return (n <= 1) ? k : log2(n >> 1, k + 1);
540
+ }
541
+
542
+ // Returns the size as a multiple of sizeof(void *), rounded up.
543
+ inline static constexpr size_t size_in_ptrs(size_t s) {
544
+ return 1 + ((s - 1) >> log2(sizeof(void *)));
545
+ }
546
+
547
+ /**
548
+ * The space to allocate for simple layout instance holders (see below) in multiple of the size of
549
+ * a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
550
+ * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
551
+ * sizeof(std::shared_ptr<T>)).
552
+ */
553
+ constexpr size_t instance_simple_holder_in_ptrs() {
554
+ static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
555
+ "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
556
+ return size_in_ptrs(sizeof(std::shared_ptr<int>));
557
+ }
558
+
559
+ // Forward declarations
560
+ struct type_info;
561
+ struct value_and_holder;
562
+
563
+ struct nonsimple_values_and_holders {
564
+ void **values_and_holders;
565
+ uint8_t *status;
566
+ };
567
+
568
+ /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
569
+ struct instance {
570
+ PyObject_HEAD
571
+ /// Storage for pointers and holder; see simple_layout, below, for a description
572
+ union {
573
+ void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
574
+ nonsimple_values_and_holders nonsimple;
575
+ };
576
+ /// Weak references
577
+ PyObject *weakrefs;
578
+ /// If true, the pointer is owned which means we're free to manage it with a holder.
579
+ bool owned : 1;
580
+ /**
581
+ * An instance has two possible value/holder layouts.
582
+ *
583
+ * Simple layout (when this flag is true), means the `simple_value_holder` is set with a
584
+ * pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
585
+ * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
586
+ * type's holder will fit in the default space (which is large enough to hold either a
587
+ * std::unique_ptr or std::shared_ptr).
588
+ *
589
+ * Non-simple layout applies when using custom holders that require more space than
590
+ * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
591
+ * used on the python side. Non-simple layout allocates the required amount of memory to have
592
+ * multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
593
+ * set to a pointer to allocated space of the required space to hold a sequence of value
594
+ * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
595
+ * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
596
+ * of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
597
+ * the [bb...] block (but not independently allocated).
598
+ *
599
+ * Status bits indicate whether the associated holder is constructed (&
600
+ * status_holder_constructed) and whether the value pointer is registered (&
601
+ * status_instance_registered) in `registered_instances`.
602
+ */
603
+ bool simple_layout : 1;
604
+ /// For simple layout, tracks whether the holder has been constructed
605
+ bool simple_holder_constructed : 1;
606
+ /// For simple layout, tracks whether the instance is registered in `registered_instances`
607
+ bool simple_instance_registered : 1;
608
+ /// If true, get_internals().patients has an entry for this object
609
+ bool has_patients : 1;
610
+
611
+ /// Initializes all of the above type/values/holders data (but not the instance values
612
+ /// themselves)
613
+ void allocate_layout();
614
+
615
+ /// Destroys/deallocates all of the above
616
+ void deallocate_layout();
617
+
618
+ /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
619
+ /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
620
+ /// `throw_if_missing` is false.
621
+ value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
622
+ bool throw_if_missing = true);
623
+
624
+ /// Bit values for the non-simple status flags
625
+ static constexpr uint8_t status_holder_constructed = 1;
626
+ static constexpr uint8_t status_instance_registered = 2;
627
+ };
628
+
629
+ static_assert(std::is_standard_layout<instance>::value,
630
+ "Internal error: `pybind11::detail::instance` is not standard layout!");
631
+
632
+ /// from __cpp_future__ import (convenient aliases from C++14/17)
633
+ #if defined(PYBIND11_CPP14)
634
+ using std::conditional_t;
635
+ using std::enable_if_t;
636
+ using std::remove_cv_t;
637
+ using std::remove_reference_t;
638
+ #else
639
+ template <bool B, typename T = void>
640
+ using enable_if_t = typename std::enable_if<B, T>::type;
641
+ template <bool B, typename T, typename F>
642
+ using conditional_t = typename std::conditional<B, T, F>::type;
643
+ template <typename T>
644
+ using remove_cv_t = typename std::remove_cv<T>::type;
645
+ template <typename T>
646
+ using remove_reference_t = typename std::remove_reference<T>::type;
647
+ #endif
648
+
649
+ #if defined(PYBIND11_CPP20)
650
+ using std::remove_cvref;
651
+ using std::remove_cvref_t;
652
+ #else
653
+ template <class T>
654
+ struct remove_cvref {
655
+ using type = remove_cv_t<remove_reference_t<T>>;
656
+ };
657
+ template <class T>
658
+ using remove_cvref_t = typename remove_cvref<T>::type;
659
+ #endif
660
+
661
+ /// Example usage: is_same_ignoring_cvref<T, PyObject *>::value
662
+ template <typename T, typename U>
663
+ using is_same_ignoring_cvref = std::is_same<detail::remove_cvref_t<T>, U>;
664
+
665
+ /// Index sequences
666
+ #if defined(PYBIND11_CPP14)
667
+ using std::index_sequence;
668
+ using std::make_index_sequence;
669
+ #else
670
+ template <size_t...>
671
+ struct index_sequence {};
672
+ template <size_t N, size_t... S>
673
+ struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
674
+ template <size_t... S>
675
+ struct make_index_sequence_impl<0, S...> {
676
+ using type = index_sequence<S...>;
677
+ };
678
+ template <size_t N>
679
+ using make_index_sequence = typename make_index_sequence_impl<N>::type;
680
+ #endif
681
+
682
+ /// Make an index sequence of the indices of true arguments
683
+ template <typename ISeq, size_t, bool...>
684
+ struct select_indices_impl {
685
+ using type = ISeq;
686
+ };
687
+ template <size_t... IPrev, size_t I, bool B, bool... Bs>
688
+ struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
689
+ : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
690
+ I + 1,
691
+ Bs...> {};
692
+ template <bool... Bs>
693
+ using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
694
+
695
+ /// Backports of std::bool_constant and std::negation to accommodate older compilers
696
+ template <bool B>
697
+ using bool_constant = std::integral_constant<bool, B>;
698
+ template <typename T>
699
+ struct negation : bool_constant<!T::value> {};
700
+
701
+ // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
702
+ // using the new one (C++14 defect, so generally works on newer compilers, even
703
+ // if not in C++17 mode)
704
+ #if defined(__PGIC__) || defined(__INTEL_COMPILER)
705
+ template <typename...>
706
+ using void_t = void;
707
+ #else
708
+ template <typename...>
709
+ struct void_t_impl {
710
+ using type = void;
711
+ };
712
+ template <typename... Ts>
713
+ using void_t = typename void_t_impl<Ts...>::type;
714
+ #endif
715
+
716
+ /// Compile-time all/any/none of that check the boolean value of all template types
717
+ #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
718
+ template <class... Ts>
719
+ using all_of = bool_constant<(Ts::value && ...)>;
720
+ template <class... Ts>
721
+ using any_of = bool_constant<(Ts::value || ...)>;
722
+ #elif !defined(_MSC_VER)
723
+ template <bool...>
724
+ struct bools {};
725
+ template <class... Ts>
726
+ using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
727
+ template <class... Ts>
728
+ using any_of = negation<all_of<negation<Ts>...>>;
729
+ #else
730
+ // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
731
+ // at a slight loss of compilation efficiency).
732
+ template <class... Ts>
733
+ using all_of = std::conjunction<Ts...>;
734
+ template <class... Ts>
735
+ using any_of = std::disjunction<Ts...>;
736
+ #endif
737
+ template <class... Ts>
738
+ using none_of = negation<any_of<Ts...>>;
739
+
740
+ template <class T, template <class> class... Predicates>
741
+ using satisfies_all_of = all_of<Predicates<T>...>;
742
+ template <class T, template <class> class... Predicates>
743
+ using satisfies_any_of = any_of<Predicates<T>...>;
744
+ template <class T, template <class> class... Predicates>
745
+ using satisfies_none_of = none_of<Predicates<T>...>;
746
+
747
+ /// Strip the class from a method type
748
+ template <typename T>
749
+ struct remove_class {};
750
+ template <typename C, typename R, typename... A>
751
+ struct remove_class<R (C::*)(A...)> {
752
+ using type = R(A...);
753
+ };
754
+ template <typename C, typename R, typename... A>
755
+ struct remove_class<R (C::*)(A...) const> {
756
+ using type = R(A...);
757
+ };
758
+ #ifdef __cpp_noexcept_function_type
759
+ template <typename C, typename R, typename... A>
760
+ struct remove_class<R (C::*)(A...) noexcept> {
761
+ using type = R(A...);
762
+ };
763
+ template <typename C, typename R, typename... A>
764
+ struct remove_class<R (C::*)(A...) const noexcept> {
765
+ using type = R(A...);
766
+ };
767
+ #endif
768
+ /// Helper template to strip away type modifiers
769
+ template <typename T>
770
+ struct intrinsic_type {
771
+ using type = T;
772
+ };
773
+ template <typename T>
774
+ struct intrinsic_type<const T> {
775
+ using type = typename intrinsic_type<T>::type;
776
+ };
777
+ template <typename T>
778
+ struct intrinsic_type<T *> {
779
+ using type = typename intrinsic_type<T>::type;
780
+ };
781
+ template <typename T>
782
+ struct intrinsic_type<T &> {
783
+ using type = typename intrinsic_type<T>::type;
784
+ };
785
+ template <typename T>
786
+ struct intrinsic_type<T &&> {
787
+ using type = typename intrinsic_type<T>::type;
788
+ };
789
+ template <typename T, size_t N>
790
+ struct intrinsic_type<const T[N]> {
791
+ using type = typename intrinsic_type<T>::type;
792
+ };
793
+ template <typename T, size_t N>
794
+ struct intrinsic_type<T[N]> {
795
+ using type = typename intrinsic_type<T>::type;
796
+ };
797
+ template <typename T>
798
+ using intrinsic_t = typename intrinsic_type<T>::type;
799
+
800
+ /// Helper type to replace 'void' in some expressions
801
+ struct void_type {};
802
+
803
+ /// Helper template which holds a list of types
804
+ template <typename...>
805
+ struct type_list {};
806
+
807
+ /// Compile-time integer sum
808
+ #ifdef __cpp_fold_expressions
809
+ template <typename... Ts>
810
+ constexpr size_t constexpr_sum(Ts... ns) {
811
+ return (0 + ... + size_t{ns});
812
+ }
813
+ #else
814
+ constexpr size_t constexpr_sum() { return 0; }
815
+ template <typename T, typename... Ts>
816
+ constexpr size_t constexpr_sum(T n, Ts... ns) {
817
+ return size_t{n} + constexpr_sum(ns...);
818
+ }
819
+ #endif
820
+
821
+ PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
822
+ /// Implementation details for constexpr functions
823
+ constexpr int first(int i) { return i; }
824
+ template <typename T, typename... Ts>
825
+ constexpr int first(int i, T v, Ts... vs) {
826
+ return v ? i : first(i + 1, vs...);
827
+ }
828
+
829
+ constexpr int last(int /*i*/, int result) { return result; }
830
+ template <typename T, typename... Ts>
831
+ constexpr int last(int i, int result, T v, Ts... vs) {
832
+ return last(i + 1, v ? i : result, vs...);
833
+ }
834
+ PYBIND11_NAMESPACE_END(constexpr_impl)
835
+
836
+ /// Return the index of the first type in Ts which satisfies Predicate<T>.
837
+ /// Returns sizeof...(Ts) if none match.
838
+ template <template <typename> class Predicate, typename... Ts>
839
+ constexpr int constexpr_first() {
840
+ return constexpr_impl::first(0, Predicate<Ts>::value...);
841
+ }
842
+
843
+ /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
844
+ template <template <typename> class Predicate, typename... Ts>
845
+ constexpr int constexpr_last() {
846
+ return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
847
+ }
848
+
849
+ /// Return the Nth element from the parameter pack
850
+ template <size_t N, typename T, typename... Ts>
851
+ struct pack_element {
852
+ using type = typename pack_element<N - 1, Ts...>::type;
853
+ };
854
+ template <typename T, typename... Ts>
855
+ struct pack_element<0, T, Ts...> {
856
+ using type = T;
857
+ };
858
+
859
+ /// Return the one and only type which matches the predicate, or Default if none match.
860
+ /// If more than one type matches the predicate, fail at compile-time.
861
+ template <template <typename> class Predicate, typename Default, typename... Ts>
862
+ struct exactly_one {
863
+ static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
864
+ static_assert(found <= 1, "Found more than one type matching the predicate");
865
+
866
+ static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
867
+ using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
868
+ };
869
+ template <template <typename> class P, typename Default>
870
+ struct exactly_one<P, Default> {
871
+ using type = Default;
872
+ };
873
+
874
+ template <template <typename> class Predicate, typename Default, typename... Ts>
875
+ using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
876
+
877
+ /// Defer the evaluation of type T until types Us are instantiated
878
+ template <typename T, typename... /*Us*/>
879
+ struct deferred_type {
880
+ using type = T;
881
+ };
882
+ template <typename T, typename... Us>
883
+ using deferred_t = typename deferred_type<T, Us...>::type;
884
+
885
+ /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
886
+ /// unlike `std::is_base_of`)
887
+ template <typename Base, typename Derived>
888
+ using is_strict_base_of
889
+ = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
890
+
891
+ /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
892
+ /// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
893
+ /// we need to check `is_same` as well.
894
+ template <typename Base, typename Derived>
895
+ using is_accessible_base_of
896
+ = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
897
+ && std::is_convertible<Derived *, Base *>::value>;
898
+
899
+ template <template <typename...> class Base>
900
+ struct is_template_base_of_impl {
901
+ template <typename... Us>
902
+ static std::true_type check(Base<Us...> *);
903
+ static std::false_type check(...);
904
+ };
905
+
906
+ /// Check if a template is the base of a type. For example:
907
+ /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
908
+ template <template <typename...> class Base, typename T>
909
+ // Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
910
+ // See also: https://github.com/pybind/pybind11/pull/3741
911
+ #if !defined(_MSC_VER)
912
+ using is_template_base_of
913
+ = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
914
+ #else
915
+ struct is_template_base_of
916
+ : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
917
+ };
918
+ #endif
919
+
920
+ /// Check if T is an instantiation of the template `Class`. For example:
921
+ /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
922
+ template <template <typename...> class Class, typename T>
923
+ struct is_instantiation : std::false_type {};
924
+ template <template <typename...> class Class, typename... Us>
925
+ struct is_instantiation<Class, Class<Us...>> : std::true_type {};
926
+
927
+ /// Check if T is std::shared_ptr<U> where U can be anything
928
+ template <typename T>
929
+ using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
930
+
931
+ /// Check if T looks like an input iterator
932
+ template <typename T, typename = void>
933
+ struct is_input_iterator : std::false_type {};
934
+ template <typename T>
935
+ struct is_input_iterator<T,
936
+ void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
937
+ : std::true_type {};
938
+
939
+ template <typename T>
940
+ using is_function_pointer
941
+ = bool_constant<std::is_pointer<T>::value
942
+ && std::is_function<typename std::remove_pointer<T>::type>::value>;
943
+
944
+ template <typename F>
945
+ struct strip_function_object {
946
+ // If you are encountering an
947
+ // 'error: name followed by "::" must be a class or namespace name'
948
+ // with the Intel compiler and a noexcept function here,
949
+ // try to use noexcept(true) instead of plain noexcept.
950
+ using type = typename remove_class<decltype(&F::operator())>::type;
951
+ };
952
+
953
+ // Extracts the function signature from a function, function pointer or lambda.
954
+ template <typename Function, typename F = remove_reference_t<Function>>
955
+ using function_signature_t = conditional_t<
956
+ std::is_function<F>::value,
957
+ F,
958
+ typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
959
+ std::remove_pointer<F>,
960
+ strip_function_object<F>>::type>;
961
+
962
+ /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
963
+ /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
964
+ /// in a place where passing a lambda makes sense.
965
+ template <typename T>
966
+ using is_lambda = satisfies_none_of<remove_reference_t<T>,
967
+ std::is_function,
968
+ std::is_pointer,
969
+ std::is_member_pointer>;
970
+
971
+ // [workaround(intel)] Internal error on fold expression
972
+ /// Apply a function over each element of a parameter pack
973
+ #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
974
+ // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
975
+ # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
976
+ #else
977
+ using expand_side_effects = bool[];
978
+ # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
979
+ (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
980
+ #endif
981
+
982
+ PYBIND11_NAMESPACE_END(detail)
983
+
984
+ /// C++ bindings of builtin Python exceptions
985
+ class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
986
+ public:
987
+ using std::runtime_error::runtime_error;
988
+ /// Set the error using the Python C API
989
+ virtual void set_error() const = 0;
990
+ };
991
+
992
+ #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
993
+ class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
994
+ public: \
995
+ using builtin_exception::builtin_exception; \
996
+ name() : name("") {} \
997
+ void set_error() const override { PyErr_SetString(type, what()); } \
998
+ };
999
+
1000
+ PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
1001
+ PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
1002
+ PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
1003
+ PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
1004
+ PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
1005
+ PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
1006
+ PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
1007
+ PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
1008
+ PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
1009
+ /// handle::call fail due to a type
1010
+ /// casting error
1011
+ PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
1012
+
1013
+ [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
1014
+ assert(!PyErr_Occurred());
1015
+ throw std::runtime_error(reason);
1016
+ }
1017
+ [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
1018
+ assert(!PyErr_Occurred());
1019
+ throw std::runtime_error(reason);
1020
+ }
1021
+
1022
+ template <typename T, typename SFINAE = void>
1023
+ struct format_descriptor {};
1024
+
1025
+ template <typename T>
1026
+ struct format_descriptor<
1027
+ T,
1028
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value>> {
1029
+ static constexpr const char c = 'O';
1030
+ static constexpr const char value[2] = {c, '\0'};
1031
+ static std::string format() { return std::string(1, c); }
1032
+ };
1033
+
1034
+ PYBIND11_NAMESPACE_BEGIN(detail)
1035
+ // Returns the index of the given type in the type char array below, and in the list in numpy.h
1036
+ // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
1037
+ // complex float,double,long double. Note that the long double types only participate when long
1038
+ // double is actually longer than double (it isn't under MSVC).
1039
+ // NB: not only the string below but also complex.h and numpy.h rely on this order.
1040
+ template <typename T, typename SFINAE = void>
1041
+ struct is_fmt_numeric {
1042
+ static constexpr bool value = false;
1043
+ };
1044
+ template <typename T>
1045
+ struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
1046
+ static constexpr bool value = true;
1047
+ static constexpr int index
1048
+ = std::is_same<T, bool>::value
1049
+ ? 0
1050
+ : 1
1051
+ + (std::is_integral<T>::value
1052
+ ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
1053
+ : 8
1054
+ + (std::is_same<T, double>::value ? 1
1055
+ : std::is_same<T, long double>::value ? 2
1056
+ : 0));
1057
+ };
1058
+ PYBIND11_NAMESPACE_END(detail)
1059
+
1060
+ template <typename T>
1061
+ struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
1062
+ static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
1063
+ static constexpr const char value[2] = {c, '\0'};
1064
+ static std::string format() { return std::string(1, c); }
1065
+ };
1066
+
1067
+ #if !defined(PYBIND11_CPP17)
1068
+
1069
+ template <typename T>
1070
+ constexpr const char
1071
+ format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
1072
+
1073
+ #endif
1074
+
1075
+ /// RAII wrapper that temporarily clears any Python error state
1076
+ struct error_scope {
1077
+ PyObject *type, *value, *trace;
1078
+ error_scope() { PyErr_Fetch(&type, &value, &trace); }
1079
+ error_scope(const error_scope &) = delete;
1080
+ error_scope &operator=(const error_scope &) = delete;
1081
+ ~error_scope() { PyErr_Restore(type, value, trace); }
1082
+ };
1083
+
1084
+ /// Dummy destructor wrapper that can be used to expose classes with a private destructor
1085
+ struct nodelete {
1086
+ template <typename T>
1087
+ void operator()(T *) {}
1088
+ };
1089
+
1090
+ PYBIND11_NAMESPACE_BEGIN(detail)
1091
+ template <typename... Args>
1092
+ struct overload_cast_impl {
1093
+ template <typename Return>
1094
+ constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
1095
+ return pf;
1096
+ }
1097
+
1098
+ template <typename Return, typename Class>
1099
+ constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
1100
+ -> decltype(pmf) {
1101
+ return pmf;
1102
+ }
1103
+
1104
+ template <typename Return, typename Class>
1105
+ constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
1106
+ -> decltype(pmf) {
1107
+ return pmf;
1108
+ }
1109
+ };
1110
+ PYBIND11_NAMESPACE_END(detail)
1111
+
1112
+ // overload_cast requires variable templates: C++14
1113
+ #if defined(PYBIND11_CPP14)
1114
+ # define PYBIND11_OVERLOAD_CAST 1
1115
+ /// Syntax sugar for resolving overloaded function pointers:
1116
+ /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
1117
+ /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
1118
+ template <typename... Args>
1119
+ static constexpr detail::overload_cast_impl<Args...> overload_cast{};
1120
+ #endif
1121
+
1122
+ /// Const member function selector for overload_cast
1123
+ /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
1124
+ /// - sweet: overload_cast<Arg>(&Class::func, const_)
1125
+ static constexpr auto const_ = std::true_type{};
1126
+
1127
+ #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
1128
+ template <typename... Args>
1129
+ struct overload_cast {
1130
+ static_assert(detail::deferred_t<std::false_type, Args...>::value,
1131
+ "pybind11::overload_cast<...> requires compiling in C++14 mode");
1132
+ };
1133
+ #endif // overload_cast
1134
+
1135
+ PYBIND11_NAMESPACE_BEGIN(detail)
1136
+
1137
+ // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
1138
+ // any standard container (or C-style array) supporting std::begin/std::end, any singleton
1139
+ // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
1140
+ template <typename T>
1141
+ class any_container {
1142
+ std::vector<T> v;
1143
+
1144
+ public:
1145
+ any_container() = default;
1146
+
1147
+ // Can construct from a pair of iterators
1148
+ template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
1149
+ any_container(It first, It last) : v(first, last) {}
1150
+
1151
+ // Implicit conversion constructor from any arbitrary container type
1152
+ // with values convertible to T
1153
+ template <typename Container,
1154
+ typename = enable_if_t<
1155
+ std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
1156
+ T>::value>>
1157
+ // NOLINTNEXTLINE(google-explicit-constructor)
1158
+ any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
1159
+
1160
+ // initializer_list's aren't deducible, so don't get matched by the above template;
1161
+ // we need this to explicitly allow implicit conversion from one:
1162
+ template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
1163
+ any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
1164
+
1165
+ // Avoid copying if given an rvalue vector of the correct type.
1166
+ // NOLINTNEXTLINE(google-explicit-constructor)
1167
+ any_container(std::vector<T> &&v) : v(std::move(v)) {}
1168
+
1169
+ // Moves the vector out of an rvalue any_container
1170
+ // NOLINTNEXTLINE(google-explicit-constructor)
1171
+ operator std::vector<T> &&() && { return std::move(v); }
1172
+
1173
+ // Dereferencing obtains a reference to the underlying vector
1174
+ std::vector<T> &operator*() { return v; }
1175
+ const std::vector<T> &operator*() const { return v; }
1176
+
1177
+ // -> lets you call methods on the underlying vector
1178
+ std::vector<T> *operator->() { return &v; }
1179
+ const std::vector<T> *operator->() const { return &v; }
1180
+ };
1181
+
1182
+ // Forward-declaration; see detail/class.h
1183
+ std::string get_fully_qualified_tp_name(PyTypeObject *);
1184
+
1185
+ template <typename T>
1186
+ inline static std::shared_ptr<T>
1187
+ try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
1188
+ // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
1189
+ // Use at your own risk!
1190
+ // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
1191
+ // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
1192
+ #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1193
+ return holder_value_ptr->weak_from_this().lock();
1194
+ #else
1195
+ try {
1196
+ return holder_value_ptr->shared_from_this();
1197
+ } catch (const std::bad_weak_ptr &) {
1198
+ return nullptr;
1199
+ }
1200
+ #endif
1201
+ }
1202
+
1203
+ // For silencing "unused" compiler warnings in special situations.
1204
+ template <typename... Args>
1205
+ #if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
1206
+ constexpr
1207
+ #endif
1208
+ inline void
1209
+ silence_unused_warnings(Args &&...) {
1210
+ }
1211
+
1212
+ // MSVC warning C4100: Unreferenced formal parameter
1213
+ #if defined(_MSC_VER) && _MSC_VER <= 1916
1214
+ # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
1215
+ detail::silence_unused_warnings(__VA_ARGS__)
1216
+ #else
1217
+ # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
1218
+ #endif
1219
+
1220
+ // GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
1221
+ #if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
1222
+ # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
1223
+ detail::silence_unused_warnings(__VA_ARGS__)
1224
+ #else
1225
+ # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
1226
+ #endif
1227
+
1228
+ #if defined(__clang__) \
1229
+ && (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point \
1230
+ available. */ \
1231
+ || (__clang_major__ >= 7 \
1232
+ && __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */ \
1233
+ )
1234
+ # define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
1235
+ // Example:
1236
+ // tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite
1237
+ // being returned by name [-Werror,-Wreturn-std-move]
1238
+ // m.def("args_function", [](py::args args) -> py::tuple { return args; });
1239
+ // ^~~~
1240
+ // test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying
1241
+ // m.def("args_function", [](py::args args) -> py::tuple { return args; });
1242
+ // ^~~~
1243
+ // std::move(args)
1244
+ #endif
1245
+
1246
+ // Pybind offers detailed error messages by default for all builts that are debug (through the
1247
+ // negation of NDEBUG). This can also be manually enabled by users, for any builds, through
1248
+ // defining PYBIND11_DETAILED_ERROR_MESSAGES. This information is primarily useful for those
1249
+ // who are writing (as opposed to merely using) libraries that use pybind11.
1250
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
1251
+ # define PYBIND11_DETAILED_ERROR_MESSAGES
1252
+ #endif
1253
+
1254
+ PYBIND11_NAMESPACE_END(detail)
1255
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/descr.h ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ #if !defined(_MSC_VER)
18
+ # define PYBIND11_DESCR_CONSTEXPR static constexpr
19
+ #else
20
+ # define PYBIND11_DESCR_CONSTEXPR const
21
+ #endif
22
+
23
+ /* Concatenate type signatures at compile time */
24
+ template <size_t N, typename... Ts>
25
+ struct descr {
26
+ char text[N + 1]{'\0'};
27
+
28
+ constexpr descr() = default;
29
+ // NOLINTNEXTLINE(google-explicit-constructor)
30
+ constexpr descr(char const (&s)[N + 1]) : descr(s, make_index_sequence<N>()) {}
31
+
32
+ template <size_t... Is>
33
+ constexpr descr(char const (&s)[N + 1], index_sequence<Is...>) : text{s[Is]..., '\0'} {}
34
+
35
+ template <typename... Chars>
36
+ // NOLINTNEXTLINE(google-explicit-constructor)
37
+ constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} {}
38
+
39
+ static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {
40
+ return {{&typeid(Ts)..., nullptr}};
41
+ }
42
+ };
43
+
44
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>
45
+ constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a,
46
+ const descr<N2, Ts2...> &b,
47
+ index_sequence<Is1...>,
48
+ index_sequence<Is2...>) {
49
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(b);
50
+ return {a.text[Is1]..., b.text[Is2]...};
51
+ }
52
+
53
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
54
+ constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a,
55
+ const descr<N2, Ts2...> &b) {
56
+ return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());
57
+ }
58
+
59
+ template <size_t N>
60
+ constexpr descr<N - 1> const_name(char const (&text)[N]) {
61
+ return descr<N - 1>(text);
62
+ }
63
+ constexpr descr<0> const_name(char const (&)[1]) { return {}; }
64
+
65
+ template <size_t Rem, size_t... Digits>
66
+ struct int_to_str : int_to_str<Rem / 10, Rem % 10, Digits...> {};
67
+ template <size_t... Digits>
68
+ struct int_to_str<0, Digits...> {
69
+ // WARNING: This only works with C++17 or higher.
70
+ static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);
71
+ };
72
+
73
+ // Ternary description (like std::conditional)
74
+ template <bool B, size_t N1, size_t N2>
75
+ constexpr enable_if_t<B, descr<N1 - 1>> const_name(char const (&text1)[N1], char const (&)[N2]) {
76
+ return const_name(text1);
77
+ }
78
+ template <bool B, size_t N1, size_t N2>
79
+ constexpr enable_if_t<!B, descr<N2 - 1>> const_name(char const (&)[N1], char const (&text2)[N2]) {
80
+ return const_name(text2);
81
+ }
82
+
83
+ template <bool B, typename T1, typename T2>
84
+ constexpr enable_if_t<B, T1> const_name(const T1 &d, const T2 &) {
85
+ return d;
86
+ }
87
+ template <bool B, typename T1, typename T2>
88
+ constexpr enable_if_t<!B, T2> const_name(const T1 &, const T2 &d) {
89
+ return d;
90
+ }
91
+
92
+ template <size_t Size>
93
+ auto constexpr const_name() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
94
+ return int_to_str<Size / 10, Size % 10>::digits;
95
+ }
96
+
97
+ template <typename Type>
98
+ constexpr descr<1, Type> const_name() {
99
+ return {'%'};
100
+ }
101
+
102
+ // If "_" is defined as a macro, py::detail::_ cannot be provided.
103
+ // It is therefore best to use py::detail::const_name universally.
104
+ // This block is for backward compatibility only.
105
+ // (The const_name code is repeated to avoid introducing a "_" #define ourselves.)
106
+ #ifndef _
107
+ # define PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
108
+ template <size_t N>
109
+ constexpr descr<N - 1> _(char const (&text)[N]) {
110
+ return const_name<N>(text);
111
+ }
112
+ template <bool B, size_t N1, size_t N2>
113
+ constexpr enable_if_t<B, descr<N1 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
114
+ return const_name<B, N1, N2>(text1, text2);
115
+ }
116
+ template <bool B, size_t N1, size_t N2>
117
+ constexpr enable_if_t<!B, descr<N2 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
118
+ return const_name<B, N1, N2>(text1, text2);
119
+ }
120
+ template <bool B, typename T1, typename T2>
121
+ constexpr enable_if_t<B, T1> _(const T1 &d1, const T2 &d2) {
122
+ return const_name<B, T1, T2>(d1, d2);
123
+ }
124
+ template <bool B, typename T1, typename T2>
125
+ constexpr enable_if_t<!B, T2> _(const T1 &d1, const T2 &d2) {
126
+ return const_name<B, T1, T2>(d1, d2);
127
+ }
128
+
129
+ template <size_t Size>
130
+ auto constexpr _() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
131
+ return const_name<Size>();
132
+ }
133
+ template <typename Type>
134
+ constexpr descr<1, Type> _() {
135
+ return const_name<Type>();
136
+ }
137
+ #endif // #ifndef _
138
+
139
+ constexpr descr<0> concat() { return {}; }
140
+
141
+ template <size_t N, typename... Ts>
142
+ constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) {
143
+ return descr;
144
+ }
145
+
146
+ #ifdef __cpp_fold_expressions
147
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
148
+ constexpr descr<N1 + N2 + 2, Ts1..., Ts2...> operator,(const descr<N1, Ts1...> &a,
149
+ const descr<N2, Ts2...> &b) {
150
+ return a + const_name(", ") + b;
151
+ }
152
+
153
+ template <size_t N, typename... Ts, typename... Args>
154
+ constexpr auto concat(const descr<N, Ts...> &d, const Args &...args) {
155
+ return (d, ..., args);
156
+ }
157
+ #else
158
+ template <size_t N, typename... Ts, typename... Args>
159
+ constexpr auto concat(const descr<N, Ts...> &d, const Args &...args)
160
+ -> decltype(std::declval<descr<N + 2, Ts...>>() + concat(args...)) {
161
+ return d + const_name(", ") + concat(args...);
162
+ }
163
+ #endif
164
+
165
+ template <size_t N, typename... Ts>
166
+ constexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {
167
+ return const_name("{") + descr + const_name("}");
168
+ }
169
+
170
+ PYBIND11_NAMESPACE_END(detail)
171
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/init.h ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/init.h: init factory function implementation and support code.
3
+
4
+ Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "class.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+
16
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(detail)
19
+
20
+ template <>
21
+ class type_caster<value_and_holder> {
22
+ public:
23
+ bool load(handle h, bool) {
24
+ value = reinterpret_cast<value_and_holder *>(h.ptr());
25
+ return true;
26
+ }
27
+
28
+ template <typename>
29
+ using cast_op_type = value_and_holder &;
30
+ explicit operator value_and_holder &() { return *value; }
31
+ static constexpr auto name = const_name<value_and_holder>();
32
+
33
+ private:
34
+ value_and_holder *value = nullptr;
35
+ };
36
+
37
+ PYBIND11_NAMESPACE_BEGIN(initimpl)
38
+
39
+ inline void no_nullptr(void *ptr) {
40
+ if (!ptr) {
41
+ throw type_error("pybind11::init(): factory function returned nullptr");
42
+ }
43
+ }
44
+
45
+ // Implementing functions for all forms of py::init<...> and py::init(...)
46
+ template <typename Class>
47
+ using Cpp = typename Class::type;
48
+ template <typename Class>
49
+ using Alias = typename Class::type_alias;
50
+ template <typename Class>
51
+ using Holder = typename Class::holder_type;
52
+
53
+ template <typename Class>
54
+ using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
55
+
56
+ // Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
57
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
58
+ bool is_alias(Cpp<Class> *ptr) {
59
+ return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
60
+ }
61
+ // Failing fallback version of the above for a no-alias class (always returns false)
62
+ template <typename /*Class*/>
63
+ constexpr bool is_alias(void *) {
64
+ return false;
65
+ }
66
+
67
+ // Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
68
+ // back to brace aggregate initiailization so that for aggregate initialization can be used with
69
+ // py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
70
+ // non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
71
+ // works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
72
+ template <typename Class,
73
+ typename... Args,
74
+ detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
75
+ inline Class *construct_or_initialize(Args &&...args) {
76
+ return new Class(std::forward<Args>(args)...);
77
+ }
78
+ template <typename Class,
79
+ typename... Args,
80
+ detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
81
+ inline Class *construct_or_initialize(Args &&...args) {
82
+ return new Class{std::forward<Args>(args)...};
83
+ }
84
+
85
+ // Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
86
+ // an alias to provide only a single Cpp factory function as long as the Alias can be
87
+ // constructed from an rvalue reference of the base Cpp type. This means that Alias classes
88
+ // can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
89
+ // inherit all the base class constructors.
90
+ template <typename Class>
91
+ void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
92
+ value_and_holder &v_h,
93
+ Cpp<Class> &&base) {
94
+ v_h.value_ptr() = new Alias<Class>(std::move(base));
95
+ }
96
+ template <typename Class>
97
+ [[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
98
+ value_and_holder &,
99
+ Cpp<Class> &&) {
100
+ throw type_error("pybind11::init(): unable to convert returned instance to required "
101
+ "alias class: no `Alias<Class>(Class &&)` constructor available");
102
+ }
103
+
104
+ // Error-generating fallback for factories that don't match one of the below construction
105
+ // mechanisms.
106
+ template <typename Class>
107
+ void construct(...) {
108
+ static_assert(!std::is_same<Class, Class>::value /* always false */,
109
+ "pybind11::init(): init function must return a compatible pointer, "
110
+ "holder, or value");
111
+ }
112
+
113
+ // Pointer return v1: the factory function returns a class pointer for a registered class.
114
+ // If we don't need an alias (because this class doesn't have one, or because the final type is
115
+ // inherited on the Python side) we can simply take over ownership. Otherwise we need to try to
116
+ // construct an Alias from the returned base instance.
117
+ template <typename Class>
118
+ void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
119
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
120
+ no_nullptr(ptr);
121
+ if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
122
+ // We're going to try to construct an alias by moving the cpp type. Whether or not
123
+ // that succeeds, we still need to destroy the original cpp pointer (either the
124
+ // moved away leftover, if the alias construction works, or the value itself if we
125
+ // throw an error), but we can't just call `delete ptr`: it might have a special
126
+ // deleter, or might be shared_from_this. So we construct a holder around it as if
127
+ // it was a normal instance, then steal the holder away into a local variable; thus
128
+ // the holder and destruction happens when we leave the C++ scope, and the holder
129
+ // class gets to handle the destruction however it likes.
130
+ v_h.value_ptr() = ptr;
131
+ v_h.set_instance_registered(true); // To prevent init_instance from registering it
132
+ v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
133
+ Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
134
+ v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
135
+ v_h.set_instance_registered(false);
136
+
137
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
138
+ } else {
139
+ // Otherwise the type isn't inherited, so we don't need an Alias
140
+ v_h.value_ptr() = ptr;
141
+ }
142
+ }
143
+
144
+ // Pointer return v2: a factory that always returns an alias instance ptr. We simply take over
145
+ // ownership of the pointer.
146
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
147
+ void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
148
+ no_nullptr(alias_ptr);
149
+ v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
150
+ }
151
+
152
+ // Holder return: copy its pointer, and move or copy the returned holder into the new instance's
153
+ // holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
154
+ // derived type (through those holder's implicit conversion from derived class holder
155
+ // constructors).
156
+ template <typename Class>
157
+ void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
158
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
159
+ auto *ptr = holder_helper<Holder<Class>>::get(holder);
160
+ no_nullptr(ptr);
161
+ // If we need an alias, check that the held pointer is actually an alias instance
162
+ if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
163
+ throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
164
+ "is not an alias instance");
165
+ }
166
+
167
+ v_h.value_ptr() = ptr;
168
+ v_h.type->init_instance(v_h.inst, &holder);
169
+ }
170
+
171
+ // return-by-value version 1: returning a cpp class by value. If the class has an alias and an
172
+ // alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
173
+ // the alias from the base when needed (i.e. because of Python-side inheritance). When we don't
174
+ // need it, we simply move-construct the cpp value into a new instance.
175
+ template <typename Class>
176
+ void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
177
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
178
+ static_assert(is_move_constructible<Cpp<Class>>::value,
179
+ "pybind11::init() return-by-value factory function requires a movable class");
180
+ if (Class::has_alias && need_alias) {
181
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
182
+ } else {
183
+ v_h.value_ptr() = new Cpp<Class>(std::move(result));
184
+ }
185
+ }
186
+
187
+ // return-by-value version 2: returning a value of the alias type itself. We move-construct an
188
+ // Alias instance (even if no the python-side inheritance is involved). The is intended for
189
+ // cases where Alias initialization is always desired.
190
+ template <typename Class>
191
+ void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
192
+ static_assert(
193
+ is_move_constructible<Alias<Class>>::value,
194
+ "pybind11::init() return-by-alias-value factory function requires a movable alias class");
195
+ v_h.value_ptr() = new Alias<Class>(std::move(result));
196
+ }
197
+
198
+ // Implementing class for py::init<...>()
199
+ template <typename... Args>
200
+ struct constructor {
201
+ template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
202
+ static void execute(Class &cl, const Extra &...extra) {
203
+ cl.def(
204
+ "__init__",
205
+ [](value_and_holder &v_h, Args... args) {
206
+ v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
207
+ },
208
+ is_new_style_constructor(),
209
+ extra...);
210
+ }
211
+
212
+ template <
213
+ typename Class,
214
+ typename... Extra,
215
+ enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value, int>
216
+ = 0>
217
+ static void execute(Class &cl, const Extra &...extra) {
218
+ cl.def(
219
+ "__init__",
220
+ [](value_and_holder &v_h, Args... args) {
221
+ if (Py_TYPE(v_h.inst) == v_h.type->type) {
222
+ v_h.value_ptr()
223
+ = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
224
+ } else {
225
+ v_h.value_ptr()
226
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
227
+ }
228
+ },
229
+ is_new_style_constructor(),
230
+ extra...);
231
+ }
232
+
233
+ template <
234
+ typename Class,
235
+ typename... Extra,
236
+ enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value, int>
237
+ = 0>
238
+ static void execute(Class &cl, const Extra &...extra) {
239
+ cl.def(
240
+ "__init__",
241
+ [](value_and_holder &v_h, Args... args) {
242
+ v_h.value_ptr()
243
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
244
+ },
245
+ is_new_style_constructor(),
246
+ extra...);
247
+ }
248
+ };
249
+
250
+ // Implementing class for py::init_alias<...>()
251
+ template <typename... Args>
252
+ struct alias_constructor {
253
+ template <
254
+ typename Class,
255
+ typename... Extra,
256
+ enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int>
257
+ = 0>
258
+ static void execute(Class &cl, const Extra &...extra) {
259
+ cl.def(
260
+ "__init__",
261
+ [](value_and_holder &v_h, Args... args) {
262
+ v_h.value_ptr()
263
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
264
+ },
265
+ is_new_style_constructor(),
266
+ extra...);
267
+ }
268
+ };
269
+
270
+ // Implementation class for py::init(Func) and py::init(Func, AliasFunc)
271
+ template <typename CFunc,
272
+ typename AFunc = void_type (*)(),
273
+ typename = function_signature_t<CFunc>,
274
+ typename = function_signature_t<AFunc>>
275
+ struct factory;
276
+
277
+ // Specialization for py::init(Func)
278
+ template <typename Func, typename Return, typename... Args>
279
+ struct factory<Func, void_type (*)(), Return(Args...)> {
280
+ remove_reference_t<Func> class_factory;
281
+
282
+ // NOLINTNEXTLINE(google-explicit-constructor)
283
+ factory(Func &&f) : class_factory(std::forward<Func>(f)) {}
284
+
285
+ // The given class either has no alias or has no separate alias factory;
286
+ // this always constructs the class itself. If the class is registered with an alias
287
+ // type and an alias instance is needed (i.e. because the final type is a Python class
288
+ // inheriting from the C++ type) the returned value needs to either already be an alias
289
+ // instance, or the alias needs to be constructible from a `Class &&` argument.
290
+ template <typename Class, typename... Extra>
291
+ void execute(Class &cl, const Extra &...extra) && {
292
+ #if defined(PYBIND11_CPP14)
293
+ cl.def(
294
+ "__init__",
295
+ [func = std::move(class_factory)]
296
+ #else
297
+ auto &func = class_factory;
298
+ cl.def(
299
+ "__init__",
300
+ [func]
301
+ #endif
302
+ (value_and_holder &v_h, Args... args) {
303
+ construct<Class>(
304
+ v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);
305
+ },
306
+ is_new_style_constructor(),
307
+ extra...);
308
+ }
309
+ };
310
+
311
+ // Specialization for py::init(Func, AliasFunc)
312
+ template <typename CFunc,
313
+ typename AFunc,
314
+ typename CReturn,
315
+ typename... CArgs,
316
+ typename AReturn,
317
+ typename... AArgs>
318
+ struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
319
+ static_assert(sizeof...(CArgs) == sizeof...(AArgs),
320
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
321
+ "must have identical argument signatures");
322
+ static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
323
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
324
+ "must have identical argument signatures");
325
+
326
+ remove_reference_t<CFunc> class_factory;
327
+ remove_reference_t<AFunc> alias_factory;
328
+
329
+ factory(CFunc &&c, AFunc &&a)
330
+ : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}
331
+
332
+ // The class factory is called when the `self` type passed to `__init__` is the direct
333
+ // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
334
+ template <typename Class, typename... Extra>
335
+ void execute(Class &cl, const Extra &...extra) && {
336
+ static_assert(Class::has_alias,
337
+ "The two-argument version of `py::init()` can "
338
+ "only be used if the class has an alias");
339
+ #if defined(PYBIND11_CPP14)
340
+ cl.def(
341
+ "__init__",
342
+ [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
343
+ #else
344
+ auto &class_func = class_factory;
345
+ auto &alias_func = alias_factory;
346
+ cl.def(
347
+ "__init__",
348
+ [class_func, alias_func]
349
+ #endif
350
+ (value_and_holder &v_h, CArgs... args) {
351
+ if (Py_TYPE(v_h.inst) == v_h.type->type) {
352
+ // If the instance type equals the registered type we don't have inheritance,
353
+ // so don't need the alias and can construct using the class function:
354
+ construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
355
+ } else {
356
+ construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
357
+ }
358
+ },
359
+ is_new_style_constructor(),
360
+ extra...);
361
+ }
362
+ };
363
+
364
+ /// Set just the C++ state. Same as `__init__`.
365
+ template <typename Class, typename T>
366
+ void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
367
+ construct<Class>(v_h, std::forward<T>(result), need_alias);
368
+ }
369
+
370
+ /// Set both the C++ and Python states
371
+ template <typename Class,
372
+ typename T,
373
+ typename O,
374
+ enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
375
+ void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
376
+ construct<Class>(v_h, std::move(result.first), need_alias);
377
+ auto d = handle(result.second);
378
+ if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
379
+ // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
380
+ // See PR #2972 for details.
381
+ return;
382
+ }
383
+ setattr((PyObject *) v_h.inst, "__dict__", d);
384
+ }
385
+
386
+ /// Implementation for py::pickle(GetState, SetState)
387
+ template <typename Get,
388
+ typename Set,
389
+ typename = function_signature_t<Get>,
390
+ typename = function_signature_t<Set>>
391
+ struct pickle_factory;
392
+
393
+ template <typename Get,
394
+ typename Set,
395
+ typename RetState,
396
+ typename Self,
397
+ typename NewInstance,
398
+ typename ArgState>
399
+ struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
400
+ static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
401
+ "The type returned by `__getstate__` must be the same "
402
+ "as the argument accepted by `__setstate__`");
403
+
404
+ remove_reference_t<Get> get;
405
+ remove_reference_t<Set> set;
406
+
407
+ pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}
408
+
409
+ template <typename Class, typename... Extra>
410
+ void execute(Class &cl, const Extra &...extra) && {
411
+ cl.def("__getstate__", std::move(get));
412
+
413
+ #if defined(PYBIND11_CPP14)
414
+ cl.def(
415
+ "__setstate__",
416
+ [func = std::move(set)]
417
+ #else
418
+ auto &func = set;
419
+ cl.def(
420
+ "__setstate__",
421
+ [func]
422
+ #endif
423
+ (value_and_holder &v_h, ArgState state) {
424
+ setstate<Class>(
425
+ v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);
426
+ },
427
+ is_new_style_constructor(),
428
+ extra...);
429
+ }
430
+ };
431
+
432
+ PYBIND11_NAMESPACE_END(initimpl)
433
+ PYBIND11_NAMESPACE_END(detail)
434
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/internals.h ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/internals.h: Internal data structure and related functions
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "common.h"
13
+
14
+ #if defined(WITH_THREAD) && defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
15
+ # include "../gil.h"
16
+ #endif
17
+
18
+ #include "../pytypes.h"
19
+
20
+ #include <exception>
21
+
22
+ /// Tracks the `internals` and `type_info` ABI version independent of the main library version.
23
+ ///
24
+ /// Some portions of the code use an ABI that is conditional depending on this
25
+ /// version number. That allows ABI-breaking changes to be "pre-implemented".
26
+ /// Once the default version number is incremented, the conditional logic that
27
+ /// no longer applies can be removed. Additionally, users that need not
28
+ /// maintain ABI compatibility can increase the version number in order to take
29
+ /// advantage of any functionality/efficiency improvements that depend on the
30
+ /// newer ABI.
31
+ ///
32
+ /// WARNING: If you choose to manually increase the ABI version, note that
33
+ /// pybind11 may not be tested as thoroughly with a non-default ABI version, and
34
+ /// further ABI-incompatible changes may be made before the ABI is officially
35
+ /// changed to the new version.
36
+ #ifndef PYBIND11_INTERNALS_VERSION
37
+ # if PY_VERSION_HEX >= 0x030C0000
38
+ // Version bump for Python 3.12+, before first 3.12 beta release.
39
+ # define PYBIND11_INTERNALS_VERSION 5
40
+ # else
41
+ # define PYBIND11_INTERNALS_VERSION 4
42
+ # endif
43
+ #endif
44
+
45
+ // This requirement is mainly to reduce the support burden (see PR #4570).
46
+ static_assert(PY_VERSION_HEX < 0x030C0000 || PYBIND11_INTERNALS_VERSION >= 5,
47
+ "pybind11 ABI version 5 is the minimum for Python 3.12+");
48
+
49
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
50
+
51
+ using ExceptionTranslator = void (*)(std::exception_ptr);
52
+
53
+ PYBIND11_NAMESPACE_BEGIN(detail)
54
+
55
+ constexpr const char *internals_function_record_capsule_name = "pybind11_function_record_capsule";
56
+
57
+ // Forward declarations
58
+ inline PyTypeObject *make_static_property_type();
59
+ inline PyTypeObject *make_default_metaclass();
60
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass);
61
+
62
+ // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
63
+ // Thread Specific Storage (TSS) API.
64
+ #if PY_VERSION_HEX >= 0x03070000
65
+ // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
66
+ // `Py_LIMITED_API` anyway.
67
+ # if PYBIND11_INTERNALS_VERSION > 4
68
+ # define PYBIND11_TLS_KEY_REF Py_tss_t &
69
+ # if defined(__GNUC__) && !defined(__INTEL_COMPILER)
70
+ // Clang on macOS warns due to `Py_tss_NEEDS_INIT` not specifying an initializer
71
+ // for every field.
72
+ # define PYBIND11_TLS_KEY_INIT(var) \
73
+ _Pragma("GCC diagnostic push") /**/ \
74
+ _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
75
+ Py_tss_t var \
76
+ = Py_tss_NEEDS_INIT; \
77
+ _Pragma("GCC diagnostic pop")
78
+ # else
79
+ # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
80
+ # endif
81
+ # define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
82
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
83
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
84
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
85
+ # define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
86
+ # else
87
+ # define PYBIND11_TLS_KEY_REF Py_tss_t *
88
+ # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
89
+ # define PYBIND11_TLS_KEY_CREATE(var) \
90
+ (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
91
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
92
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
93
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
94
+ # define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
95
+ # endif
96
+ #else
97
+ // Usually an int but a long on Cygwin64 with Python 3.x
98
+ # define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
99
+ # define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0;
100
+ # define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
101
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
102
+ # if defined(PYPY_VERSION)
103
+ // On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
104
+ // the value if it has already been set. Instead, it must first be deleted and
105
+ // then set again.
106
+ inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) {
107
+ PyThread_delete_key_value(key);
108
+ PyThread_set_key_value(key, value);
109
+ }
110
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
111
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) \
112
+ ::pybind11::detail::tls_replace_value((key), (value))
113
+ # else
114
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
115
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
116
+ # endif
117
+ # define PYBIND11_TLS_FREE(key) (void) key
118
+ #endif
119
+
120
+ // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
121
+ // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
122
+ // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
123
+ // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
124
+ // which works. If not under a known-good stl, provide our own name-based hash and equality
125
+ // functions that use the type name.
126
+ #if (PYBIND11_INTERNALS_VERSION <= 4 && defined(__GLIBCXX__)) \
127
+ || (PYBIND11_INTERNALS_VERSION >= 5 && !defined(_LIBCPP_VERSION))
128
+ inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
129
+ using type_hash = std::hash<std::type_index>;
130
+ using type_equal_to = std::equal_to<std::type_index>;
131
+ #else
132
+ inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
133
+ return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
134
+ }
135
+
136
+ struct type_hash {
137
+ size_t operator()(const std::type_index &t) const {
138
+ size_t hash = 5381;
139
+ const char *ptr = t.name();
140
+ while (auto c = static_cast<unsigned char>(*ptr++)) {
141
+ hash = (hash * 33) ^ c;
142
+ }
143
+ return hash;
144
+ }
145
+ };
146
+
147
+ struct type_equal_to {
148
+ bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
149
+ return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
150
+ }
151
+ };
152
+ #endif
153
+
154
+ template <typename value_type>
155
+ using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
156
+
157
+ struct override_hash {
158
+ inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
159
+ size_t value = std::hash<const void *>()(v.first);
160
+ value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
161
+ return value;
162
+ }
163
+ };
164
+
165
+ /// Internal data structure used to track registered instances and types.
166
+ /// Whenever binary incompatible changes are made to this structure,
167
+ /// `PYBIND11_INTERNALS_VERSION` must be incremented.
168
+ struct internals {
169
+ // std::type_index -> pybind11's type information
170
+ type_map<type_info *> registered_types_cpp;
171
+ // PyTypeObject* -> base type_info(s)
172
+ std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
173
+ std::unordered_multimap<const void *, instance *> registered_instances; // void * -> instance*
174
+ std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
175
+ inactive_override_cache;
176
+ type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
177
+ std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
178
+ std::forward_list<ExceptionTranslator> registered_exception_translators;
179
+ std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
180
+ // extensions
181
+ #if PYBIND11_INTERNALS_VERSION == 4
182
+ std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
183
+ #endif
184
+ std::forward_list<std::string> static_strings; // Stores the std::strings backing
185
+ // detail::c_str()
186
+ PyTypeObject *static_property_type;
187
+ PyTypeObject *default_metaclass;
188
+ PyObject *instance_base;
189
+ #if defined(WITH_THREAD)
190
+ // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
191
+ PYBIND11_TLS_KEY_INIT(tstate)
192
+ # if PYBIND11_INTERNALS_VERSION > 4
193
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
194
+ # endif // PYBIND11_INTERNALS_VERSION > 4
195
+ // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
196
+ PyInterpreterState *istate = nullptr;
197
+
198
+ # if PYBIND11_INTERNALS_VERSION > 4
199
+ // Note that we have to use a std::string to allocate memory to ensure a unique address
200
+ // We want unique addresses since we use pointer equality to compare function records
201
+ std::string function_record_capsule_name = internals_function_record_capsule_name;
202
+ # endif
203
+
204
+ internals() = default;
205
+ internals(const internals &other) = delete;
206
+ internals &operator=(const internals &other) = delete;
207
+ ~internals() {
208
+ # if PYBIND11_INTERNALS_VERSION > 4
209
+ PYBIND11_TLS_FREE(loader_life_support_tls_key);
210
+ # endif // PYBIND11_INTERNALS_VERSION > 4
211
+
212
+ // This destructor is called *after* Py_Finalize() in finalize_interpreter().
213
+ // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
214
+ // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
215
+ // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
216
+ // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
217
+ // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
218
+ // that the `tstate` be allocated with the CPython allocator.
219
+ PYBIND11_TLS_FREE(tstate);
220
+ }
221
+ #endif
222
+ };
223
+
224
+ /// Additional type information which does not fit into the PyTypeObject.
225
+ /// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.
226
+ struct type_info {
227
+ PyTypeObject *type;
228
+ const std::type_info *cpptype;
229
+ size_t type_size, type_align, holder_size_in_ptrs;
230
+ void *(*operator_new)(size_t);
231
+ void (*init_instance)(instance *, const void *);
232
+ void (*dealloc)(value_and_holder &v_h);
233
+ std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
234
+ std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
235
+ std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
236
+ buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
237
+ void *get_buffer_data = nullptr;
238
+ void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
239
+ /* A simple type never occurs as a (direct or indirect) parent
240
+ * of a class that makes use of multiple inheritance.
241
+ * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
242
+ */
243
+ bool simple_type : 1;
244
+ /* True if there is no multiple inheritance in this type's inheritance tree */
245
+ bool simple_ancestors : 1;
246
+ /* for base vs derived holder_type checks */
247
+ bool default_holder : 1;
248
+ /* true if this is a type registered with py::module_local */
249
+ bool module_local : 1;
250
+ };
251
+
252
+ /// On MSVC, debug and release builds are not ABI-compatible!
253
+ #if defined(_MSC_VER) && defined(_DEBUG)
254
+ # define PYBIND11_BUILD_TYPE "_debug"
255
+ #else
256
+ # define PYBIND11_BUILD_TYPE ""
257
+ #endif
258
+
259
+ /// Let's assume that different compilers are ABI-incompatible.
260
+ /// A user can manually set this string if they know their
261
+ /// compiler is compatible.
262
+ #ifndef PYBIND11_COMPILER_TYPE
263
+ # if defined(_MSC_VER)
264
+ # define PYBIND11_COMPILER_TYPE "_msvc"
265
+ # elif defined(__INTEL_COMPILER)
266
+ # define PYBIND11_COMPILER_TYPE "_icc"
267
+ # elif defined(__clang__)
268
+ # define PYBIND11_COMPILER_TYPE "_clang"
269
+ # elif defined(__PGI)
270
+ # define PYBIND11_COMPILER_TYPE "_pgi"
271
+ # elif defined(__MINGW32__)
272
+ # define PYBIND11_COMPILER_TYPE "_mingw"
273
+ # elif defined(__CYGWIN__)
274
+ # define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
275
+ # elif defined(__GNUC__)
276
+ # define PYBIND11_COMPILER_TYPE "_gcc"
277
+ # else
278
+ # define PYBIND11_COMPILER_TYPE "_unknown"
279
+ # endif
280
+ #endif
281
+
282
+ /// Also standard libs
283
+ #ifndef PYBIND11_STDLIB
284
+ # if defined(_LIBCPP_VERSION)
285
+ # define PYBIND11_STDLIB "_libcpp"
286
+ # elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
287
+ # define PYBIND11_STDLIB "_libstdcpp"
288
+ # else
289
+ # define PYBIND11_STDLIB ""
290
+ # endif
291
+ #endif
292
+
293
+ /// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility.
294
+ #ifndef PYBIND11_BUILD_ABI
295
+ # if defined(__GXX_ABI_VERSION)
296
+ # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
297
+ # else
298
+ # define PYBIND11_BUILD_ABI ""
299
+ # endif
300
+ #endif
301
+
302
+ #ifndef PYBIND11_INTERNALS_KIND
303
+ # if defined(WITH_THREAD)
304
+ # define PYBIND11_INTERNALS_KIND ""
305
+ # else
306
+ # define PYBIND11_INTERNALS_KIND "_without_thread"
307
+ # endif
308
+ #endif
309
+
310
+ #define PYBIND11_INTERNALS_ID \
311
+ "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
312
+ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
313
+ PYBIND11_BUILD_TYPE "__"
314
+
315
+ #define PYBIND11_MODULE_LOCAL_ID \
316
+ "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
317
+ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
318
+ PYBIND11_BUILD_TYPE "__"
319
+
320
+ /// Each module locally stores a pointer to the `internals` data. The data
321
+ /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
322
+ inline internals **&get_internals_pp() {
323
+ static internals **internals_pp = nullptr;
324
+ return internals_pp;
325
+ }
326
+
327
+ // forward decl
328
+ inline void translate_exception(std::exception_ptr);
329
+
330
+ template <class T,
331
+ enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
332
+ bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
333
+ std::exception_ptr nested = exc.nested_ptr();
334
+ if (nested != nullptr && nested != p) {
335
+ translate_exception(nested);
336
+ return true;
337
+ }
338
+ return false;
339
+ }
340
+
341
+ template <class T,
342
+ enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
343
+ bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
344
+ if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
345
+ return handle_nested_exception(*nep, p);
346
+ }
347
+ return false;
348
+ }
349
+
350
+ inline bool raise_err(PyObject *exc_type, const char *msg) {
351
+ if (PyErr_Occurred()) {
352
+ raise_from(exc_type, msg);
353
+ return true;
354
+ }
355
+ PyErr_SetString(exc_type, msg);
356
+ return false;
357
+ }
358
+
359
+ inline void translate_exception(std::exception_ptr p) {
360
+ if (!p) {
361
+ return;
362
+ }
363
+ try {
364
+ std::rethrow_exception(p);
365
+ } catch (error_already_set &e) {
366
+ handle_nested_exception(e, p);
367
+ e.restore();
368
+ return;
369
+ } catch (const builtin_exception &e) {
370
+ // Could not use template since it's an abstract class.
371
+ if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
372
+ handle_nested_exception(*nep, p);
373
+ }
374
+ e.set_error();
375
+ return;
376
+ } catch (const std::bad_alloc &e) {
377
+ handle_nested_exception(e, p);
378
+ raise_err(PyExc_MemoryError, e.what());
379
+ return;
380
+ } catch (const std::domain_error &e) {
381
+ handle_nested_exception(e, p);
382
+ raise_err(PyExc_ValueError, e.what());
383
+ return;
384
+ } catch (const std::invalid_argument &e) {
385
+ handle_nested_exception(e, p);
386
+ raise_err(PyExc_ValueError, e.what());
387
+ return;
388
+ } catch (const std::length_error &e) {
389
+ handle_nested_exception(e, p);
390
+ raise_err(PyExc_ValueError, e.what());
391
+ return;
392
+ } catch (const std::out_of_range &e) {
393
+ handle_nested_exception(e, p);
394
+ raise_err(PyExc_IndexError, e.what());
395
+ return;
396
+ } catch (const std::range_error &e) {
397
+ handle_nested_exception(e, p);
398
+ raise_err(PyExc_ValueError, e.what());
399
+ return;
400
+ } catch (const std::overflow_error &e) {
401
+ handle_nested_exception(e, p);
402
+ raise_err(PyExc_OverflowError, e.what());
403
+ return;
404
+ } catch (const std::exception &e) {
405
+ handle_nested_exception(e, p);
406
+ raise_err(PyExc_RuntimeError, e.what());
407
+ return;
408
+ } catch (const std::nested_exception &e) {
409
+ handle_nested_exception(e, p);
410
+ raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
411
+ return;
412
+ } catch (...) {
413
+ raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
414
+ return;
415
+ }
416
+ }
417
+
418
+ #if !defined(__GLIBCXX__)
419
+ inline void translate_local_exception(std::exception_ptr p) {
420
+ try {
421
+ if (p) {
422
+ std::rethrow_exception(p);
423
+ }
424
+ } catch (error_already_set &e) {
425
+ e.restore();
426
+ return;
427
+ } catch (const builtin_exception &e) {
428
+ e.set_error();
429
+ return;
430
+ }
431
+ }
432
+ #endif
433
+
434
+ inline object get_python_state_dict() {
435
+ object state_dict;
436
+ #if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
437
+ state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
438
+ #else
439
+ # if PY_VERSION_HEX < 0x03090000
440
+ PyInterpreterState *istate = _PyInterpreterState_Get();
441
+ # else
442
+ PyInterpreterState *istate = PyInterpreterState_Get();
443
+ # endif
444
+ if (istate) {
445
+ state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
446
+ }
447
+ #endif
448
+ if (!state_dict) {
449
+ raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
450
+ }
451
+ return state_dict;
452
+ }
453
+
454
+ inline object get_internals_obj_from_state_dict(handle state_dict) {
455
+ return reinterpret_borrow<object>(dict_getitemstring(state_dict.ptr(), PYBIND11_INTERNALS_ID));
456
+ }
457
+
458
+ inline internals **get_internals_pp_from_capsule(handle obj) {
459
+ void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
460
+ if (raw_ptr == nullptr) {
461
+ raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
462
+ }
463
+ return static_cast<internals **>(raw_ptr);
464
+ }
465
+
466
+ /// Return a reference to the current `internals` data
467
+ PYBIND11_NOINLINE internals &get_internals() {
468
+ auto **&internals_pp = get_internals_pp();
469
+ if (internals_pp && *internals_pp) {
470
+ return **internals_pp;
471
+ }
472
+
473
+ #if defined(WITH_THREAD)
474
+ # if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
475
+ gil_scoped_acquire gil;
476
+ # else
477
+ // Ensure that the GIL is held since we will need to make Python calls.
478
+ // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
479
+ struct gil_scoped_acquire_local {
480
+ gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
481
+ gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
482
+ gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
483
+ ~gil_scoped_acquire_local() { PyGILState_Release(state); }
484
+ const PyGILState_STATE state;
485
+ } gil;
486
+ # endif
487
+ #endif
488
+ error_scope err_scope;
489
+
490
+ dict state_dict = get_python_state_dict();
491
+ if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
492
+ internals_pp = get_internals_pp_from_capsule(internals_obj);
493
+ }
494
+ if (internals_pp && *internals_pp) {
495
+ // We loaded the internals through `state_dict`, which means that our `error_already_set`
496
+ // and `builtin_exception` may be different local classes than the ones set up in the
497
+ // initial exception translator, below, so add another for our local exception classes.
498
+ //
499
+ // libstdc++ doesn't require this (types there are identified only by name)
500
+ // libc++ with CPython doesn't require this (types are explicitly exported)
501
+ // libc++ with PyPy still need it, awaiting further investigation
502
+ #if !defined(__GLIBCXX__)
503
+ (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
504
+ #endif
505
+ } else {
506
+ if (!internals_pp) {
507
+ internals_pp = new internals *();
508
+ }
509
+ auto *&internals_ptr = *internals_pp;
510
+ internals_ptr = new internals();
511
+ #if defined(WITH_THREAD)
512
+
513
+ PyThreadState *tstate = PyThreadState_Get();
514
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
515
+ if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
516
+ pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
517
+ }
518
+ PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
519
+
520
+ # if PYBIND11_INTERNALS_VERSION > 4
521
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
522
+ if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
523
+ pybind11_fail("get_internals: could not successfully initialize the "
524
+ "loader_life_support TSS key!");
525
+ }
526
+ # endif
527
+ internals_ptr->istate = tstate->interp;
528
+ #endif
529
+ state_dict[PYBIND11_INTERNALS_ID] = capsule(internals_pp);
530
+ internals_ptr->registered_exception_translators.push_front(&translate_exception);
531
+ internals_ptr->static_property_type = make_static_property_type();
532
+ internals_ptr->default_metaclass = make_default_metaclass();
533
+ internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
534
+ }
535
+ return **internals_pp;
536
+ }
537
+
538
+ // the internals struct (above) is shared between all the modules. local_internals are only
539
+ // for a single module. Any changes made to internals may require an update to
540
+ // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
541
+ // restricted to a single module. Whether a module has local internals or not should not
542
+ // impact any other modules, because the only things accessing the local internals is the
543
+ // module that contains them.
544
+ struct local_internals {
545
+ type_map<type_info *> registered_types_cpp;
546
+ std::forward_list<ExceptionTranslator> registered_exception_translators;
547
+ #if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
548
+
549
+ // For ABI compatibility, we can't store the loader_life_support TLS key in
550
+ // the `internals` struct directly. Instead, we store it in `shared_data` and
551
+ // cache a copy in `local_internals`. If we allocated a separate TLS key for
552
+ // each instance of `local_internals`, we could end up allocating hundreds of
553
+ // TLS keys if hundreds of different pybind11 modules are loaded (which is a
554
+ // plausible number).
555
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
556
+
557
+ // Holds the shared TLS key for the loader_life_support stack.
558
+ struct shared_loader_life_support_data {
559
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
560
+ shared_loader_life_support_data() {
561
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
562
+ if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
563
+ pybind11_fail("local_internals: could not successfully initialize the "
564
+ "loader_life_support TLS key!");
565
+ }
566
+ }
567
+ // We can't help but leak the TLS key, because Python never unloads extension modules.
568
+ };
569
+
570
+ local_internals() {
571
+ auto &internals = get_internals();
572
+ // Get or create the `loader_life_support_stack_key`.
573
+ auto &ptr = internals.shared_data["_life_support"];
574
+ if (!ptr) {
575
+ ptr = new shared_loader_life_support_data;
576
+ }
577
+ loader_life_support_tls_key
578
+ = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
579
+ }
580
+ #endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
581
+ };
582
+
583
+ /// Works like `get_internals`, but for things which are locally registered.
584
+ inline local_internals &get_local_internals() {
585
+ // Current static can be created in the interpreter finalization routine. If the later will be
586
+ // destroyed in another static variable destructor, creation of this static there will cause
587
+ // static deinitialization fiasco. In order to avoid it we avoid destruction of the
588
+ // local_internals static. One can read more about the problem and current solution here:
589
+ // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
590
+ static auto *locals = new local_internals();
591
+ return *locals;
592
+ }
593
+
594
+ /// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
595
+ /// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only
596
+ /// cleared when the program exits or after interpreter shutdown (when embedding), and so are
597
+ /// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
598
+ template <typename... Args>
599
+ const char *c_str(Args &&...args) {
600
+ auto &strings = get_internals().static_strings;
601
+ strings.emplace_front(std::forward<Args>(args)...);
602
+ return strings.front().c_str();
603
+ }
604
+
605
+ inline const char *get_function_record_capsule_name() {
606
+ #if PYBIND11_INTERNALS_VERSION > 4
607
+ return get_internals().function_record_capsule_name.c_str();
608
+ #else
609
+ return nullptr;
610
+ #endif
611
+ }
612
+
613
+ // Determine whether or not the following capsule contains a pybind11 function record.
614
+ // Note that we use `internals` to make sure that only ABI compatible records are touched.
615
+ //
616
+ // This check is currently used in two places:
617
+ // - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
618
+ // - The sibling feature of cpp_function to allow overloads
619
+ inline bool is_function_record_capsule(const capsule &cap) {
620
+ // Pointer equality as we rely on internals() to ensure unique pointers
621
+ return cap.name() == get_function_record_capsule_name();
622
+ }
623
+
624
+ PYBIND11_NAMESPACE_END(detail)
625
+
626
+ /// Returns a named pointer that is shared among all extension modules (using the same
627
+ /// pybind11 version) running in the current interpreter. Names starting with underscores
628
+ /// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
629
+ PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
630
+ auto &internals = detail::get_internals();
631
+ auto it = internals.shared_data.find(name);
632
+ return it != internals.shared_data.end() ? it->second : nullptr;
633
+ }
634
+
635
+ /// Set the shared data that can be later recovered by `get_shared_data()`.
636
+ PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
637
+ detail::get_internals().shared_data[name] = data;
638
+ return data;
639
+ }
640
+
641
+ /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
642
+ /// such entry exists. Otherwise, a new object of default-constructible type `T` is
643
+ /// added to the shared data under the given name and a reference to it is returned.
644
+ template <typename T>
645
+ T &get_or_create_shared_data(const std::string &name) {
646
+ auto &internals = detail::get_internals();
647
+ auto it = internals.shared_data.find(name);
648
+ T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
649
+ if (!ptr) {
650
+ ptr = new T();
651
+ internals.shared_data[name] = ptr;
652
+ }
653
+ return *ptr;
654
+ }
655
+
656
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/type_caster_base.h ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/type_caster_base.h (originally first part of pybind11/cast.h)
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../pytypes.h"
13
+ #include "common.h"
14
+ #include "descr.h"
15
+ #include "internals.h"
16
+ #include "typeid.h"
17
+
18
+ #include <cstdint>
19
+ #include <iterator>
20
+ #include <new>
21
+ #include <string>
22
+ #include <type_traits>
23
+ #include <typeindex>
24
+ #include <typeinfo>
25
+ #include <unordered_map>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
30
+ PYBIND11_NAMESPACE_BEGIN(detail)
31
+
32
+ /// A life support system for temporary objects created by `type_caster::load()`.
33
+ /// Adding a patient will keep it alive up until the enclosing function returns.
34
+ class loader_life_support {
35
+ private:
36
+ loader_life_support *parent = nullptr;
37
+ std::unordered_set<PyObject *> keep_alive;
38
+
39
+ #if defined(WITH_THREAD)
40
+ // Store stack pointer in thread-local storage.
41
+ static PYBIND11_TLS_KEY_REF get_stack_tls_key() {
42
+ # if PYBIND11_INTERNALS_VERSION == 4
43
+ return get_local_internals().loader_life_support_tls_key;
44
+ # else
45
+ return get_internals().loader_life_support_tls_key;
46
+ # endif
47
+ }
48
+ static loader_life_support *get_stack_top() {
49
+ return static_cast<loader_life_support *>(PYBIND11_TLS_GET_VALUE(get_stack_tls_key()));
50
+ }
51
+ static void set_stack_top(loader_life_support *value) {
52
+ PYBIND11_TLS_REPLACE_VALUE(get_stack_tls_key(), value);
53
+ }
54
+ #else
55
+ // Use single global variable for stack.
56
+ static loader_life_support **get_stack_pp() {
57
+ static loader_life_support *global_stack = nullptr;
58
+ return global_stack;
59
+ }
60
+ static loader_life_support *get_stack_top() { return *get_stack_pp(); }
61
+ static void set_stack_top(loader_life_support *value) { *get_stack_pp() = value; }
62
+ #endif
63
+
64
+ public:
65
+ /// A new patient frame is created when a function is entered
66
+ loader_life_support() : parent{get_stack_top()} { set_stack_top(this); }
67
+
68
+ /// ... and destroyed after it returns
69
+ ~loader_life_support() {
70
+ if (get_stack_top() != this) {
71
+ pybind11_fail("loader_life_support: internal error");
72
+ }
73
+ set_stack_top(parent);
74
+ for (auto *item : keep_alive) {
75
+ Py_DECREF(item);
76
+ }
77
+ }
78
+
79
+ /// This can only be used inside a pybind11-bound function, either by `argument_loader`
80
+ /// at argument preparation time or by `py::cast()` at execution time.
81
+ PYBIND11_NOINLINE static void add_patient(handle h) {
82
+ loader_life_support *frame = get_stack_top();
83
+ if (!frame) {
84
+ // NOTE: It would be nice to include the stack frames here, as this indicates
85
+ // use of pybind11::cast<> outside the normal call framework, finding such
86
+ // a location is challenging. Developers could consider printing out
87
+ // stack frame addresses here using something like __builtin_frame_address(0)
88
+ throw cast_error("When called outside a bound function, py::cast() cannot "
89
+ "do Python -> C++ conversions which require the creation "
90
+ "of temporary values");
91
+ }
92
+
93
+ if (frame->keep_alive.insert(h.ptr()).second) {
94
+ Py_INCREF(h.ptr());
95
+ }
96
+ }
97
+ };
98
+
99
+ // Gets the cache entry for the given type, creating it if necessary. The return value is the pair
100
+ // returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
101
+ // just created.
102
+ inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
103
+ all_type_info_get_cache(PyTypeObject *type);
104
+
105
+ // Populates a just-created cache entry.
106
+ PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
107
+ std::vector<PyTypeObject *> check;
108
+ for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
109
+ check.push_back((PyTypeObject *) parent.ptr());
110
+ }
111
+
112
+ auto const &type_dict = get_internals().registered_types_py;
113
+ for (size_t i = 0; i < check.size(); i++) {
114
+ auto *type = check[i];
115
+ // Ignore Python2 old-style class super type:
116
+ if (!PyType_Check((PyObject *) type)) {
117
+ continue;
118
+ }
119
+
120
+ // Check `type` in the current set of registered python types:
121
+ auto it = type_dict.find(type);
122
+ if (it != type_dict.end()) {
123
+ // We found a cache entry for it, so it's either pybind-registered or has pre-computed
124
+ // pybind bases, but we have to make sure we haven't already seen the type(s) before:
125
+ // we want to follow Python/virtual C++ rules that there should only be one instance of
126
+ // a common base.
127
+ for (auto *tinfo : it->second) {
128
+ // NB: Could use a second set here, rather than doing a linear search, but since
129
+ // having a large number of immediate pybind11-registered types seems fairly
130
+ // unlikely, that probably isn't worthwhile.
131
+ bool found = false;
132
+ for (auto *known : bases) {
133
+ if (known == tinfo) {
134
+ found = true;
135
+ break;
136
+ }
137
+ }
138
+ if (!found) {
139
+ bases.push_back(tinfo);
140
+ }
141
+ }
142
+ } else if (type->tp_bases) {
143
+ // It's some python type, so keep follow its bases classes to look for one or more
144
+ // registered types
145
+ if (i + 1 == check.size()) {
146
+ // When we're at the end, we can pop off the current element to avoid growing
147
+ // `check` when adding just one base (which is typical--i.e. when there is no
148
+ // multiple inheritance)
149
+ check.pop_back();
150
+ i--;
151
+ }
152
+ for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
153
+ check.push_back((PyTypeObject *) parent.ptr());
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
161
+ * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
162
+ * derived class that uses single inheritance. Will contain as many types as required for a Python
163
+ * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
164
+ * pybind-registered classes. Will be empty if neither the type nor any base classes are
165
+ * pybind-registered.
166
+ *
167
+ * The value is cached for the lifetime of the Python type.
168
+ */
169
+ inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
170
+ auto ins = all_type_info_get_cache(type);
171
+ if (ins.second) {
172
+ // New cache entry: populate it
173
+ all_type_info_populate(type, ins.first->second);
174
+ }
175
+
176
+ return ins.first->second;
177
+ }
178
+
179
+ /**
180
+ * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
181
+ * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
182
+ * `all_type_info` instead if you want to support multiple bases.
183
+ */
184
+ PYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {
185
+ const auto &bases = all_type_info(type);
186
+ if (bases.empty()) {
187
+ return nullptr;
188
+ }
189
+ if (bases.size() > 1) {
190
+ pybind11_fail(
191
+ "pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
192
+ }
193
+ return bases.front();
194
+ }
195
+
196
+ inline detail::type_info *get_local_type_info(const std::type_index &tp) {
197
+ auto &locals = get_local_internals().registered_types_cpp;
198
+ auto it = locals.find(tp);
199
+ if (it != locals.end()) {
200
+ return it->second;
201
+ }
202
+ return nullptr;
203
+ }
204
+
205
+ inline detail::type_info *get_global_type_info(const std::type_index &tp) {
206
+ auto &types = get_internals().registered_types_cpp;
207
+ auto it = types.find(tp);
208
+ if (it != types.end()) {
209
+ return it->second;
210
+ }
211
+ return nullptr;
212
+ }
213
+
214
+ /// Return the type info for a given C++ type; on lookup failure can either throw or return
215
+ /// nullptr.
216
+ PYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_index &tp,
217
+ bool throw_if_missing = false) {
218
+ if (auto *ltype = get_local_type_info(tp)) {
219
+ return ltype;
220
+ }
221
+ if (auto *gtype = get_global_type_info(tp)) {
222
+ return gtype;
223
+ }
224
+
225
+ if (throw_if_missing) {
226
+ std::string tname = tp.name();
227
+ detail::clean_type_id(tname);
228
+ pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \""
229
+ + std::move(tname) + '"');
230
+ }
231
+ return nullptr;
232
+ }
233
+
234
+ PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
235
+ detail::type_info *type_info = get_type_info(tp, throw_if_missing);
236
+ return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
237
+ }
238
+
239
+ // Searches the inheritance graph for a registered Python instance, using all_type_info().
240
+ PYBIND11_NOINLINE handle find_registered_python_instance(void *src,
241
+ const detail::type_info *tinfo) {
242
+ auto it_instances = get_internals().registered_instances.equal_range(src);
243
+ for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
244
+ for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
245
+ if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {
246
+ return handle((PyObject *) it_i->second).inc_ref();
247
+ }
248
+ }
249
+ }
250
+ return handle();
251
+ }
252
+
253
+ struct value_and_holder {
254
+ instance *inst = nullptr;
255
+ size_t index = 0u;
256
+ const detail::type_info *type = nullptr;
257
+ void **vh = nullptr;
258
+
259
+ // Main constructor for a found value/holder:
260
+ value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
261
+ : inst{i}, index{index}, type{type},
262
+ vh{inst->simple_layout ? inst->simple_value_holder
263
+ : &inst->nonsimple.values_and_holders[vpos]} {}
264
+
265
+ // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
266
+ value_and_holder() = default;
267
+
268
+ // Used for past-the-end iterator
269
+ explicit value_and_holder(size_t index) : index{index} {}
270
+
271
+ template <typename V = void>
272
+ V *&value_ptr() const {
273
+ return reinterpret_cast<V *&>(vh[0]);
274
+ }
275
+ // True if this `value_and_holder` has a non-null value pointer
276
+ explicit operator bool() const { return value_ptr() != nullptr; }
277
+
278
+ template <typename H>
279
+ H &holder() const {
280
+ return reinterpret_cast<H &>(vh[1]);
281
+ }
282
+ bool holder_constructed() const {
283
+ return inst->simple_layout
284
+ ? inst->simple_holder_constructed
285
+ : (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;
286
+ }
287
+ // NOLINTNEXTLINE(readability-make-member-function-const)
288
+ void set_holder_constructed(bool v = true) {
289
+ if (inst->simple_layout) {
290
+ inst->simple_holder_constructed = v;
291
+ } else if (v) {
292
+ inst->nonsimple.status[index] |= instance::status_holder_constructed;
293
+ } else {
294
+ inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
295
+ }
296
+ }
297
+ bool instance_registered() const {
298
+ return inst->simple_layout
299
+ ? inst->simple_instance_registered
300
+ : ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);
301
+ }
302
+ // NOLINTNEXTLINE(readability-make-member-function-const)
303
+ void set_instance_registered(bool v = true) {
304
+ if (inst->simple_layout) {
305
+ inst->simple_instance_registered = v;
306
+ } else if (v) {
307
+ inst->nonsimple.status[index] |= instance::status_instance_registered;
308
+ } else {
309
+ inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
310
+ }
311
+ }
312
+ };
313
+
314
+ // Container for accessing and iterating over an instance's values/holders
315
+ struct values_and_holders {
316
+ private:
317
+ instance *inst;
318
+ using type_vec = std::vector<detail::type_info *>;
319
+ const type_vec &tinfo;
320
+
321
+ public:
322
+ explicit values_and_holders(instance *inst)
323
+ : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
324
+
325
+ struct iterator {
326
+ private:
327
+ instance *inst = nullptr;
328
+ const type_vec *types = nullptr;
329
+ value_and_holder curr;
330
+ friend struct values_and_holders;
331
+ iterator(instance *inst, const type_vec *tinfo)
332
+ : inst{inst}, types{tinfo},
333
+ curr(inst /* instance */,
334
+ types->empty() ? nullptr : (*types)[0] /* type info */,
335
+ 0, /* vpos: (non-simple types only): the first vptr comes first */
336
+ 0 /* index */) {}
337
+ // Past-the-end iterator:
338
+ explicit iterator(size_t end) : curr(end) {}
339
+
340
+ public:
341
+ bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
342
+ bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
343
+ iterator &operator++() {
344
+ if (!inst->simple_layout) {
345
+ curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
346
+ }
347
+ ++curr.index;
348
+ curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
349
+ return *this;
350
+ }
351
+ value_and_holder &operator*() { return curr; }
352
+ value_and_holder *operator->() { return &curr; }
353
+ };
354
+
355
+ iterator begin() { return iterator(inst, &tinfo); }
356
+ iterator end() { return iterator(tinfo.size()); }
357
+
358
+ iterator find(const type_info *find_type) {
359
+ auto it = begin(), endit = end();
360
+ while (it != endit && it->type != find_type) {
361
+ ++it;
362
+ }
363
+ return it;
364
+ }
365
+
366
+ size_t size() { return tinfo.size(); }
367
+ };
368
+
369
+ /**
370
+ * Extracts C++ value and holder pointer references from an instance (which may contain multiple
371
+ * values/holders for python-side multiple inheritance) that match the given type. Throws an error
372
+ * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
373
+ * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
374
+ * regardless of type (and the resulting .type will be nullptr).
375
+ *
376
+ * The returned object should be short-lived: in particular, it must not outlive the called-upon
377
+ * instance.
378
+ */
379
+ PYBIND11_NOINLINE value_and_holder
380
+ instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,
381
+ bool throw_if_missing /*= true in common.h*/) {
382
+ // Optimize common case:
383
+ if (!find_type || Py_TYPE(this) == find_type->type) {
384
+ return value_and_holder(this, find_type, 0, 0);
385
+ }
386
+
387
+ detail::values_and_holders vhs(this);
388
+ auto it = vhs.find(find_type);
389
+ if (it != vhs.end()) {
390
+ return *it;
391
+ }
392
+
393
+ if (!throw_if_missing) {
394
+ return value_and_holder();
395
+ }
396
+
397
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
398
+ pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
399
+ + get_fully_qualified_tp_name(find_type->type)
400
+ + "' is not a pybind11 base of the given `"
401
+ + get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
402
+ #else
403
+ pybind11_fail(
404
+ "pybind11::detail::instance::get_value_and_holder: "
405
+ "type is not a pybind11 base of the given instance "
406
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for type details)");
407
+ #endif
408
+ }
409
+
410
+ PYBIND11_NOINLINE void instance::allocate_layout() {
411
+ const auto &tinfo = all_type_info(Py_TYPE(this));
412
+
413
+ const size_t n_types = tinfo.size();
414
+
415
+ if (n_types == 0) {
416
+ pybind11_fail(
417
+ "instance allocation failed: new instance has no pybind11-registered base types");
418
+ }
419
+
420
+ simple_layout
421
+ = n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
422
+
423
+ // Simple path: no python-side multiple inheritance, and a small-enough holder
424
+ if (simple_layout) {
425
+ simple_value_holder[0] = nullptr;
426
+ simple_holder_constructed = false;
427
+ simple_instance_registered = false;
428
+ } else { // multiple base types or a too-large holder
429
+ // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
430
+ // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
431
+ // values that tracks whether each associated holder has been initialized. Each [block] is
432
+ // padded, if necessary, to an integer multiple of sizeof(void *).
433
+ size_t space = 0;
434
+ for (auto *t : tinfo) {
435
+ space += 1; // value pointer
436
+ space += t->holder_size_in_ptrs; // holder instance
437
+ }
438
+ size_t flags_at = space;
439
+ space += size_in_ptrs(n_types); // status bytes (holder_constructed and
440
+ // instance_registered)
441
+
442
+ // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
443
+ // in particular, need to be 0). Use Python's memory allocation
444
+ // functions: Python is using pymalloc, which is designed to be
445
+ // efficient for small allocations like the one we're doing here;
446
+ // for larger allocations they are just wrappers around malloc.
447
+ // TODO: is this still true for pure Python 3.6?
448
+ nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
449
+ if (!nonsimple.values_and_holders) {
450
+ throw std::bad_alloc();
451
+ }
452
+ nonsimple.status
453
+ = reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
454
+ }
455
+ owned = true;
456
+ }
457
+
458
+ // NOLINTNEXTLINE(readability-make-member-function-const)
459
+ PYBIND11_NOINLINE void instance::deallocate_layout() {
460
+ if (!simple_layout) {
461
+ PyMem_Free(nonsimple.values_and_holders);
462
+ }
463
+ }
464
+
465
+ PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
466
+ handle type = detail::get_type_handle(tp, false);
467
+ if (!type) {
468
+ return false;
469
+ }
470
+ return isinstance(obj, type);
471
+ }
472
+
473
+ PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
474
+ auto &instances = get_internals().registered_instances;
475
+ auto range = instances.equal_range(ptr);
476
+ for (auto it = range.first; it != range.second; ++it) {
477
+ for (const auto &vh : values_and_holders(it->second)) {
478
+ if (vh.type == type) {
479
+ return handle((PyObject *) it->second);
480
+ }
481
+ }
482
+ }
483
+ return handle();
484
+ }
485
+
486
+ inline PyThreadState *get_thread_state_unchecked() {
487
+ #if defined(PYPY_VERSION)
488
+ return PyThreadState_GET();
489
+ #else
490
+ return _PyThreadState_UncheckedGet();
491
+ #endif
492
+ }
493
+
494
+ // Forward declarations
495
+ void keep_alive_impl(handle nurse, handle patient);
496
+ inline PyObject *make_new_instance(PyTypeObject *type);
497
+
498
+ class type_caster_generic {
499
+ public:
500
+ PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
501
+ : typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
502
+
503
+ explicit type_caster_generic(const type_info *typeinfo)
504
+ : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
505
+
506
+ bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
507
+
508
+ PYBIND11_NOINLINE static handle cast(const void *_src,
509
+ return_value_policy policy,
510
+ handle parent,
511
+ const detail::type_info *tinfo,
512
+ void *(*copy_constructor)(const void *),
513
+ void *(*move_constructor)(const void *),
514
+ const void *existing_holder = nullptr) {
515
+ if (!tinfo) { // no type info: error will be set already
516
+ return handle();
517
+ }
518
+
519
+ void *src = const_cast<void *>(_src);
520
+ if (src == nullptr) {
521
+ return none().release();
522
+ }
523
+
524
+ if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
525
+ return registered_inst;
526
+ }
527
+
528
+ auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
529
+ auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
530
+ wrapper->owned = false;
531
+ void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
532
+
533
+ switch (policy) {
534
+ case return_value_policy::automatic:
535
+ case return_value_policy::take_ownership:
536
+ valueptr = src;
537
+ wrapper->owned = true;
538
+ break;
539
+
540
+ case return_value_policy::automatic_reference:
541
+ case return_value_policy::reference:
542
+ valueptr = src;
543
+ wrapper->owned = false;
544
+ break;
545
+
546
+ case return_value_policy::copy:
547
+ if (copy_constructor) {
548
+ valueptr = copy_constructor(src);
549
+ } else {
550
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
551
+ std::string type_name(tinfo->cpptype->name());
552
+ detail::clean_type_id(type_name);
553
+ throw cast_error("return_value_policy = copy, but type " + type_name
554
+ + " is non-copyable!");
555
+ #else
556
+ throw cast_error("return_value_policy = copy, but type is "
557
+ "non-copyable! (#define PYBIND11_DETAILED_ERROR_MESSAGES or "
558
+ "compile in debug mode for details)");
559
+ #endif
560
+ }
561
+ wrapper->owned = true;
562
+ break;
563
+
564
+ case return_value_policy::move:
565
+ if (move_constructor) {
566
+ valueptr = move_constructor(src);
567
+ } else if (copy_constructor) {
568
+ valueptr = copy_constructor(src);
569
+ } else {
570
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
571
+ std::string type_name(tinfo->cpptype->name());
572
+ detail::clean_type_id(type_name);
573
+ throw cast_error("return_value_policy = move, but type " + type_name
574
+ + " is neither movable nor copyable!");
575
+ #else
576
+ throw cast_error("return_value_policy = move, but type is neither "
577
+ "movable nor copyable! "
578
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in "
579
+ "debug mode for details)");
580
+ #endif
581
+ }
582
+ wrapper->owned = true;
583
+ break;
584
+
585
+ case return_value_policy::reference_internal:
586
+ valueptr = src;
587
+ wrapper->owned = false;
588
+ keep_alive_impl(inst, parent);
589
+ break;
590
+
591
+ default:
592
+ throw cast_error("unhandled return_value_policy: should not happen!");
593
+ }
594
+
595
+ tinfo->init_instance(wrapper, existing_holder);
596
+
597
+ return inst.release();
598
+ }
599
+
600
+ // Base methods for generic caster; there are overridden in copyable_holder_caster
601
+ void load_value(value_and_holder &&v_h) {
602
+ auto *&vptr = v_h.value_ptr();
603
+ // Lazy allocation for unallocated values:
604
+ if (vptr == nullptr) {
605
+ const auto *type = v_h.type ? v_h.type : typeinfo;
606
+ if (type->operator_new) {
607
+ vptr = type->operator_new(type->type_size);
608
+ } else {
609
+ #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
610
+ if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
611
+ vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
612
+ } else {
613
+ vptr = ::operator new(type->type_size);
614
+ }
615
+ #else
616
+ vptr = ::operator new(type->type_size);
617
+ #endif
618
+ }
619
+ }
620
+ value = vptr;
621
+ }
622
+ bool try_implicit_casts(handle src, bool convert) {
623
+ for (const auto &cast : typeinfo->implicit_casts) {
624
+ type_caster_generic sub_caster(*cast.first);
625
+ if (sub_caster.load(src, convert)) {
626
+ value = cast.second(sub_caster.value);
627
+ return true;
628
+ }
629
+ }
630
+ return false;
631
+ }
632
+ bool try_direct_conversions(handle src) {
633
+ for (auto &converter : *typeinfo->direct_conversions) {
634
+ if (converter(src.ptr(), value)) {
635
+ return true;
636
+ }
637
+ }
638
+ return false;
639
+ }
640
+ void check_holder_compat() {}
641
+
642
+ PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
643
+ auto caster = type_caster_generic(ti);
644
+ if (caster.load(src, false)) {
645
+ return caster.value;
646
+ }
647
+ return nullptr;
648
+ }
649
+
650
+ /// Try to load with foreign typeinfo, if available. Used when there is no
651
+ /// native typeinfo, or when the native one wasn't able to produce a value.
652
+ PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
653
+ constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
654
+ const auto pytype = type::handle_of(src);
655
+ if (!hasattr(pytype, local_key)) {
656
+ return false;
657
+ }
658
+
659
+ type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
660
+ // Only consider this foreign loader if actually foreign and is a loader of the correct cpp
661
+ // type
662
+ if (foreign_typeinfo->module_local_load == &local_load
663
+ || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
664
+ return false;
665
+ }
666
+
667
+ if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
668
+ value = result;
669
+ return true;
670
+ }
671
+ return false;
672
+ }
673
+
674
+ // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
675
+ // bits of code between here and copyable_holder_caster where the two classes need different
676
+ // logic (without having to resort to virtual inheritance).
677
+ template <typename ThisT>
678
+ PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
679
+ if (!src) {
680
+ return false;
681
+ }
682
+ if (!typeinfo) {
683
+ return try_load_foreign_module_local(src);
684
+ }
685
+
686
+ auto &this_ = static_cast<ThisT &>(*this);
687
+ this_.check_holder_compat();
688
+
689
+ PyTypeObject *srctype = Py_TYPE(src.ptr());
690
+
691
+ // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
692
+ // the instance's value pointer to the target type:
693
+ if (srctype == typeinfo->type) {
694
+ this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
695
+ return true;
696
+ }
697
+ // Case 2: We have a derived class
698
+ if (PyType_IsSubtype(srctype, typeinfo->type)) {
699
+ const auto &bases = all_type_info(srctype);
700
+ bool no_cpp_mi = typeinfo->simple_type;
701
+
702
+ // Case 2a: the python type is a Python-inherited derived class that inherits from just
703
+ // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
704
+ // the right type and we can use reinterpret_cast.
705
+ // (This is essentially the same as case 2b, but because not using multiple inheritance
706
+ // is extremely common, we handle it specially to avoid the loop iterator and type
707
+ // pointer lookup overhead)
708
+ if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
709
+ this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
710
+ return true;
711
+ }
712
+ // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
713
+ // if we can find an exact match (or, for a simple C++ type, an inherited match); if
714
+ // so, we can safely reinterpret_cast to the relevant pointer.
715
+ if (bases.size() > 1) {
716
+ for (auto *base : bases) {
717
+ if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
718
+ : base->type == typeinfo->type) {
719
+ this_.load_value(
720
+ reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
721
+ return true;
722
+ }
723
+ }
724
+ }
725
+
726
+ // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
727
+ // match in the registered bases, above, so try implicit casting (needed for proper C++
728
+ // casting when MI is involved).
729
+ if (this_.try_implicit_casts(src, convert)) {
730
+ return true;
731
+ }
732
+ }
733
+
734
+ // Perform an implicit conversion
735
+ if (convert) {
736
+ for (const auto &converter : typeinfo->implicit_conversions) {
737
+ auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
738
+ if (load_impl<ThisT>(temp, false)) {
739
+ loader_life_support::add_patient(temp);
740
+ return true;
741
+ }
742
+ }
743
+ if (this_.try_direct_conversions(src)) {
744
+ return true;
745
+ }
746
+ }
747
+
748
+ // Failed to match local typeinfo. Try again with global.
749
+ if (typeinfo->module_local) {
750
+ if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
751
+ typeinfo = gtype;
752
+ return load(src, false);
753
+ }
754
+ }
755
+
756
+ // Global typeinfo has precedence over foreign module_local
757
+ if (try_load_foreign_module_local(src)) {
758
+ return true;
759
+ }
760
+
761
+ // Custom converters didn't take None, now we convert None to nullptr.
762
+ if (src.is_none()) {
763
+ // Defer accepting None to other overloads (if we aren't in convert mode):
764
+ if (!convert) {
765
+ return false;
766
+ }
767
+ value = nullptr;
768
+ return true;
769
+ }
770
+
771
+ return false;
772
+ }
773
+
774
+ // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
775
+ // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
776
+ // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
777
+ PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
778
+ src_and_type(const void *src,
779
+ const std::type_info &cast_type,
780
+ const std::type_info *rtti_type = nullptr) {
781
+ if (auto *tpi = get_type_info(cast_type)) {
782
+ return {src, const_cast<const type_info *>(tpi)};
783
+ }
784
+
785
+ // Not found, set error:
786
+ std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
787
+ detail::clean_type_id(tname);
788
+ std::string msg = "Unregistered type : " + tname;
789
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
790
+ return {nullptr, nullptr};
791
+ }
792
+
793
+ const type_info *typeinfo = nullptr;
794
+ const std::type_info *cpptype = nullptr;
795
+ void *value = nullptr;
796
+ };
797
+
798
+ /**
799
+ * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
800
+ * needs to provide `operator T*()` and `operator T&()` operators.
801
+ *
802
+ * If the type supports moving the value away via an `operator T&&() &&` method, it should use
803
+ * `movable_cast_op_type` instead.
804
+ */
805
+ template <typename T>
806
+ using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
807
+ typename std::add_pointer<intrinsic_t<T>>::type,
808
+ typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
809
+
810
+ /**
811
+ * Determine suitable casting operator for a type caster with a movable value. Such a type caster
812
+ * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
813
+ * called in appropriate contexts where the value can be moved rather than copied.
814
+ *
815
+ * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
816
+ */
817
+ template <typename T>
818
+ using movable_cast_op_type
819
+ = conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
820
+ typename std::add_pointer<intrinsic_t<T>>::type,
821
+ conditional_t<std::is_rvalue_reference<T>::value,
822
+ typename std::add_rvalue_reference<intrinsic_t<T>>::type,
823
+ typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
824
+
825
+ // Does the container have a mapped type and is it recursive?
826
+ // Implemented by specializations below.
827
+ template <typename Container, typename SFINAE = void>
828
+ struct container_mapped_type_traits {
829
+ static constexpr bool has_mapped_type = false;
830
+ static constexpr bool has_recursive_mapped_type = false;
831
+ };
832
+
833
+ template <typename Container>
834
+ struct container_mapped_type_traits<
835
+ Container,
836
+ typename std::enable_if<
837
+ std::is_same<typename Container::mapped_type, Container>::value>::type> {
838
+ static constexpr bool has_mapped_type = true;
839
+ static constexpr bool has_recursive_mapped_type = true;
840
+ };
841
+
842
+ template <typename Container>
843
+ struct container_mapped_type_traits<
844
+ Container,
845
+ typename std::enable_if<
846
+ negation<std::is_same<typename Container::mapped_type, Container>>::value>::type> {
847
+ static constexpr bool has_mapped_type = true;
848
+ static constexpr bool has_recursive_mapped_type = false;
849
+ };
850
+
851
+ // Does the container have a value type and is it recursive?
852
+ // Implemented by specializations below.
853
+ template <typename Container, typename SFINAE = void>
854
+ struct container_value_type_traits : std::false_type {
855
+ static constexpr bool has_value_type = false;
856
+ static constexpr bool has_recursive_value_type = false;
857
+ };
858
+
859
+ template <typename Container>
860
+ struct container_value_type_traits<
861
+ Container,
862
+ typename std::enable_if<
863
+ std::is_same<typename Container::value_type, Container>::value>::type> {
864
+ static constexpr bool has_value_type = true;
865
+ static constexpr bool has_recursive_value_type = true;
866
+ };
867
+
868
+ template <typename Container>
869
+ struct container_value_type_traits<
870
+ Container,
871
+ typename std::enable_if<
872
+ negation<std::is_same<typename Container::value_type, Container>>::value>::type> {
873
+ static constexpr bool has_value_type = true;
874
+ static constexpr bool has_recursive_value_type = false;
875
+ };
876
+
877
+ /*
878
+ * Tag to be used for representing the bottom of recursively defined types.
879
+ * Define this tag so we don't have to use void.
880
+ */
881
+ struct recursive_bottom {};
882
+
883
+ /*
884
+ * Implementation detail of `recursive_container_traits` below.
885
+ * `T` is the `value_type` of the container, which might need to be modified to
886
+ * avoid recursive types and const types.
887
+ */
888
+ template <typename T, bool is_this_a_map>
889
+ struct impl_type_to_check_recursively {
890
+ /*
891
+ * If the container is recursive, then no further recursion should be done.
892
+ */
893
+ using if_recursive = recursive_bottom;
894
+ /*
895
+ * Otherwise yield `T` unchanged.
896
+ */
897
+ using if_not_recursive = T;
898
+ };
899
+
900
+ /*
901
+ * For pairs - only as value type of a map -, the first type should remove the `const`.
902
+ * Also, if the map is recursive, then the recursive checking should consider
903
+ * the first type only.
904
+ */
905
+ template <typename A, typename B>
906
+ struct impl_type_to_check_recursively<std::pair<A, B>, /* is_this_a_map = */ true> {
907
+ using if_recursive = typename std::remove_const<A>::type;
908
+ using if_not_recursive = std::pair<typename std::remove_const<A>::type, B>;
909
+ };
910
+
911
+ /*
912
+ * Implementation of `recursive_container_traits` below.
913
+ */
914
+ template <typename Container, typename SFINAE = void>
915
+ struct impl_recursive_container_traits {
916
+ using type_to_check_recursively = recursive_bottom;
917
+ };
918
+
919
+ template <typename Container>
920
+ struct impl_recursive_container_traits<
921
+ Container,
922
+ typename std::enable_if<container_value_type_traits<Container>::has_value_type>::type> {
923
+ static constexpr bool is_recursive
924
+ = container_mapped_type_traits<Container>::has_recursive_mapped_type
925
+ || container_value_type_traits<Container>::has_recursive_value_type;
926
+ /*
927
+ * This member dictates which type Pybind11 should check recursively in traits
928
+ * such as `is_move_constructible`, `is_copy_constructible`, `is_move_assignable`, ...
929
+ * Direct access to `value_type` should be avoided:
930
+ * 1. `value_type` might recursively contain the type again
931
+ * 2. `value_type` of STL map types is `std::pair<A const, B>`, the `const`
932
+ * should be removed.
933
+ *
934
+ */
935
+ using type_to_check_recursively = typename std::conditional<
936
+ is_recursive,
937
+ typename impl_type_to_check_recursively<
938
+ typename Container::value_type,
939
+ container_mapped_type_traits<Container>::has_mapped_type>::if_recursive,
940
+ typename impl_type_to_check_recursively<
941
+ typename Container::value_type,
942
+ container_mapped_type_traits<Container>::has_mapped_type>::if_not_recursive>::type;
943
+ };
944
+
945
+ /*
946
+ * This trait defines the `type_to_check_recursively` which is needed to properly
947
+ * handle recursively defined traits such as `is_move_constructible` without going
948
+ * into an infinite recursion.
949
+ * Should be used instead of directly accessing the `value_type`.
950
+ * It cancels the recursion by returning the `recursive_bottom` tag.
951
+ *
952
+ * The default definition of `type_to_check_recursively` is as follows:
953
+ *
954
+ * 1. By default, it is `recursive_bottom`, so that the recursion is canceled.
955
+ * 2. If the type is non-recursive and defines a `value_type`, then the `value_type` is used.
956
+ * If the `value_type` is a pair and a `mapped_type` is defined,
957
+ * then the `const` is removed from the first type.
958
+ * 3. If the type is recursive and `value_type` is not a pair, then `recursive_bottom` is returned.
959
+ * 4. If the type is recursive and `value_type` is a pair and a `mapped_type` is defined,
960
+ * then `const` is removed from the first type and the first type is returned.
961
+ *
962
+ * This behavior can be extended by the user as seen in test_stl_binders.cpp.
963
+ *
964
+ * This struct is exactly the same as impl_recursive_container_traits.
965
+ * The duplication achieves that user-defined specializations don't compete
966
+ * with internal specializations, but take precedence.
967
+ */
968
+ template <typename Container, typename SFINAE = void>
969
+ struct recursive_container_traits : impl_recursive_container_traits<Container> {};
970
+
971
+ template <typename T>
972
+ struct is_move_constructible
973
+ : all_of<std::is_move_constructible<T>,
974
+ is_move_constructible<
975
+ typename recursive_container_traits<T>::type_to_check_recursively>> {};
976
+
977
+ template <>
978
+ struct is_move_constructible<recursive_bottom> : std::true_type {};
979
+
980
+ // Likewise for std::pair
981
+ // (after C++17 it is mandatory that the move constructor not exist when the two types aren't
982
+ // themselves move constructible, but this can not be relied upon when T1 or T2 are themselves
983
+ // containers).
984
+ template <typename T1, typename T2>
985
+ struct is_move_constructible<std::pair<T1, T2>>
986
+ : all_of<is_move_constructible<T1>, is_move_constructible<T2>> {};
987
+
988
+ // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
989
+ // T is non-copyable, but code containing such a copy constructor fails to actually compile.
990
+ template <typename T>
991
+ struct is_copy_constructible
992
+ : all_of<std::is_copy_constructible<T>,
993
+ is_copy_constructible<
994
+ typename recursive_container_traits<T>::type_to_check_recursively>> {};
995
+
996
+ template <>
997
+ struct is_copy_constructible<recursive_bottom> : std::true_type {};
998
+
999
+ // Likewise for std::pair
1000
+ // (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
1001
+ // themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
1002
+ // containers).
1003
+ template <typename T1, typename T2>
1004
+ struct is_copy_constructible<std::pair<T1, T2>>
1005
+ : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
1006
+
1007
+ // The same problems arise with std::is_copy_assignable, so we use the same workaround.
1008
+ template <typename T>
1009
+ struct is_copy_assignable
1010
+ : all_of<
1011
+ std::is_copy_assignable<T>,
1012
+ is_copy_assignable<typename recursive_container_traits<T>::type_to_check_recursively>> {
1013
+ };
1014
+
1015
+ template <>
1016
+ struct is_copy_assignable<recursive_bottom> : std::true_type {};
1017
+
1018
+ template <typename T1, typename T2>
1019
+ struct is_copy_assignable<std::pair<T1, T2>>
1020
+ : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
1021
+
1022
+ PYBIND11_NAMESPACE_END(detail)
1023
+
1024
+ // polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
1025
+ // to by `src` actually is an instance of some class derived from `itype`.
1026
+ // If so, it sets `tinfo` to point to the std::type_info representing that derived
1027
+ // type, and returns a pointer to the start of the most-derived object of that type
1028
+ // (in which `src` is a subobject; this will be the same address as `src` in most
1029
+ // single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
1030
+ // and leaves `tinfo` at its default value of nullptr.
1031
+ //
1032
+ // The default polymorphic_type_hook just returns src. A specialization for polymorphic
1033
+ // types determines the runtime type of the passed object and adjusts the this-pointer
1034
+ // appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
1035
+ // to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
1036
+ // registered with pybind11, and this Animal is in fact a Dog).
1037
+ //
1038
+ // You may specialize polymorphic_type_hook yourself for types that want to appear
1039
+ // polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
1040
+ // in performance-sensitive applications, used most notably in LLVM.)
1041
+ //
1042
+ // polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
1043
+ // std::enable_if. User provided specializations will always have higher priority than
1044
+ // the default implementation and specialization provided in polymorphic_type_hook_base.
1045
+ template <typename itype, typename SFINAE = void>
1046
+ struct polymorphic_type_hook_base {
1047
+ static const void *get(const itype *src, const std::type_info *&) { return src; }
1048
+ };
1049
+ template <typename itype>
1050
+ struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
1051
+ static const void *get(const itype *src, const std::type_info *&type) {
1052
+ type = src ? &typeid(*src) : nullptr;
1053
+ return dynamic_cast<const void *>(src);
1054
+ }
1055
+ };
1056
+ template <typename itype, typename SFINAE = void>
1057
+ struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
1058
+
1059
+ PYBIND11_NAMESPACE_BEGIN(detail)
1060
+
1061
+ /// Generic type caster for objects stored on the heap
1062
+ template <typename type>
1063
+ class type_caster_base : public type_caster_generic {
1064
+ using itype = intrinsic_t<type>;
1065
+
1066
+ public:
1067
+ static constexpr auto name = const_name<type>();
1068
+
1069
+ type_caster_base() : type_caster_base(typeid(type)) {}
1070
+ explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
1071
+
1072
+ static handle cast(const itype &src, return_value_policy policy, handle parent) {
1073
+ if (policy == return_value_policy::automatic
1074
+ || policy == return_value_policy::automatic_reference) {
1075
+ policy = return_value_policy::copy;
1076
+ }
1077
+ return cast(&src, policy, parent);
1078
+ }
1079
+
1080
+ static handle cast(itype &&src, return_value_policy, handle parent) {
1081
+ return cast(&src, return_value_policy::move, parent);
1082
+ }
1083
+
1084
+ // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
1085
+ // polymorphic type (using RTTI by default, but can be overridden by specializing
1086
+ // polymorphic_type_hook). If the instance isn't derived, returns the base version.
1087
+ static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
1088
+ const auto &cast_type = typeid(itype);
1089
+ const std::type_info *instance_type = nullptr;
1090
+ const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
1091
+ if (instance_type && !same_type(cast_type, *instance_type)) {
1092
+ // This is a base pointer to a derived type. If the derived type is registered
1093
+ // with pybind11, we want to make the full derived object available.
1094
+ // In the typical case where itype is polymorphic, we get the correct
1095
+ // derived pointer (which may be != base pointer) by a dynamic_cast to
1096
+ // most derived type. If itype is not polymorphic, we won't get here
1097
+ // except via a user-provided specialization of polymorphic_type_hook,
1098
+ // and the user has promised that no this-pointer adjustment is
1099
+ // required in that case, so it's OK to use static_cast.
1100
+ if (const auto *tpi = get_type_info(*instance_type)) {
1101
+ return {vsrc, tpi};
1102
+ }
1103
+ }
1104
+ // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
1105
+ // so don't do a cast
1106
+ return type_caster_generic::src_and_type(src, cast_type, instance_type);
1107
+ }
1108
+
1109
+ static handle cast(const itype *src, return_value_policy policy, handle parent) {
1110
+ auto st = src_and_type(src);
1111
+ return type_caster_generic::cast(st.first,
1112
+ policy,
1113
+ parent,
1114
+ st.second,
1115
+ make_copy_constructor(src),
1116
+ make_move_constructor(src));
1117
+ }
1118
+
1119
+ static handle cast_holder(const itype *src, const void *holder) {
1120
+ auto st = src_and_type(src);
1121
+ return type_caster_generic::cast(st.first,
1122
+ return_value_policy::take_ownership,
1123
+ {},
1124
+ st.second,
1125
+ nullptr,
1126
+ nullptr,
1127
+ holder);
1128
+ }
1129
+
1130
+ template <typename T>
1131
+ using cast_op_type = detail::cast_op_type<T>;
1132
+
1133
+ // NOLINTNEXTLINE(google-explicit-constructor)
1134
+ operator itype *() { return (type *) value; }
1135
+ // NOLINTNEXTLINE(google-explicit-constructor)
1136
+ operator itype &() {
1137
+ if (!value) {
1138
+ throw reference_cast_error();
1139
+ }
1140
+ return *((itype *) value);
1141
+ }
1142
+
1143
+ protected:
1144
+ using Constructor = void *(*) (const void *);
1145
+
1146
+ /* Only enabled when the types are {copy,move}-constructible *and* when the type
1147
+ does not have a private operator new implementation. A comma operator is used in the
1148
+ decltype argument to apply SFINAE to the public copy/move constructors.*/
1149
+ template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
1150
+ static auto make_copy_constructor(const T *)
1151
+ -> decltype(new T(std::declval<const T>()), Constructor{}) {
1152
+ return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
1153
+ }
1154
+
1155
+ template <typename T, typename = enable_if_t<is_move_constructible<T>::value>>
1156
+ static auto make_move_constructor(const T *)
1157
+ -> decltype(new T(std::declval<T &&>()), Constructor{}) {
1158
+ return [](const void *arg) -> void * {
1159
+ return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
1160
+ };
1161
+ }
1162
+
1163
+ static Constructor make_copy_constructor(...) { return nullptr; }
1164
+ static Constructor make_move_constructor(...) { return nullptr; }
1165
+ };
1166
+
1167
+ PYBIND11_NOINLINE std::string type_info_description(const std::type_info &ti) {
1168
+ if (auto *type_data = get_type_info(ti)) {
1169
+ handle th((PyObject *) type_data->type);
1170
+ return th.attr("__module__").cast<std::string>() + '.'
1171
+ + th.attr("__qualname__").cast<std::string>();
1172
+ }
1173
+ return clean_type_id(ti.name());
1174
+ }
1175
+
1176
+ PYBIND11_NAMESPACE_END(detail)
1177
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/detail/typeid.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/typeid.h: Compiler-independent access to type identifiers
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+
15
+ #if defined(__GNUG__)
16
+ # include <cxxabi.h>
17
+ #endif
18
+
19
+ #include "common.h"
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+
24
+ /// Erase all occurrences of a substring
25
+ inline void erase_all(std::string &string, const std::string &search) {
26
+ for (size_t pos = 0;;) {
27
+ pos = string.find(search, pos);
28
+ if (pos == std::string::npos) {
29
+ break;
30
+ }
31
+ string.erase(pos, search.length());
32
+ }
33
+ }
34
+
35
+ PYBIND11_NOINLINE void clean_type_id(std::string &name) {
36
+ #if defined(__GNUG__)
37
+ int status = 0;
38
+ std::unique_ptr<char, void (*)(void *)> res{
39
+ abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free};
40
+ if (status == 0) {
41
+ name = res.get();
42
+ }
43
+ #else
44
+ detail::erase_all(name, "class ");
45
+ detail::erase_all(name, "struct ");
46
+ detail::erase_all(name, "enum ");
47
+ #endif
48
+ detail::erase_all(name, "pybind11::");
49
+ }
50
+
51
+ inline std::string clean_type_id(const char *typeid_name) {
52
+ std::string name(typeid_name);
53
+ detail::clean_type_id(name);
54
+ return name;
55
+ }
56
+
57
+ PYBIND11_NAMESPACE_END(detail)
58
+
59
+ /// Return a string representation of a C++ type
60
+ template <typename T>
61
+ static std::string type_id() {
62
+ return detail::clean_type_id(typeid(T).name());
63
+ }
64
+
65
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "eigen/matrix.h"
videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen/common.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2023 The pybind Community.
2
+
3
+ #pragma once
4
+
5
+ // Common message for `static_assert()`s, which are useful to easily
6
+ // preempt much less obvious errors.
7
+ #define PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED \
8
+ "Pointer types (in particular `PyObject *`) are not supported as scalar types for Eigen " \
9
+ "types."
videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen/matrix.h ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eigen/matrix.h: Transparent conversion for dense and sparse Eigen matrices
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "../numpy.h"
13
+ #include "common.h"
14
+
15
+ /* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
16
+ See also:
17
+ https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
18
+ https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
19
+ */
20
+ PYBIND11_WARNING_PUSH
21
+ PYBIND11_WARNING_DISABLE_MSVC(5054) // https://github.com/pybind/pybind11/pull/3741
22
+ // C5054: operator '&': deprecated between enumerations of different types
23
+ #if defined(__MINGW32__)
24
+ PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
25
+ #endif
26
+
27
+ #include <Eigen/Core>
28
+ #include <Eigen/SparseCore>
29
+
30
+ PYBIND11_WARNING_POP
31
+
32
+ // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
33
+ // move constructors that break things. We could detect this an explicitly copy, but an extra copy
34
+ // of matrices seems highly undesirable.
35
+ static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
36
+ "Eigen matrix support in pybind11 requires Eigen >= 3.2.7");
37
+
38
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
39
+
40
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
41
+
42
+ // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
43
+ using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
44
+ template <typename MatrixType>
45
+ using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
46
+ template <typename MatrixType>
47
+ using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
48
+
49
+ PYBIND11_NAMESPACE_BEGIN(detail)
50
+
51
+ #if EIGEN_VERSION_AT_LEAST(3, 3, 0)
52
+ using EigenIndex = Eigen::Index;
53
+ template <typename Scalar, int Flags, typename StorageIndex>
54
+ using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
55
+ #else
56
+ using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
57
+ template <typename Scalar, int Flags, typename StorageIndex>
58
+ using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
59
+ #endif
60
+
61
+ // Matches Eigen::Map, Eigen::Ref, blocks, etc:
62
+ template <typename T>
63
+ using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
64
+ std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
65
+ template <typename T>
66
+ using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
67
+ template <typename T>
68
+ using is_eigen_dense_plain
69
+ = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
70
+ template <typename T>
71
+ using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
72
+ // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
73
+ // basically covers anything that can be assigned to a dense matrix but that don't have a typical
74
+ // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
75
+ // SelfAdjointView fall into this category.
76
+ template <typename T>
77
+ using is_eigen_other
78
+ = all_of<is_template_base_of<Eigen::EigenBase, T>,
79
+ negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
80
+
81
+ // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
82
+ template <bool EigenRowMajor>
83
+ struct EigenConformable {
84
+ bool conformable = false;
85
+ EigenIndex rows = 0, cols = 0;
86
+ EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
87
+ bool negativestrides = false; // If true, do not use stride!
88
+
89
+ // NOLINTNEXTLINE(google-explicit-constructor)
90
+ EigenConformable(bool fits = false) : conformable{fits} {}
91
+ // Matrix type:
92
+ EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
93
+ : conformable{true}, rows{r}, cols{c},
94
+ // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
95
+ // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
96
+ stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
97
+ : (cstride > 0 ? cstride : 0) /* outer stride */,
98
+ EigenRowMajor ? (cstride > 0 ? cstride : 0)
99
+ : (rstride > 0 ? rstride : 0) /* inner stride */},
100
+ negativestrides{rstride < 0 || cstride < 0} {}
101
+ // Vector type:
102
+ EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
103
+ : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
104
+
105
+ template <typename props>
106
+ bool stride_compatible() const {
107
+ // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
108
+ // matching strides, or a dimension size of 1 (in which case the stride value is
109
+ // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
110
+ // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
111
+ if (negativestrides) {
112
+ return false;
113
+ }
114
+ if (rows == 0 || cols == 0) {
115
+ return true;
116
+ }
117
+ return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
118
+ || (EigenRowMajor ? cols : rows) == 1)
119
+ && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
120
+ || (EigenRowMajor ? rows : cols) == 1);
121
+ }
122
+ // NOLINTNEXTLINE(google-explicit-constructor)
123
+ operator bool() const { return conformable; }
124
+ };
125
+
126
+ template <typename Type>
127
+ struct eigen_extract_stride {
128
+ using type = Type;
129
+ };
130
+ template <typename PlainObjectType, int MapOptions, typename StrideType>
131
+ struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
132
+ using type = StrideType;
133
+ };
134
+ template <typename PlainObjectType, int Options, typename StrideType>
135
+ struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
136
+ using type = StrideType;
137
+ };
138
+
139
+ // Helper struct for extracting information from an Eigen type
140
+ template <typename Type_>
141
+ struct EigenProps {
142
+ using Type = Type_;
143
+ using Scalar = typename Type::Scalar;
144
+ using StrideType = typename eigen_extract_stride<Type>::type;
145
+ static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
146
+ size = Type::SizeAtCompileTime;
147
+ static constexpr bool row_major = Type::IsRowMajor,
148
+ vector
149
+ = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
150
+ fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
151
+ fixed = size != Eigen::Dynamic, // Fully-fixed size
152
+ dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
153
+
154
+ template <EigenIndex i, EigenIndex ifzero>
155
+ using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
156
+ static constexpr EigenIndex inner_stride
157
+ = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
158
+ outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
159
+ vector ? size
160
+ : row_major ? cols
161
+ : rows > ::value;
162
+ static constexpr bool dynamic_stride
163
+ = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
164
+ static constexpr bool requires_row_major
165
+ = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
166
+ static constexpr bool requires_col_major
167
+ = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
168
+
169
+ // Takes an input array and determines whether we can make it fit into the Eigen type. If
170
+ // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
171
+ // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
172
+ static EigenConformable<row_major> conformable(const array &a) {
173
+ const auto dims = a.ndim();
174
+ if (dims < 1 || dims > 2) {
175
+ return false;
176
+ }
177
+
178
+ if (dims == 2) { // Matrix type: require exact match (or dynamic)
179
+
180
+ EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
181
+ np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
182
+ np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
183
+ if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) {
184
+ return false;
185
+ }
186
+
187
+ return {np_rows, np_cols, np_rstride, np_cstride};
188
+ }
189
+
190
+ // Otherwise we're storing an n-vector. Only one of the strides will be used, but
191
+ // whichever is used, we want the (single) numpy stride value.
192
+ const EigenIndex n = a.shape(0),
193
+ stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
194
+
195
+ if (vector) { // Eigen type is a compile-time vector
196
+ if (fixed && size != n) {
197
+ return false; // Vector size mismatch
198
+ }
199
+ return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
200
+ }
201
+ if (fixed) {
202
+ // The type has a fixed size, but is not a vector: abort
203
+ return false;
204
+ }
205
+ if (fixed_cols) {
206
+ // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
207
+ // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
208
+ if (cols != n) {
209
+ return false;
210
+ }
211
+ return {1, n, stride};
212
+ } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
213
+ if (fixed_rows && rows != n) {
214
+ return false;
215
+ }
216
+ return {n, 1, stride};
217
+ }
218
+
219
+ static constexpr bool show_writeable
220
+ = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
221
+ static constexpr bool show_order = is_eigen_dense_map<Type>::value;
222
+ static constexpr bool show_c_contiguous = show_order && requires_row_major;
223
+ static constexpr bool show_f_contiguous
224
+ = !show_c_contiguous && show_order && requires_col_major;
225
+
226
+ static constexpr auto descriptor
227
+ = const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
228
+ + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
229
+ + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
230
+ +
231
+ // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
232
+ // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
233
+ // stride options, possibly f_contiguous or c_contiguous. We include them in the
234
+ // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
235
+ // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
236
+ // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
237
+ const_name<show_writeable>(", flags.writeable", "")
238
+ + const_name<show_c_contiguous>(", flags.c_contiguous", "")
239
+ + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
240
+ };
241
+
242
+ // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
243
+ // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
244
+ template <typename props>
245
+ handle
246
+ eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
247
+ constexpr ssize_t elem_size = sizeof(typename props::Scalar);
248
+ array a;
249
+ if (props::vector) {
250
+ a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
251
+ } else {
252
+ a = array({src.rows(), src.cols()},
253
+ {elem_size * src.rowStride(), elem_size * src.colStride()},
254
+ src.data(),
255
+ base);
256
+ }
257
+
258
+ if (!writeable) {
259
+ array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
260
+ }
261
+
262
+ return a.release();
263
+ }
264
+
265
+ // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
266
+ // reference the Eigen object's data with `base` as the python-registered base class (if omitted,
267
+ // the base will be set to None, and lifetime management is up to the caller). The numpy array is
268
+ // non-writeable if the given type is const.
269
+ template <typename props, typename Type>
270
+ handle eigen_ref_array(Type &src, handle parent = none()) {
271
+ // none here is to get past array's should-we-copy detection, which currently always
272
+ // copies when there is no base. Setting the base to None should be harmless.
273
+ return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
274
+ }
275
+
276
+ // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
277
+ // numpy array that references the encapsulated data with a python-side reference to the capsule to
278
+ // tie its destruction to that of any dependent python objects. Const-ness is determined by
279
+ // whether or not the Type of the pointer given is const.
280
+ template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
281
+ handle eigen_encapsulate(Type *src) {
282
+ capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
283
+ return eigen_ref_array<props>(*src, base);
284
+ }
285
+
286
+ // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
287
+ // types.
288
+ template <typename Type>
289
+ struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
290
+ using Scalar = typename Type::Scalar;
291
+ static_assert(!std::is_pointer<Scalar>::value,
292
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
293
+ using props = EigenProps<Type>;
294
+
295
+ bool load(handle src, bool convert) {
296
+ // If we're in no-convert mode, only load if given an array of the correct type
297
+ if (!convert && !isinstance<array_t<Scalar>>(src)) {
298
+ return false;
299
+ }
300
+
301
+ // Coerce into an array, but don't do type conversion yet; the copy below handles it.
302
+ auto buf = array::ensure(src);
303
+
304
+ if (!buf) {
305
+ return false;
306
+ }
307
+
308
+ auto dims = buf.ndim();
309
+ if (dims < 1 || dims > 2) {
310
+ return false;
311
+ }
312
+
313
+ auto fits = props::conformable(buf);
314
+ if (!fits) {
315
+ return false;
316
+ }
317
+
318
+ // Allocate the new type, then build a numpy reference into it
319
+ value = Type(fits.rows, fits.cols);
320
+ auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
321
+ if (dims == 1) {
322
+ ref = ref.squeeze();
323
+ } else if (ref.ndim() == 1) {
324
+ buf = buf.squeeze();
325
+ }
326
+
327
+ int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
328
+
329
+ if (result < 0) { // Copy failed!
330
+ PyErr_Clear();
331
+ return false;
332
+ }
333
+
334
+ return true;
335
+ }
336
+
337
+ private:
338
+ // Cast implementation
339
+ template <typename CType>
340
+ static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
341
+ switch (policy) {
342
+ case return_value_policy::take_ownership:
343
+ case return_value_policy::automatic:
344
+ return eigen_encapsulate<props>(src);
345
+ case return_value_policy::move:
346
+ return eigen_encapsulate<props>(new CType(std::move(*src)));
347
+ case return_value_policy::copy:
348
+ return eigen_array_cast<props>(*src);
349
+ case return_value_policy::reference:
350
+ case return_value_policy::automatic_reference:
351
+ return eigen_ref_array<props>(*src);
352
+ case return_value_policy::reference_internal:
353
+ return eigen_ref_array<props>(*src, parent);
354
+ default:
355
+ throw cast_error("unhandled return_value_policy: should not happen!");
356
+ };
357
+ }
358
+
359
+ public:
360
+ // Normal returned non-reference, non-const value:
361
+ static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
362
+ return cast_impl(&src, return_value_policy::move, parent);
363
+ }
364
+ // If you return a non-reference const, we mark the numpy array readonly:
365
+ static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
366
+ return cast_impl(&src, return_value_policy::move, parent);
367
+ }
368
+ // lvalue reference return; default (automatic) becomes copy
369
+ static handle cast(Type &src, return_value_policy policy, handle parent) {
370
+ if (policy == return_value_policy::automatic
371
+ || policy == return_value_policy::automatic_reference) {
372
+ policy = return_value_policy::copy;
373
+ }
374
+ return cast_impl(&src, policy, parent);
375
+ }
376
+ // const lvalue reference return; default (automatic) becomes copy
377
+ static handle cast(const Type &src, return_value_policy policy, handle parent) {
378
+ if (policy == return_value_policy::automatic
379
+ || policy == return_value_policy::automatic_reference) {
380
+ policy = return_value_policy::copy;
381
+ }
382
+ return cast(&src, policy, parent);
383
+ }
384
+ // non-const pointer return
385
+ static handle cast(Type *src, return_value_policy policy, handle parent) {
386
+ return cast_impl(src, policy, parent);
387
+ }
388
+ // const pointer return
389
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
390
+ return cast_impl(src, policy, parent);
391
+ }
392
+
393
+ static constexpr auto name = props::descriptor;
394
+
395
+ // NOLINTNEXTLINE(google-explicit-constructor)
396
+ operator Type *() { return &value; }
397
+ // NOLINTNEXTLINE(google-explicit-constructor)
398
+ operator Type &() { return value; }
399
+ // NOLINTNEXTLINE(google-explicit-constructor)
400
+ operator Type &&() && { return std::move(value); }
401
+ template <typename T>
402
+ using cast_op_type = movable_cast_op_type<T>;
403
+
404
+ private:
405
+ Type value;
406
+ };
407
+
408
+ // Base class for casting reference/map/block/etc. objects back to python.
409
+ template <typename MapType>
410
+ struct eigen_map_caster {
411
+ static_assert(!std::is_pointer<typename MapType::Scalar>::value,
412
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
413
+
414
+ private:
415
+ using props = EigenProps<MapType>;
416
+
417
+ public:
418
+ // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
419
+ // to stay around), but we'll allow it under the assumption that you know what you're doing
420
+ // (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
421
+ // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
422
+ // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
423
+ // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
424
+ static handle cast(const MapType &src, return_value_policy policy, handle parent) {
425
+ switch (policy) {
426
+ case return_value_policy::copy:
427
+ return eigen_array_cast<props>(src);
428
+ case return_value_policy::reference_internal:
429
+ return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
430
+ case return_value_policy::reference:
431
+ case return_value_policy::automatic:
432
+ case return_value_policy::automatic_reference:
433
+ return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
434
+ default:
435
+ // move, take_ownership don't make any sense for a ref/map:
436
+ pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
437
+ }
438
+ }
439
+
440
+ static constexpr auto name = props::descriptor;
441
+
442
+ // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
443
+ // types but not bound arguments). We still provide them (with an explicitly delete) so that
444
+ // you end up here if you try anyway.
445
+ bool load(handle, bool) = delete;
446
+ operator MapType() = delete;
447
+ template <typename>
448
+ using cast_op_type = MapType;
449
+ };
450
+
451
+ // We can return any map-like object (but can only load Refs, specialized next):
452
+ template <typename Type>
453
+ struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
454
+
455
+ // Loader for Ref<...> arguments. See the documentation for info on how to make this work without
456
+ // copying (it requires some extra effort in many cases).
457
+ template <typename PlainObjectType, typename StrideType>
458
+ struct type_caster<
459
+ Eigen::Ref<PlainObjectType, 0, StrideType>,
460
+ enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
461
+ : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
462
+ private:
463
+ using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
464
+ using props = EigenProps<Type>;
465
+ using Scalar = typename props::Scalar;
466
+ static_assert(!std::is_pointer<Scalar>::value,
467
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
468
+ using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
469
+ using Array
470
+ = array_t<Scalar,
471
+ array::forcecast
472
+ | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
473
+ ? array::c_style
474
+ : (props::row_major ? props::outer_stride : props::inner_stride) == 1
475
+ ? array::f_style
476
+ : 0)>;
477
+ static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
478
+ // Delay construction (these have no default constructor)
479
+ std::unique_ptr<MapType> map;
480
+ std::unique_ptr<Type> ref;
481
+ // Our array. When possible, this is just a numpy array pointing to the source data, but
482
+ // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
483
+ // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
484
+ // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
485
+ // conversion and storage order conversion. (Note that we refuse to use this temporary copy
486
+ // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
487
+ Array copy_or_ref;
488
+
489
+ public:
490
+ bool load(handle src, bool convert) {
491
+ // First check whether what we have is already an array of the right type. If not, we
492
+ // can't avoid a copy (because the copy is also going to do type conversion).
493
+ bool need_copy = !isinstance<Array>(src);
494
+
495
+ EigenConformable<props::row_major> fits;
496
+ if (!need_copy) {
497
+ // We don't need a converting copy, but we also need to check whether the strides are
498
+ // compatible with the Ref's stride requirements
499
+ auto aref = reinterpret_borrow<Array>(src);
500
+
501
+ if (aref && (!need_writeable || aref.writeable())) {
502
+ fits = props::conformable(aref);
503
+ if (!fits) {
504
+ return false; // Incompatible dimensions
505
+ }
506
+ if (!fits.template stride_compatible<props>()) {
507
+ need_copy = true;
508
+ } else {
509
+ copy_or_ref = std::move(aref);
510
+ }
511
+ } else {
512
+ need_copy = true;
513
+ }
514
+ }
515
+
516
+ if (need_copy) {
517
+ // We need to copy: If we need a mutable reference, or we're not supposed to convert
518
+ // (either because we're in the no-convert overload pass, or because we're explicitly
519
+ // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
520
+ if (!convert || need_writeable) {
521
+ return false;
522
+ }
523
+
524
+ Array copy = Array::ensure(src);
525
+ if (!copy) {
526
+ return false;
527
+ }
528
+ fits = props::conformable(copy);
529
+ if (!fits || !fits.template stride_compatible<props>()) {
530
+ return false;
531
+ }
532
+ copy_or_ref = std::move(copy);
533
+ loader_life_support::add_patient(copy_or_ref);
534
+ }
535
+
536
+ ref.reset();
537
+ map.reset(new MapType(data(copy_or_ref),
538
+ fits.rows,
539
+ fits.cols,
540
+ make_stride(fits.stride.outer(), fits.stride.inner())));
541
+ ref.reset(new Type(*map));
542
+
543
+ return true;
544
+ }
545
+
546
+ // NOLINTNEXTLINE(google-explicit-constructor)
547
+ operator Type *() { return ref.get(); }
548
+ // NOLINTNEXTLINE(google-explicit-constructor)
549
+ operator Type &() { return *ref; }
550
+ template <typename _T>
551
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
552
+
553
+ private:
554
+ template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
555
+ Scalar *data(Array &a) {
556
+ return a.mutable_data();
557
+ }
558
+
559
+ template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
560
+ const Scalar *data(Array &a) {
561
+ return a.data();
562
+ }
563
+
564
+ // Attempt to figure out a constructor of `Stride` that will work.
565
+ // If both strides are fixed, use a default constructor:
566
+ template <typename S>
567
+ using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
568
+ && S::OuterStrideAtCompileTime != Eigen::Dynamic
569
+ && std::is_default_constructible<S>::value>;
570
+ // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
571
+ // Eigen::Stride, and use it:
572
+ template <typename S>
573
+ using stride_ctor_dual
574
+ = bool_constant<!stride_ctor_default<S>::value
575
+ && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
576
+ // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
577
+ // it (passing whichever stride is dynamic).
578
+ template <typename S>
579
+ using stride_ctor_outer
580
+ = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
581
+ && S::OuterStrideAtCompileTime == Eigen::Dynamic
582
+ && S::InnerStrideAtCompileTime != Eigen::Dynamic
583
+ && std::is_constructible<S, EigenIndex>::value>;
584
+ template <typename S>
585
+ using stride_ctor_inner
586
+ = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
587
+ && S::InnerStrideAtCompileTime == Eigen::Dynamic
588
+ && S::OuterStrideAtCompileTime != Eigen::Dynamic
589
+ && std::is_constructible<S, EigenIndex>::value>;
590
+
591
+ template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
592
+ static S make_stride(EigenIndex, EigenIndex) {
593
+ return S();
594
+ }
595
+ template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
596
+ static S make_stride(EigenIndex outer, EigenIndex inner) {
597
+ return S(outer, inner);
598
+ }
599
+ template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
600
+ static S make_stride(EigenIndex outer, EigenIndex) {
601
+ return S(outer);
602
+ }
603
+ template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
604
+ static S make_stride(EigenIndex, EigenIndex inner) {
605
+ return S(inner);
606
+ }
607
+ };
608
+
609
+ // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
610
+ // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
611
+ // load() is not supported, but we can cast them into the python domain by first copying to a
612
+ // regular Eigen::Matrix, then casting that.
613
+ template <typename Type>
614
+ struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
615
+ static_assert(!std::is_pointer<typename Type::Scalar>::value,
616
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
617
+
618
+ protected:
619
+ using Matrix
620
+ = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
621
+ using props = EigenProps<Matrix>;
622
+
623
+ public:
624
+ static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
625
+ handle h = eigen_encapsulate<props>(new Matrix(src));
626
+ return h;
627
+ }
628
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
629
+ return cast(*src, policy, parent);
630
+ }
631
+
632
+ static constexpr auto name = props::descriptor;
633
+
634
+ // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
635
+ // types but not bound arguments). We still provide them (with an explicitly delete) so that
636
+ // you end up here if you try anyway.
637
+ bool load(handle, bool) = delete;
638
+ operator Type() = delete;
639
+ template <typename>
640
+ using cast_op_type = Type;
641
+ };
642
+
643
+ template <typename Type>
644
+ struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
645
+ using Scalar = typename Type::Scalar;
646
+ static_assert(!std::is_pointer<Scalar>::value,
647
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
648
+ using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
649
+ using Index = typename Type::Index;
650
+ static constexpr bool rowMajor = Type::IsRowMajor;
651
+
652
+ bool load(handle src, bool) {
653
+ if (!src) {
654
+ return false;
655
+ }
656
+
657
+ auto obj = reinterpret_borrow<object>(src);
658
+ object sparse_module = module_::import("scipy.sparse");
659
+ object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
660
+
661
+ if (!type::handle_of(obj).is(matrix_type)) {
662
+ try {
663
+ obj = matrix_type(obj);
664
+ } catch (const error_already_set &) {
665
+ return false;
666
+ }
667
+ }
668
+
669
+ auto values = array_t<Scalar>((object) obj.attr("data"));
670
+ auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
671
+ auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
672
+ auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
673
+ auto nnz = obj.attr("nnz").cast<Index>();
674
+
675
+ if (!values || !innerIndices || !outerIndices) {
676
+ return false;
677
+ }
678
+
679
+ value = EigenMapSparseMatrix<Scalar,
680
+ Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
681
+ StorageIndex>(shape[0].cast<Index>(),
682
+ shape[1].cast<Index>(),
683
+ std::move(nnz),
684
+ outerIndices.mutable_data(),
685
+ innerIndices.mutable_data(),
686
+ values.mutable_data());
687
+
688
+ return true;
689
+ }
690
+
691
+ static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
692
+ const_cast<Type &>(src).makeCompressed();
693
+
694
+ object matrix_type
695
+ = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
696
+
697
+ array data(src.nonZeros(), src.valuePtr());
698
+ array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
699
+ array innerIndices(src.nonZeros(), src.innerIndexPtr());
700
+
701
+ return matrix_type(pybind11::make_tuple(
702
+ std::move(data), std::move(innerIndices), std::move(outerIndices)),
703
+ pybind11::make_tuple(src.rows(), src.cols()))
704
+ .release();
705
+ }
706
+
707
+ PYBIND11_TYPE_CASTER(Type,
708
+ const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
709
+ "scipy.sparse.csc_matrix[")
710
+ + npy_format_descriptor<Scalar>::name + const_name("]"));
711
+ };
712
+
713
+ PYBIND11_NAMESPACE_END(detail)
714
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/eigen/tensor.h ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eigen/tensor.h: Transparent conversion for Eigen tensors
3
+
4
+ All rights reserved. Use of this source code is governed by a
5
+ BSD-style license that can be found in the LICENSE file.
6
+ */
7
+
8
+ #pragma once
9
+
10
+ #include "../numpy.h"
11
+ #include "common.h"
12
+
13
+ #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
14
+ static_assert(__GNUC__ > 5, "Eigen Tensor support in pybind11 requires GCC > 5.0");
15
+ #endif
16
+
17
+ // Disable warnings for Eigen
18
+ PYBIND11_WARNING_PUSH
19
+ PYBIND11_WARNING_DISABLE_MSVC(4554)
20
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
21
+ #if defined(__MINGW32__)
22
+ PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
23
+ #endif
24
+
25
+ #include <unsupported/Eigen/CXX11/Tensor>
26
+
27
+ PYBIND11_WARNING_POP
28
+
29
+ static_assert(EIGEN_VERSION_AT_LEAST(3, 3, 0),
30
+ "Eigen Tensor support in pybind11 requires Eigen >= 3.3.0");
31
+
32
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
33
+
34
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
35
+
36
+ PYBIND11_NAMESPACE_BEGIN(detail)
37
+
38
+ inline bool is_tensor_aligned(const void *data) {
39
+ return (reinterpret_cast<std::size_t>(data) % EIGEN_DEFAULT_ALIGN_BYTES) == 0;
40
+ }
41
+
42
+ template <typename T>
43
+ constexpr int compute_array_flag_from_tensor() {
44
+ static_assert((static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor))
45
+ || (static_cast<int>(T::Layout) == static_cast<int>(Eigen::ColMajor)),
46
+ "Layout must be row or column major");
47
+ return (static_cast<int>(T::Layout) == static_cast<int>(Eigen::RowMajor)) ? array::c_style
48
+ : array::f_style;
49
+ }
50
+
51
+ template <typename T>
52
+ struct eigen_tensor_helper {};
53
+
54
+ template <typename Scalar_, int NumIndices_, int Options_, typename IndexType>
55
+ struct eigen_tensor_helper<Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>> {
56
+ using Type = Eigen::Tensor<Scalar_, NumIndices_, Options_, IndexType>;
57
+ using ValidType = void;
58
+
59
+ static Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape(const Type &f) {
60
+ return f.dimensions();
61
+ }
62
+
63
+ static constexpr bool
64
+ is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> & /*shape*/) {
65
+ return true;
66
+ }
67
+
68
+ template <typename T>
69
+ struct helper {};
70
+
71
+ template <size_t... Is>
72
+ struct helper<index_sequence<Is...>> {
73
+ static constexpr auto value = concat(const_name(((void) Is, "?"))...);
74
+ };
75
+
76
+ static constexpr auto dimensions_descriptor
77
+ = helper<decltype(make_index_sequence<Type::NumIndices>())>::value;
78
+
79
+ template <typename... Args>
80
+ static Type *alloc(Args &&...args) {
81
+ return new Type(std::forward<Args>(args)...);
82
+ }
83
+
84
+ static void free(Type *tensor) { delete tensor; }
85
+ };
86
+
87
+ template <typename Scalar_, typename std::ptrdiff_t... Indices, int Options_, typename IndexType>
88
+ struct eigen_tensor_helper<
89
+ Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>> {
90
+ using Type = Eigen::TensorFixedSize<Scalar_, Eigen::Sizes<Indices...>, Options_, IndexType>;
91
+ using ValidType = void;
92
+
93
+ static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices>
94
+ get_shape(const Type & /*f*/) {
95
+ return get_shape();
96
+ }
97
+
98
+ static constexpr Eigen::DSizes<typename Type::Index, Type::NumIndices> get_shape() {
99
+ return Eigen::DSizes<typename Type::Index, Type::NumIndices>(Indices...);
100
+ }
101
+
102
+ static bool
103
+ is_correct_shape(const Eigen::DSizes<typename Type::Index, Type::NumIndices> &shape) {
104
+ return get_shape() == shape;
105
+ }
106
+
107
+ static constexpr auto dimensions_descriptor = concat(const_name<Indices>()...);
108
+
109
+ template <typename... Args>
110
+ static Type *alloc(Args &&...args) {
111
+ Eigen::aligned_allocator<Type> allocator;
112
+ return ::new (allocator.allocate(1)) Type(std::forward<Args>(args)...);
113
+ }
114
+
115
+ static void free(Type *tensor) {
116
+ Eigen::aligned_allocator<Type> allocator;
117
+ tensor->~Type();
118
+ allocator.deallocate(tensor, 1);
119
+ }
120
+ };
121
+
122
+ template <typename Type, bool ShowDetails, bool NeedsWriteable = false>
123
+ struct get_tensor_descriptor {
124
+ static constexpr auto details
125
+ = const_name<NeedsWriteable>(", flags.writeable", "")
126
+ + const_name<static_cast<int>(Type::Layout) == static_cast<int>(Eigen::RowMajor)>(
127
+ ", flags.c_contiguous", ", flags.f_contiguous");
128
+ static constexpr auto value
129
+ = const_name("numpy.ndarray[") + npy_format_descriptor<typename Type::Scalar>::name
130
+ + const_name("[") + eigen_tensor_helper<remove_cv_t<Type>>::dimensions_descriptor
131
+ + const_name("]") + const_name<ShowDetails>(details, const_name("")) + const_name("]");
132
+ };
133
+
134
+ // When EIGEN_AVOID_STL_ARRAY is defined, Eigen::DSizes<T, 0> does not have the begin() member
135
+ // function. Falling back to a simple loop works around this issue.
136
+ //
137
+ // We need to disable the type-limits warning for the inner loop when size = 0.
138
+
139
+ PYBIND11_WARNING_PUSH
140
+ PYBIND11_WARNING_DISABLE_GCC("-Wtype-limits")
141
+
142
+ template <typename T, int size>
143
+ std::vector<T> convert_dsizes_to_vector(const Eigen::DSizes<T, size> &arr) {
144
+ std::vector<T> result(size);
145
+
146
+ for (size_t i = 0; i < size; i++) {
147
+ result[i] = arr[i];
148
+ }
149
+
150
+ return result;
151
+ }
152
+
153
+ template <typename T, int size>
154
+ Eigen::DSizes<T, size> get_shape_for_array(const array &arr) {
155
+ Eigen::DSizes<T, size> result;
156
+ const T *shape = arr.shape();
157
+ for (size_t i = 0; i < size; i++) {
158
+ result[i] = shape[i];
159
+ }
160
+
161
+ return result;
162
+ }
163
+
164
+ PYBIND11_WARNING_POP
165
+
166
+ template <typename Type>
167
+ struct type_caster<Type, typename eigen_tensor_helper<Type>::ValidType> {
168
+ static_assert(!std::is_pointer<typename Type::Scalar>::value,
169
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
170
+ using Helper = eigen_tensor_helper<Type>;
171
+ static constexpr auto temp_name = get_tensor_descriptor<Type, false>::value;
172
+ PYBIND11_TYPE_CASTER(Type, temp_name);
173
+
174
+ bool load(handle src, bool convert) {
175
+ if (!convert) {
176
+ if (!isinstance<array>(src)) {
177
+ return false;
178
+ }
179
+ array temp = array::ensure(src);
180
+ if (!temp) {
181
+ return false;
182
+ }
183
+
184
+ if (!temp.dtype().is(dtype::of<typename Type::Scalar>())) {
185
+ return false;
186
+ }
187
+ }
188
+
189
+ array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()> arr(
190
+ reinterpret_borrow<object>(src));
191
+
192
+ if (arr.ndim() != Type::NumIndices) {
193
+ return false;
194
+ }
195
+ auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
196
+
197
+ if (!Helper::is_correct_shape(shape)) {
198
+ return false;
199
+ }
200
+
201
+ #if EIGEN_VERSION_AT_LEAST(3, 4, 0)
202
+ auto data_pointer = arr.data();
203
+ #else
204
+ // Handle Eigen bug
205
+ auto data_pointer = const_cast<typename Type::Scalar *>(arr.data());
206
+ #endif
207
+
208
+ if (is_tensor_aligned(arr.data())) {
209
+ value = Eigen::TensorMap<const Type, Eigen::Aligned>(data_pointer, shape);
210
+ } else {
211
+ value = Eigen::TensorMap<const Type>(data_pointer, shape);
212
+ }
213
+
214
+ return true;
215
+ }
216
+
217
+ static handle cast(Type &&src, return_value_policy policy, handle parent) {
218
+ if (policy == return_value_policy::reference
219
+ || policy == return_value_policy::reference_internal) {
220
+ pybind11_fail("Cannot use a reference return value policy for an rvalue");
221
+ }
222
+ return cast_impl(&src, return_value_policy::move, parent);
223
+ }
224
+
225
+ static handle cast(const Type &&src, return_value_policy policy, handle parent) {
226
+ if (policy == return_value_policy::reference
227
+ || policy == return_value_policy::reference_internal) {
228
+ pybind11_fail("Cannot use a reference return value policy for an rvalue");
229
+ }
230
+ return cast_impl(&src, return_value_policy::move, parent);
231
+ }
232
+
233
+ static handle cast(Type &src, return_value_policy policy, handle parent) {
234
+ if (policy == return_value_policy::automatic
235
+ || policy == return_value_policy::automatic_reference) {
236
+ policy = return_value_policy::copy;
237
+ }
238
+ return cast_impl(&src, policy, parent);
239
+ }
240
+
241
+ static handle cast(const Type &src, return_value_policy policy, handle parent) {
242
+ if (policy == return_value_policy::automatic
243
+ || policy == return_value_policy::automatic_reference) {
244
+ policy = return_value_policy::copy;
245
+ }
246
+ return cast(&src, policy, parent);
247
+ }
248
+
249
+ static handle cast(Type *src, return_value_policy policy, handle parent) {
250
+ if (policy == return_value_policy::automatic) {
251
+ policy = return_value_policy::take_ownership;
252
+ } else if (policy == return_value_policy::automatic_reference) {
253
+ policy = return_value_policy::reference;
254
+ }
255
+ return cast_impl(src, policy, parent);
256
+ }
257
+
258
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
259
+ if (policy == return_value_policy::automatic) {
260
+ policy = return_value_policy::take_ownership;
261
+ } else if (policy == return_value_policy::automatic_reference) {
262
+ policy = return_value_policy::reference;
263
+ }
264
+ return cast_impl(src, policy, parent);
265
+ }
266
+
267
+ template <typename C>
268
+ static handle cast_impl(C *src, return_value_policy policy, handle parent) {
269
+ object parent_object;
270
+ bool writeable = false;
271
+ switch (policy) {
272
+ case return_value_policy::move:
273
+ if (std::is_const<C>::value) {
274
+ pybind11_fail("Cannot move from a constant reference");
275
+ }
276
+
277
+ src = Helper::alloc(std::move(*src));
278
+
279
+ parent_object
280
+ = capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
281
+ writeable = true;
282
+ break;
283
+
284
+ case return_value_policy::take_ownership:
285
+ if (std::is_const<C>::value) {
286
+ // This cast is ugly, and might be UB in some cases, but we don't have an
287
+ // alternative here as we must free that memory
288
+ Helper::free(const_cast<Type *>(src));
289
+ pybind11_fail("Cannot take ownership of a const reference");
290
+ }
291
+
292
+ parent_object
293
+ = capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
294
+ writeable = true;
295
+ break;
296
+
297
+ case return_value_policy::copy:
298
+ writeable = true;
299
+ break;
300
+
301
+ case return_value_policy::reference:
302
+ parent_object = none();
303
+ writeable = !std::is_const<C>::value;
304
+ break;
305
+
306
+ case return_value_policy::reference_internal:
307
+ // Default should do the right thing
308
+ if (!parent) {
309
+ pybind11_fail("Cannot use reference internal when there is no parent");
310
+ }
311
+ parent_object = reinterpret_borrow<object>(parent);
312
+ writeable = !std::is_const<C>::value;
313
+ break;
314
+
315
+ default:
316
+ pybind11_fail("pybind11 bug in eigen.h, please file a bug report");
317
+ }
318
+
319
+ auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
320
+ convert_dsizes_to_vector(Helper::get_shape(*src)), src->data(), parent_object);
321
+
322
+ if (!writeable) {
323
+ array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
324
+ }
325
+
326
+ return result.release();
327
+ }
328
+ };
329
+
330
+ template <typename StoragePointerType,
331
+ bool needs_writeable,
332
+ enable_if_t<!needs_writeable, bool> = true>
333
+ StoragePointerType get_array_data_for_type(array &arr) {
334
+ #if EIGEN_VERSION_AT_LEAST(3, 4, 0)
335
+ return reinterpret_cast<StoragePointerType>(arr.data());
336
+ #else
337
+ // Handle Eigen bug
338
+ return reinterpret_cast<StoragePointerType>(const_cast<void *>(arr.data()));
339
+ #endif
340
+ }
341
+
342
+ template <typename StoragePointerType,
343
+ bool needs_writeable,
344
+ enable_if_t<needs_writeable, bool> = true>
345
+ StoragePointerType get_array_data_for_type(array &arr) {
346
+ return reinterpret_cast<StoragePointerType>(arr.mutable_data());
347
+ }
348
+
349
+ template <typename T, typename = void>
350
+ struct get_storage_pointer_type;
351
+
352
+ template <typename MapType>
353
+ struct get_storage_pointer_type<MapType, void_t<typename MapType::StoragePointerType>> {
354
+ using SPT = typename MapType::StoragePointerType;
355
+ };
356
+
357
+ template <typename MapType>
358
+ struct get_storage_pointer_type<MapType, void_t<typename MapType::PointerArgType>> {
359
+ using SPT = typename MapType::PointerArgType;
360
+ };
361
+
362
+ template <typename Type, int Options>
363
+ struct type_caster<Eigen::TensorMap<Type, Options>,
364
+ typename eigen_tensor_helper<remove_cv_t<Type>>::ValidType> {
365
+ static_assert(!std::is_pointer<typename Type::Scalar>::value,
366
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
367
+ using MapType = Eigen::TensorMap<Type, Options>;
368
+ using Helper = eigen_tensor_helper<remove_cv_t<Type>>;
369
+
370
+ bool load(handle src, bool /*convert*/) {
371
+ // Note that we have a lot more checks here as we want to make sure to avoid copies
372
+ if (!isinstance<array>(src)) {
373
+ return false;
374
+ }
375
+ auto arr = reinterpret_borrow<array>(src);
376
+ if ((arr.flags() & compute_array_flag_from_tensor<Type>()) == 0) {
377
+ return false;
378
+ }
379
+
380
+ if (!arr.dtype().is(dtype::of<typename Type::Scalar>())) {
381
+ return false;
382
+ }
383
+
384
+ if (arr.ndim() != Type::NumIndices) {
385
+ return false;
386
+ }
387
+
388
+ constexpr bool is_aligned = (Options & Eigen::Aligned) != 0;
389
+
390
+ if (is_aligned && !is_tensor_aligned(arr.data())) {
391
+ return false;
392
+ }
393
+
394
+ auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
395
+
396
+ if (!Helper::is_correct_shape(shape)) {
397
+ return false;
398
+ }
399
+
400
+ if (needs_writeable && !arr.writeable()) {
401
+ return false;
402
+ }
403
+
404
+ auto result = get_array_data_for_type<typename get_storage_pointer_type<MapType>::SPT,
405
+ needs_writeable>(arr);
406
+
407
+ value.reset(new MapType(std::move(result), std::move(shape)));
408
+
409
+ return true;
410
+ }
411
+
412
+ static handle cast(MapType &&src, return_value_policy policy, handle parent) {
413
+ return cast_impl(&src, policy, parent);
414
+ }
415
+
416
+ static handle cast(const MapType &&src, return_value_policy policy, handle parent) {
417
+ return cast_impl(&src, policy, parent);
418
+ }
419
+
420
+ static handle cast(MapType &src, return_value_policy policy, handle parent) {
421
+ if (policy == return_value_policy::automatic
422
+ || policy == return_value_policy::automatic_reference) {
423
+ policy = return_value_policy::copy;
424
+ }
425
+ return cast_impl(&src, policy, parent);
426
+ }
427
+
428
+ static handle cast(const MapType &src, return_value_policy policy, handle parent) {
429
+ if (policy == return_value_policy::automatic
430
+ || policy == return_value_policy::automatic_reference) {
431
+ policy = return_value_policy::copy;
432
+ }
433
+ return cast(&src, policy, parent);
434
+ }
435
+
436
+ static handle cast(MapType *src, return_value_policy policy, handle parent) {
437
+ if (policy == return_value_policy::automatic) {
438
+ policy = return_value_policy::take_ownership;
439
+ } else if (policy == return_value_policy::automatic_reference) {
440
+ policy = return_value_policy::reference;
441
+ }
442
+ return cast_impl(src, policy, parent);
443
+ }
444
+
445
+ static handle cast(const MapType *src, return_value_policy policy, handle parent) {
446
+ if (policy == return_value_policy::automatic) {
447
+ policy = return_value_policy::take_ownership;
448
+ } else if (policy == return_value_policy::automatic_reference) {
449
+ policy = return_value_policy::reference;
450
+ }
451
+ return cast_impl(src, policy, parent);
452
+ }
453
+
454
+ template <typename C>
455
+ static handle cast_impl(C *src, return_value_policy policy, handle parent) {
456
+ object parent_object;
457
+ constexpr bool writeable = !std::is_const<C>::value;
458
+ switch (policy) {
459
+ case return_value_policy::reference:
460
+ parent_object = none();
461
+ break;
462
+
463
+ case return_value_policy::reference_internal:
464
+ // Default should do the right thing
465
+ if (!parent) {
466
+ pybind11_fail("Cannot use reference internal when there is no parent");
467
+ }
468
+ parent_object = reinterpret_borrow<object>(parent);
469
+ break;
470
+
471
+ case return_value_policy::take_ownership:
472
+ delete src;
473
+ // fallthrough
474
+ default:
475
+ // move, take_ownership don't make any sense for a ref/map:
476
+ pybind11_fail("Invalid return_value_policy for Eigen Map type, must be either "
477
+ "reference or reference_internal");
478
+ }
479
+
480
+ auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
481
+ convert_dsizes_to_vector(Helper::get_shape(*src)),
482
+ src->data(),
483
+ std::move(parent_object));
484
+
485
+ if (!writeable) {
486
+ array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
487
+ }
488
+
489
+ return result.release();
490
+ }
491
+
492
+ #if EIGEN_VERSION_AT_LEAST(3, 4, 0)
493
+
494
+ static constexpr bool needs_writeable = !std::is_const<typename std::remove_pointer<
495
+ typename get_storage_pointer_type<MapType>::SPT>::type>::value;
496
+ #else
497
+ // Handle Eigen bug
498
+ static constexpr bool needs_writeable = !std::is_const<Type>::value;
499
+ #endif
500
+
501
+ protected:
502
+ // TODO: Move to std::optional once std::optional has more support
503
+ std::unique_ptr<MapType> value;
504
+
505
+ public:
506
+ static constexpr auto name = get_tensor_descriptor<Type, true, needs_writeable>::value;
507
+ explicit operator MapType *() { return value.get(); }
508
+ explicit operator MapType &() { return *value; }
509
+ explicit operator MapType &&() && { return std::move(*value); }
510
+
511
+ template <typename T_>
512
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>;
513
+ };
514
+
515
+ PYBIND11_NAMESPACE_END(detail)
516
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/embed.h ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/embed.h: Support for embedding the interpreter
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+ #include "eval.h"
14
+
15
+ #include <memory>
16
+ #include <vector>
17
+
18
+ #if defined(PYPY_VERSION)
19
+ # error Embedding the interpreter is not supported with PyPy
20
+ #endif
21
+
22
+ #define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
23
+ extern "C" PyObject *pybind11_init_impl_##name(); \
24
+ extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
25
+
26
+ /** \rst
27
+ Add a new module to the table of builtins for the interpreter. Must be
28
+ defined in global scope. The first macro parameter is the name of the
29
+ module (without quotes). The second parameter is the variable which will
30
+ be used as the interface to add functions and classes to the module.
31
+
32
+ .. code-block:: cpp
33
+
34
+ PYBIND11_EMBEDDED_MODULE(example, m) {
35
+ // ... initialize functions and classes here
36
+ m.def("foo", []() {
37
+ return "Hello, World!";
38
+ });
39
+ }
40
+ \endrst */
41
+ #define PYBIND11_EMBEDDED_MODULE(name, variable) \
42
+ static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \
43
+ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
44
+ static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
45
+ auto m = ::pybind11::module_::create_extension_module( \
46
+ PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
47
+ try { \
48
+ PYBIND11_CONCAT(pybind11_init_, name)(m); \
49
+ return m.ptr(); \
50
+ } \
51
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
52
+ } \
53
+ PYBIND11_EMBEDDED_MODULE_IMPL(name) \
54
+ ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
55
+ PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \
56
+ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
57
+ & variable) // NOLINT(bugprone-macro-parentheses)
58
+
59
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
60
+ PYBIND11_NAMESPACE_BEGIN(detail)
61
+
62
+ /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
63
+ struct embedded_module {
64
+ using init_t = PyObject *(*) ();
65
+ embedded_module(const char *name, init_t init) {
66
+ if (Py_IsInitialized() != 0) {
67
+ pybind11_fail("Can't add new modules after the interpreter has been initialized");
68
+ }
69
+
70
+ auto result = PyImport_AppendInittab(name, init);
71
+ if (result == -1) {
72
+ pybind11_fail("Insufficient memory to add a new module");
73
+ }
74
+ }
75
+ };
76
+
77
+ struct wide_char_arg_deleter {
78
+ void operator()(wchar_t *ptr) const {
79
+ // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
80
+ PyMem_RawFree(ptr);
81
+ }
82
+ };
83
+
84
+ inline wchar_t *widen_chars(const char *safe_arg) {
85
+ wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
86
+ return widened_arg;
87
+ }
88
+
89
+ inline void precheck_interpreter() {
90
+ if (Py_IsInitialized() != 0) {
91
+ pybind11_fail("The interpreter is already running");
92
+ }
93
+ }
94
+
95
+ #if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX)
96
+ # define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)
97
+ #endif
98
+
99
+ #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
100
+ inline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers,
101
+ int argc,
102
+ const char *const *argv,
103
+ bool add_program_dir_to_path) {
104
+ detail::precheck_interpreter();
105
+ Py_InitializeEx(init_signal_handlers ? 1 : 0);
106
+ # if defined(WITH_THREAD) && PY_VERSION_HEX < 0x03070000
107
+ PyEval_InitThreads();
108
+ # endif
109
+
110
+ // Before it was special-cased in python 3.8, passing an empty or null argv
111
+ // caused a segfault, so we have to reimplement the special case ourselves.
112
+ bool special_case = (argv == nullptr || argc <= 0);
113
+
114
+ const char *const empty_argv[]{"\0"};
115
+ const char *const *safe_argv = special_case ? empty_argv : argv;
116
+ if (special_case) {
117
+ argc = 1;
118
+ }
119
+
120
+ auto argv_size = static_cast<size_t>(argc);
121
+ // SetArgv* on python 3 takes wchar_t, so we have to convert.
122
+ std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
123
+ std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
124
+ widened_argv_entries.reserve(argv_size);
125
+ for (size_t ii = 0; ii < argv_size; ++ii) {
126
+ widened_argv_entries.emplace_back(detail::widen_chars(safe_argv[ii]));
127
+ if (!widened_argv_entries.back()) {
128
+ // A null here indicates a character-encoding failure or the python
129
+ // interpreter out of memory. Give up.
130
+ return;
131
+ }
132
+ widened_argv[ii] = widened_argv_entries.back().get();
133
+ }
134
+
135
+ auto *pysys_argv = widened_argv.get();
136
+
137
+ PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
138
+ }
139
+ #endif
140
+
141
+ PYBIND11_NAMESPACE_END(detail)
142
+
143
+ #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
144
+ inline void initialize_interpreter(PyConfig *config,
145
+ int argc = 0,
146
+ const char *const *argv = nullptr,
147
+ bool add_program_dir_to_path = true) {
148
+ detail::precheck_interpreter();
149
+ PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast<char *const *>(argv));
150
+ if (PyStatus_Exception(status) != 0) {
151
+ // A failure here indicates a character-encoding failure or the python
152
+ // interpreter out of memory. Give up.
153
+ PyConfig_Clear(config);
154
+ throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
155
+ : "Failed to prepare CPython");
156
+ }
157
+ status = Py_InitializeFromConfig(config);
158
+ if (PyStatus_Exception(status) != 0) {
159
+ PyConfig_Clear(config);
160
+ throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
161
+ : "Failed to init CPython");
162
+ }
163
+ if (add_program_dir_to_path) {
164
+ PyRun_SimpleString("import sys, os.path; "
165
+ "sys.path.insert(0, "
166
+ "os.path.abspath(os.path.dirname(sys.argv[0])) "
167
+ "if sys.argv and os.path.exists(sys.argv[0]) else '')");
168
+ }
169
+ PyConfig_Clear(config);
170
+ }
171
+ #endif
172
+
173
+ /** \rst
174
+ Initialize the Python interpreter. No other pybind11 or CPython API functions can be
175
+ called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
176
+ optional `init_signal_handlers` parameter can be used to skip the registration of
177
+ signal handlers (see the `Python documentation`_ for details). Calling this function
178
+ again after the interpreter has already been initialized is a fatal error.
179
+
180
+ If initializing the Python interpreter fails, then the program is terminated. (This
181
+ is controlled by the CPython runtime and is an exception to pybind11's normal behavior
182
+ of throwing exceptions on errors.)
183
+
184
+ The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
185
+ used to populate ``sys.argv`` and ``sys.path``.
186
+ See the |PySys_SetArgvEx documentation|_ for details.
187
+
188
+ .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
189
+ .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
190
+ .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
191
+ \endrst */
192
+ inline void initialize_interpreter(bool init_signal_handlers = true,
193
+ int argc = 0,
194
+ const char *const *argv = nullptr,
195
+ bool add_program_dir_to_path = true) {
196
+ #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
197
+ detail::initialize_interpreter_pre_pyconfig(
198
+ init_signal_handlers, argc, argv, add_program_dir_to_path);
199
+ #else
200
+ PyConfig config;
201
+ PyConfig_InitPythonConfig(&config);
202
+ // See PR #4473 for background
203
+ config.parse_argv = 0;
204
+
205
+ config.install_signal_handlers = init_signal_handlers ? 1 : 0;
206
+ initialize_interpreter(&config, argc, argv, add_program_dir_to_path);
207
+ #endif
208
+ }
209
+
210
+ /** \rst
211
+ Shut down the Python interpreter. No pybind11 or CPython API functions can be called
212
+ after this. In addition, pybind11 objects must not outlive the interpreter:
213
+
214
+ .. code-block:: cpp
215
+
216
+ { // BAD
217
+ py::initialize_interpreter();
218
+ auto hello = py::str("Hello, World!");
219
+ py::finalize_interpreter();
220
+ } // <-- BOOM, hello's destructor is called after interpreter shutdown
221
+
222
+ { // GOOD
223
+ py::initialize_interpreter();
224
+ { // scoped
225
+ auto hello = py::str("Hello, World!");
226
+ } // <-- OK, hello is cleaned up properly
227
+ py::finalize_interpreter();
228
+ }
229
+
230
+ { // BETTER
231
+ py::scoped_interpreter guard{};
232
+ auto hello = py::str("Hello, World!");
233
+ }
234
+
235
+ .. warning::
236
+
237
+ The interpreter can be restarted by calling `initialize_interpreter` again.
238
+ Modules created using pybind11 can be safely re-initialized. However, Python
239
+ itself cannot completely unload binary extension modules and there are several
240
+ caveats with regard to interpreter restarting. All the details can be found
241
+ in the CPython documentation. In short, not all interpreter memory may be
242
+ freed, either due to reference cycles or user-created global data.
243
+
244
+ \endrst */
245
+ inline void finalize_interpreter() {
246
+ // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
247
+ // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
248
+ // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
249
+ detail::internals **internals_ptr_ptr = detail::get_internals_pp();
250
+ // It could also be stashed in state_dict, so look there too:
251
+ if (object internals_obj
252
+ = get_internals_obj_from_state_dict(detail::get_python_state_dict())) {
253
+ internals_ptr_ptr = detail::get_internals_pp_from_capsule(internals_obj);
254
+ }
255
+ // Local internals contains data managed by the current interpreter, so we must clear them to
256
+ // avoid undefined behaviors when initializing another interpreter
257
+ detail::get_local_internals().registered_types_cpp.clear();
258
+ detail::get_local_internals().registered_exception_translators.clear();
259
+
260
+ Py_Finalize();
261
+
262
+ if (internals_ptr_ptr) {
263
+ delete *internals_ptr_ptr;
264
+ *internals_ptr_ptr = nullptr;
265
+ }
266
+ }
267
+
268
+ /** \rst
269
+ Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
270
+ This a move-only guard and only a single instance can exist.
271
+
272
+ See `initialize_interpreter` for a discussion of its constructor arguments.
273
+
274
+ .. code-block:: cpp
275
+
276
+ #include <pybind11/embed.h>
277
+
278
+ int main() {
279
+ py::scoped_interpreter guard{};
280
+ py::print(Hello, World!);
281
+ } // <-- interpreter shutdown
282
+ \endrst */
283
+ class scoped_interpreter {
284
+ public:
285
+ explicit scoped_interpreter(bool init_signal_handlers = true,
286
+ int argc = 0,
287
+ const char *const *argv = nullptr,
288
+ bool add_program_dir_to_path = true) {
289
+ initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
290
+ }
291
+
292
+ #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
293
+ explicit scoped_interpreter(PyConfig *config,
294
+ int argc = 0,
295
+ const char *const *argv = nullptr,
296
+ bool add_program_dir_to_path = true) {
297
+ initialize_interpreter(config, argc, argv, add_program_dir_to_path);
298
+ }
299
+ #endif
300
+
301
+ scoped_interpreter(const scoped_interpreter &) = delete;
302
+ scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
303
+ scoped_interpreter &operator=(const scoped_interpreter &) = delete;
304
+ scoped_interpreter &operator=(scoped_interpreter &&) = delete;
305
+
306
+ ~scoped_interpreter() {
307
+ if (is_valid) {
308
+ finalize_interpreter();
309
+ }
310
+ }
311
+
312
+ private:
313
+ bool is_valid = true;
314
+ };
315
+
316
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/eval.h ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eval.h: Support for evaluating Python expressions and statements
3
+ from strings and files
4
+
5
+ Copyright (c) 2016 Klemens Morgenstern <klemens.morgenstern@ed-chemnitz.de> and
6
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
7
+
8
+ All rights reserved. Use of this source code is governed by a
9
+ BSD-style license that can be found in the LICENSE file.
10
+ */
11
+
12
+ #pragma once
13
+
14
+ #include "pybind11.h"
15
+
16
+ #include <utility>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+ PYBIND11_NAMESPACE_BEGIN(detail)
20
+
21
+ inline void ensure_builtins_in_globals(object &global) {
22
+ #if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x03080000
23
+ // Running exec and eval adds `builtins` module under `__builtins__` key to
24
+ // globals if not yet present. Python 3.8 made PyRun_String behave
25
+ // similarly. Let's also do that for older versions, for consistency. This
26
+ // was missing from PyPy3.8 7.3.7.
27
+ if (!global.contains("__builtins__"))
28
+ global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE);
29
+ #else
30
+ (void) global;
31
+ #endif
32
+ }
33
+
34
+ PYBIND11_NAMESPACE_END(detail)
35
+
36
+ enum eval_mode {
37
+ /// Evaluate a string containing an isolated expression
38
+ eval_expr,
39
+
40
+ /// Evaluate a string containing a single statement. Returns \c none
41
+ eval_single_statement,
42
+
43
+ /// Evaluate a string containing a sequence of statement. Returns \c none
44
+ eval_statements
45
+ };
46
+
47
+ template <eval_mode mode = eval_expr>
48
+ object eval(const str &expr, object global = globals(), object local = object()) {
49
+ if (!local) {
50
+ local = global;
51
+ }
52
+
53
+ detail::ensure_builtins_in_globals(global);
54
+
55
+ /* PyRun_String does not accept a PyObject / encoding specifier,
56
+ this seems to be the only alternative */
57
+ std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr;
58
+
59
+ int start = 0;
60
+ switch (mode) {
61
+ case eval_expr:
62
+ start = Py_eval_input;
63
+ break;
64
+ case eval_single_statement:
65
+ start = Py_single_input;
66
+ break;
67
+ case eval_statements:
68
+ start = Py_file_input;
69
+ break;
70
+ default:
71
+ pybind11_fail("invalid evaluation mode");
72
+ }
73
+
74
+ PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
75
+ if (!result) {
76
+ throw error_already_set();
77
+ }
78
+ return reinterpret_steal<object>(result);
79
+ }
80
+
81
+ template <eval_mode mode = eval_expr, size_t N>
82
+ object eval(const char (&s)[N], object global = globals(), object local = object()) {
83
+ /* Support raw string literals by removing common leading whitespace */
84
+ auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s);
85
+ return eval<mode>(expr, std::move(global), std::move(local));
86
+ }
87
+
88
+ inline void exec(const str &expr, object global = globals(), object local = object()) {
89
+ eval<eval_statements>(expr, std::move(global), std::move(local));
90
+ }
91
+
92
+ template <size_t N>
93
+ void exec(const char (&s)[N], object global = globals(), object local = object()) {
94
+ eval<eval_statements>(s, std::move(global), std::move(local));
95
+ }
96
+
97
+ #if defined(PYPY_VERSION)
98
+ template <eval_mode mode = eval_statements>
99
+ object eval_file(str, object, object) {
100
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
101
+ }
102
+ template <eval_mode mode = eval_statements>
103
+ object eval_file(str, object) {
104
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
105
+ }
106
+ template <eval_mode mode = eval_statements>
107
+ object eval_file(str) {
108
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
109
+ }
110
+ #else
111
+ template <eval_mode mode = eval_statements>
112
+ object eval_file(str fname, object global = globals(), object local = object()) {
113
+ if (!local) {
114
+ local = global;
115
+ }
116
+
117
+ detail::ensure_builtins_in_globals(global);
118
+
119
+ int start = 0;
120
+ switch (mode) {
121
+ case eval_expr:
122
+ start = Py_eval_input;
123
+ break;
124
+ case eval_single_statement:
125
+ start = Py_single_input;
126
+ break;
127
+ case eval_statements:
128
+ start = Py_file_input;
129
+ break;
130
+ default:
131
+ pybind11_fail("invalid evaluation mode");
132
+ }
133
+
134
+ int closeFile = 1;
135
+ std::string fname_str = (std::string) fname;
136
+ FILE *f = _Py_fopen_obj(fname.ptr(), "r");
137
+ if (!f) {
138
+ PyErr_Clear();
139
+ pybind11_fail("File \"" + fname_str + "\" could not be opened!");
140
+ }
141
+
142
+ if (!global.contains("__file__")) {
143
+ global["__file__"] = std::move(fname);
144
+ }
145
+
146
+ PyObject *result
147
+ = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
148
+
149
+ if (!result) {
150
+ throw error_already_set();
151
+ }
152
+ return reinterpret_steal<object>(result);
153
+ }
154
+ #endif
155
+
156
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/functional.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/functional.h: std::function<> support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ #include <functional>
15
+
16
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17
+ PYBIND11_NAMESPACE_BEGIN(detail)
18
+
19
+ template <typename Return, typename... Args>
20
+ struct type_caster<std::function<Return(Args...)>> {
21
+ using type = std::function<Return(Args...)>;
22
+ using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
23
+ using function_type = Return (*)(Args...);
24
+
25
+ public:
26
+ bool load(handle src, bool convert) {
27
+ if (src.is_none()) {
28
+ // Defer accepting None to other overloads (if we aren't in convert mode):
29
+ if (!convert) {
30
+ return false;
31
+ }
32
+ return true;
33
+ }
34
+
35
+ if (!isinstance<function>(src)) {
36
+ return false;
37
+ }
38
+
39
+ auto func = reinterpret_borrow<function>(src);
40
+
41
+ /*
42
+ When passing a C++ function as an argument to another C++
43
+ function via Python, every function call would normally involve
44
+ a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
45
+ Here, we try to at least detect the case where the function is
46
+ stateless (i.e. function pointer or lambda function without
47
+ captured variables), in which case the roundtrip can be avoided.
48
+ */
49
+ if (auto cfunc = func.cpp_function()) {
50
+ auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr());
51
+ if (cfunc_self == nullptr) {
52
+ PyErr_Clear();
53
+ } else if (isinstance<capsule>(cfunc_self)) {
54
+ auto c = reinterpret_borrow<capsule>(cfunc_self);
55
+
56
+ function_record *rec = nullptr;
57
+ // Check that we can safely reinterpret the capsule into a function_record
58
+ if (detail::is_function_record_capsule(c)) {
59
+ rec = c.get_pointer<function_record>();
60
+ }
61
+
62
+ while (rec != nullptr) {
63
+ if (rec->is_stateless
64
+ && same_type(typeid(function_type),
65
+ *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
66
+ struct capture {
67
+ function_type f;
68
+ };
69
+ value = ((capture *) &rec->data)->f;
70
+ return true;
71
+ }
72
+ rec = rec->next;
73
+ }
74
+ }
75
+ // PYPY segfaults here when passing builtin function like sum.
76
+ // Raising an fail exception here works to prevent the segfault, but only on gcc.
77
+ // See PR #1413 for full details
78
+ }
79
+
80
+ // ensure GIL is held during functor destruction
81
+ struct func_handle {
82
+ function f;
83
+ #if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17))
84
+ // This triggers a syntax error under very special conditions (very weird indeed).
85
+ explicit
86
+ #endif
87
+ func_handle(function &&f_) noexcept
88
+ : f(std::move(f_)) {
89
+ }
90
+ func_handle(const func_handle &f_) { operator=(f_); }
91
+ func_handle &operator=(const func_handle &f_) {
92
+ gil_scoped_acquire acq;
93
+ f = f_.f;
94
+ return *this;
95
+ }
96
+ ~func_handle() {
97
+ gil_scoped_acquire acq;
98
+ function kill_f(std::move(f));
99
+ }
100
+ };
101
+
102
+ // to emulate 'move initialization capture' in C++11
103
+ struct func_wrapper {
104
+ func_handle hfunc;
105
+ explicit func_wrapper(func_handle &&hf) noexcept : hfunc(std::move(hf)) {}
106
+ Return operator()(Args... args) const {
107
+ gil_scoped_acquire acq;
108
+ // casts the returned object as a rvalue to the return type
109
+ return hfunc.f(std::forward<Args>(args)...).template cast<Return>();
110
+ }
111
+ };
112
+
113
+ value = func_wrapper(func_handle(std::move(func)));
114
+ return true;
115
+ }
116
+
117
+ template <typename Func>
118
+ static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
119
+ if (!f_) {
120
+ return none().release();
121
+ }
122
+
123
+ auto result = f_.template target<function_type>();
124
+ if (result) {
125
+ return cpp_function(*result, policy).release();
126
+ }
127
+ return cpp_function(std::forward<Func>(f_), policy).release();
128
+ }
129
+
130
+ PYBIND11_TYPE_CASTER(type,
131
+ const_name("Callable[[") + concat(make_caster<Args>::name...)
132
+ + const_name("], ") + make_caster<retval_type>::name
133
+ + const_name("]"));
134
+ };
135
+
136
+ PYBIND11_NAMESPACE_END(detail)
137
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/gil.h ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/gil.h: RAII helpers for managing the GIL
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+
14
+ #if defined(WITH_THREAD) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
15
+ # include "detail/internals.h"
16
+ #endif
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+
20
+ PYBIND11_NAMESPACE_BEGIN(detail)
21
+
22
+ // forward declarations
23
+ PyThreadState *get_thread_state_unchecked();
24
+
25
+ PYBIND11_NAMESPACE_END(detail)
26
+
27
+ #if defined(WITH_THREAD)
28
+
29
+ # if !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
30
+
31
+ /* The functions below essentially reproduce the PyGILState_* API using a RAII
32
+ * pattern, but there are a few important differences:
33
+ *
34
+ * 1. When acquiring the GIL from an non-main thread during the finalization
35
+ * phase, the GILState API blindly terminates the calling thread, which
36
+ * is often not what is wanted. This API does not do this.
37
+ *
38
+ * 2. The gil_scoped_release function can optionally cut the relationship
39
+ * of a PyThreadState and its associated thread, which allows moving it to
40
+ * another thread (this is a fairly rare/advanced use case).
41
+ *
42
+ * 3. The reference count of an acquired thread state can be controlled. This
43
+ * can be handy to prevent cases where callbacks issued from an external
44
+ * thread would otherwise constantly construct and destroy thread state data
45
+ * structures.
46
+ *
47
+ * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
48
+ * example which uses features 2 and 3 to migrate the Python thread of
49
+ * execution to another thread (to run the event loop on the original thread,
50
+ * in this case).
51
+ */
52
+
53
+ class gil_scoped_acquire {
54
+ public:
55
+ PYBIND11_NOINLINE gil_scoped_acquire() {
56
+ auto &internals = detail::get_internals();
57
+ tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
58
+
59
+ if (!tstate) {
60
+ /* Check if the GIL was acquired using the PyGILState_* API instead (e.g. if
61
+ calling from a Python thread). Since we use a different key, this ensures
62
+ we don't create a new thread state and deadlock in PyEval_AcquireThread
63
+ below. Note we don't save this state with internals.tstate, since we don't
64
+ create it we would fail to clear it (its reference count should be > 0). */
65
+ tstate = PyGILState_GetThisThreadState();
66
+ }
67
+
68
+ if (!tstate) {
69
+ tstate = PyThreadState_New(internals.istate);
70
+ # if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
71
+ if (!tstate) {
72
+ pybind11_fail("scoped_acquire: could not create thread state!");
73
+ }
74
+ # endif
75
+ tstate->gilstate_counter = 0;
76
+ PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
77
+ } else {
78
+ release = detail::get_thread_state_unchecked() != tstate;
79
+ }
80
+
81
+ if (release) {
82
+ PyEval_AcquireThread(tstate);
83
+ }
84
+
85
+ inc_ref();
86
+ }
87
+
88
+ gil_scoped_acquire(const gil_scoped_acquire &) = delete;
89
+ gil_scoped_acquire &operator=(const gil_scoped_acquire &) = delete;
90
+
91
+ void inc_ref() { ++tstate->gilstate_counter; }
92
+
93
+ PYBIND11_NOINLINE void dec_ref() {
94
+ --tstate->gilstate_counter;
95
+ # if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
96
+ if (detail::get_thread_state_unchecked() != tstate) {
97
+ pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
98
+ }
99
+ if (tstate->gilstate_counter < 0) {
100
+ pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
101
+ }
102
+ # endif
103
+ if (tstate->gilstate_counter == 0) {
104
+ # if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
105
+ if (!release) {
106
+ pybind11_fail("scoped_acquire::dec_ref(): internal error!");
107
+ }
108
+ # endif
109
+ PyThreadState_Clear(tstate);
110
+ if (active) {
111
+ PyThreadState_DeleteCurrent();
112
+ }
113
+ PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
114
+ release = false;
115
+ }
116
+ }
117
+
118
+ /// This method will disable the PyThreadState_DeleteCurrent call and the
119
+ /// GIL won't be acquired. This method should be used if the interpreter
120
+ /// could be shutting down when this is called, as thread deletion is not
121
+ /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
122
+ /// protect subsequent code.
123
+ PYBIND11_NOINLINE void disarm() { active = false; }
124
+
125
+ PYBIND11_NOINLINE ~gil_scoped_acquire() {
126
+ dec_ref();
127
+ if (release) {
128
+ PyEval_SaveThread();
129
+ }
130
+ }
131
+
132
+ private:
133
+ PyThreadState *tstate = nullptr;
134
+ bool release = true;
135
+ bool active = true;
136
+ };
137
+
138
+ class gil_scoped_release {
139
+ public:
140
+ explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
141
+ // `get_internals()` must be called here unconditionally in order to initialize
142
+ // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
143
+ // initialization race could occur as multiple threads try `gil_scoped_acquire`.
144
+ auto &internals = detail::get_internals();
145
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
146
+ tstate = PyEval_SaveThread();
147
+ if (disassoc) {
148
+ // Python >= 3.7 can remove this, it's an int before 3.7
149
+ // NOLINTNEXTLINE(readability-qualified-auto)
150
+ auto key = internals.tstate;
151
+ PYBIND11_TLS_DELETE_VALUE(key);
152
+ }
153
+ }
154
+
155
+ gil_scoped_release(const gil_scoped_release &) = delete;
156
+ gil_scoped_release &operator=(const gil_scoped_release &) = delete;
157
+
158
+ /// This method will disable the PyThreadState_DeleteCurrent call and the
159
+ /// GIL won't be acquired. This method should be used if the interpreter
160
+ /// could be shutting down when this is called, as thread deletion is not
161
+ /// allowed during shutdown. Check _Py_IsFinalizing() on Python 3.7+, and
162
+ /// protect subsequent code.
163
+ PYBIND11_NOINLINE void disarm() { active = false; }
164
+
165
+ ~gil_scoped_release() {
166
+ if (!tstate) {
167
+ return;
168
+ }
169
+ // `PyEval_RestoreThread()` should not be called if runtime is finalizing
170
+ if (active) {
171
+ PyEval_RestoreThread(tstate);
172
+ }
173
+ if (disassoc) {
174
+ // Python >= 3.7 can remove this, it's an int before 3.7
175
+ // NOLINTNEXTLINE(readability-qualified-auto)
176
+ auto key = detail::get_internals().tstate;
177
+ PYBIND11_TLS_REPLACE_VALUE(key, tstate);
178
+ }
179
+ }
180
+
181
+ private:
182
+ PyThreadState *tstate;
183
+ bool disassoc;
184
+ bool active = true;
185
+ };
186
+
187
+ # else // PYBIND11_SIMPLE_GIL_MANAGEMENT
188
+
189
+ class gil_scoped_acquire {
190
+ PyGILState_STATE state;
191
+
192
+ public:
193
+ gil_scoped_acquire() : state{PyGILState_Ensure()} {}
194
+ gil_scoped_acquire(const gil_scoped_acquire &) = delete;
195
+ gil_scoped_acquire &operator=(const gil_scoped_acquire &) = delete;
196
+ ~gil_scoped_acquire() { PyGILState_Release(state); }
197
+ void disarm() {}
198
+ };
199
+
200
+ class gil_scoped_release {
201
+ PyThreadState *state;
202
+
203
+ public:
204
+ gil_scoped_release() : state{PyEval_SaveThread()} {}
205
+ gil_scoped_release(const gil_scoped_release &) = delete;
206
+ gil_scoped_release &operator=(const gil_scoped_release &) = delete;
207
+ ~gil_scoped_release() { PyEval_RestoreThread(state); }
208
+ void disarm() {}
209
+ };
210
+
211
+ # endif // PYBIND11_SIMPLE_GIL_MANAGEMENT
212
+
213
+ #else // WITH_THREAD
214
+
215
+ class gil_scoped_acquire {
216
+ public:
217
+ gil_scoped_acquire() {
218
+ // Trick to suppress `unused variable` error messages (at call sites).
219
+ (void) (this != (this + 1));
220
+ }
221
+ gil_scoped_acquire(const gil_scoped_acquire &) = delete;
222
+ gil_scoped_acquire &operator=(const gil_scoped_acquire &) = delete;
223
+ void disarm() {}
224
+ };
225
+
226
+ class gil_scoped_release {
227
+ public:
228
+ gil_scoped_release() {
229
+ // Trick to suppress `unused variable` error messages (at call sites).
230
+ (void) (this != (this + 1));
231
+ }
232
+ gil_scoped_release(const gil_scoped_release &) = delete;
233
+ gil_scoped_release &operator=(const gil_scoped_release &) = delete;
234
+ void disarm() {}
235
+ };
236
+
237
+ #endif // WITH_THREAD
238
+
239
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/iostream.h ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
3
+
4
+ Copyright (c) 2017 Henry F. Schreiner
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+
9
+ WARNING: The implementation in this file is NOT thread safe. Multiple
10
+ threads writing to a redirected ostream concurrently cause data races
11
+ and potentially buffer overflows. Therefore it is currently a requirement
12
+ that all (possibly) concurrent redirected ostream writes are protected by
13
+ a mutex.
14
+ #HelpAppreciated: Work on iostream.h thread safety.
15
+ For more background see the discussions under
16
+ https://github.com/pybind/pybind11/pull/2982 and
17
+ https://github.com/pybind/pybind11/pull/2995.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include "pybind11.h"
23
+
24
+ #include <algorithm>
25
+ #include <cstring>
26
+ #include <iostream>
27
+ #include <iterator>
28
+ #include <memory>
29
+ #include <ostream>
30
+ #include <streambuf>
31
+ #include <string>
32
+ #include <utility>
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ // Buffer that writes to Python instead of C++
38
+ class pythonbuf : public std::streambuf {
39
+ private:
40
+ using traits_type = std::streambuf::traits_type;
41
+
42
+ const size_t buf_size;
43
+ std::unique_ptr<char[]> d_buffer;
44
+ object pywrite;
45
+ object pyflush;
46
+
47
+ int overflow(int c) override {
48
+ if (!traits_type::eq_int_type(c, traits_type::eof())) {
49
+ *pptr() = traits_type::to_char_type(c);
50
+ pbump(1);
51
+ }
52
+ return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
53
+ }
54
+
55
+ // Computes how many bytes at the end of the buffer are part of an
56
+ // incomplete sequence of UTF-8 bytes.
57
+ // Precondition: pbase() < pptr()
58
+ size_t utf8_remainder() const {
59
+ const auto rbase = std::reverse_iterator<char *>(pbase());
60
+ const auto rpptr = std::reverse_iterator<char *>(pptr());
61
+ auto is_ascii = [](char c) { return (static_cast<unsigned char>(c) & 0x80) == 0x00; };
62
+ auto is_leading = [](char c) { return (static_cast<unsigned char>(c) & 0xC0) == 0xC0; };
63
+ auto is_leading_2b = [](char c) { return static_cast<unsigned char>(c) <= 0xDF; };
64
+ auto is_leading_3b = [](char c) { return static_cast<unsigned char>(c) <= 0xEF; };
65
+ // If the last character is ASCII, there are no incomplete code points
66
+ if (is_ascii(*rpptr)) {
67
+ return 0;
68
+ }
69
+ // Otherwise, work back from the end of the buffer and find the first
70
+ // UTF-8 leading byte
71
+ const auto rpend = rbase - rpptr >= 3 ? rpptr + 3 : rbase;
72
+ const auto leading = std::find_if(rpptr, rpend, is_leading);
73
+ if (leading == rbase) {
74
+ return 0;
75
+ }
76
+ const auto dist = static_cast<size_t>(leading - rpptr);
77
+ size_t remainder = 0;
78
+
79
+ if (dist == 0) {
80
+ remainder = 1; // 1-byte code point is impossible
81
+ } else if (dist == 1) {
82
+ remainder = is_leading_2b(*leading) ? 0 : dist + 1;
83
+ } else if (dist == 2) {
84
+ remainder = is_leading_3b(*leading) ? 0 : dist + 1;
85
+ }
86
+ // else if (dist >= 3), at least 4 bytes before encountering an UTF-8
87
+ // leading byte, either no remainder or invalid UTF-8.
88
+ // Invalid UTF-8 will cause an exception later when converting
89
+ // to a Python string, so that's not handled here.
90
+ return remainder;
91
+ }
92
+
93
+ // This function must be non-virtual to be called in a destructor.
94
+ int _sync() {
95
+ if (pbase() != pptr()) { // If buffer is not empty
96
+ gil_scoped_acquire tmp;
97
+ // This subtraction cannot be negative, so dropping the sign.
98
+ auto size = static_cast<size_t>(pptr() - pbase());
99
+ size_t remainder = utf8_remainder();
100
+
101
+ if (size > remainder) {
102
+ str line(pbase(), size - remainder);
103
+ pywrite(std::move(line));
104
+ pyflush();
105
+ }
106
+
107
+ // Copy the remainder at the end of the buffer to the beginning:
108
+ if (remainder > 0) {
109
+ std::memmove(pbase(), pptr() - remainder, remainder);
110
+ }
111
+ setp(pbase(), epptr());
112
+ pbump(static_cast<int>(remainder));
113
+ }
114
+ return 0;
115
+ }
116
+
117
+ int sync() override { return _sync(); }
118
+
119
+ public:
120
+ explicit pythonbuf(const object &pyostream, size_t buffer_size = 1024)
121
+ : buf_size(buffer_size), d_buffer(new char[buf_size]), pywrite(pyostream.attr("write")),
122
+ pyflush(pyostream.attr("flush")) {
123
+ setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
124
+ }
125
+
126
+ pythonbuf(pythonbuf &&) = default;
127
+
128
+ /// Sync before destroy
129
+ ~pythonbuf() override { _sync(); }
130
+ };
131
+
132
+ PYBIND11_NAMESPACE_END(detail)
133
+
134
+ /** \rst
135
+ This a move-only guard that redirects output.
136
+
137
+ .. code-block:: cpp
138
+
139
+ #include <pybind11/iostream.h>
140
+
141
+ ...
142
+
143
+ {
144
+ py::scoped_ostream_redirect output;
145
+ std::cout << "Hello, World!"; // Python stdout
146
+ } // <-- return std::cout to normal
147
+
148
+ You can explicitly pass the c++ stream and the python object,
149
+ for example to guard stderr instead.
150
+
151
+ .. code-block:: cpp
152
+
153
+ {
154
+ py::scoped_ostream_redirect output{
155
+ std::cerr, py::module::import("sys").attr("stderr")};
156
+ std::cout << "Hello, World!";
157
+ }
158
+ \endrst */
159
+ class scoped_ostream_redirect {
160
+ protected:
161
+ std::streambuf *old;
162
+ std::ostream &costream;
163
+ detail::pythonbuf buffer;
164
+
165
+ public:
166
+ explicit scoped_ostream_redirect(std::ostream &costream = std::cout,
167
+ const object &pyostream
168
+ = module_::import("sys").attr("stdout"))
169
+ : costream(costream), buffer(pyostream) {
170
+ old = costream.rdbuf(&buffer);
171
+ }
172
+
173
+ ~scoped_ostream_redirect() { costream.rdbuf(old); }
174
+
175
+ scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
176
+ scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
177
+ scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
178
+ scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
179
+ };
180
+
181
+ /** \rst
182
+ Like `scoped_ostream_redirect`, but redirects cerr by default. This class
183
+ is provided primary to make ``py::call_guard`` easier to make.
184
+
185
+ .. code-block:: cpp
186
+
187
+ m.def("noisy_func", &noisy_func,
188
+ py::call_guard<scoped_ostream_redirect,
189
+ scoped_estream_redirect>());
190
+
191
+ \endrst */
192
+ class scoped_estream_redirect : public scoped_ostream_redirect {
193
+ public:
194
+ explicit scoped_estream_redirect(std::ostream &costream = std::cerr,
195
+ const object &pyostream
196
+ = module_::import("sys").attr("stderr"))
197
+ : scoped_ostream_redirect(costream, pyostream) {}
198
+ };
199
+
200
+ PYBIND11_NAMESPACE_BEGIN(detail)
201
+
202
+ // Class to redirect output as a context manager. C++ backend.
203
+ class OstreamRedirect {
204
+ bool do_stdout_;
205
+ bool do_stderr_;
206
+ std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
207
+ std::unique_ptr<scoped_estream_redirect> redirect_stderr;
208
+
209
+ public:
210
+ explicit OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
211
+ : do_stdout_(do_stdout), do_stderr_(do_stderr) {}
212
+
213
+ void enter() {
214
+ if (do_stdout_) {
215
+ redirect_stdout.reset(new scoped_ostream_redirect());
216
+ }
217
+ if (do_stderr_) {
218
+ redirect_stderr.reset(new scoped_estream_redirect());
219
+ }
220
+ }
221
+
222
+ void exit() {
223
+ redirect_stdout.reset();
224
+ redirect_stderr.reset();
225
+ }
226
+ };
227
+
228
+ PYBIND11_NAMESPACE_END(detail)
229
+
230
+ /** \rst
231
+ This is a helper function to add a C++ redirect context manager to Python
232
+ instead of using a C++ guard. To use it, add the following to your binding code:
233
+
234
+ .. code-block:: cpp
235
+
236
+ #include <pybind11/iostream.h>
237
+
238
+ ...
239
+
240
+ py::add_ostream_redirect(m, "ostream_redirect");
241
+
242
+ You now have a Python context manager that redirects your output:
243
+
244
+ .. code-block:: python
245
+
246
+ with m.ostream_redirect():
247
+ m.print_to_cout_function()
248
+
249
+ This manager can optionally be told which streams to operate on:
250
+
251
+ .. code-block:: python
252
+
253
+ with m.ostream_redirect(stdout=true, stderr=true):
254
+ m.noisy_function_with_error_printing()
255
+
256
+ \endrst */
257
+ inline class_<detail::OstreamRedirect>
258
+ add_ostream_redirect(module_ m, const std::string &name = "ostream_redirect") {
259
+ return class_<detail::OstreamRedirect>(std::move(m), name.c_str(), module_local())
260
+ .def(init<bool, bool>(), arg("stdout") = true, arg("stderr") = true)
261
+ .def("__enter__", &detail::OstreamRedirect::enter)
262
+ .def("__exit__", [](detail::OstreamRedirect &self_, const args &) { self_.exit(); });
263
+ }
264
+
265
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
videollama2/lib/python3.10/site-packages/torch/include/pybind11/numpy.h ADDED
@@ -0,0 +1,1998 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+ #include "complex.h"
14
+
15
+ #include <algorithm>
16
+ #include <array>
17
+ #include <cstdint>
18
+ #include <cstdlib>
19
+ #include <cstring>
20
+ #include <functional>
21
+ #include <numeric>
22
+ #include <sstream>
23
+ #include <string>
24
+ #include <type_traits>
25
+ #include <typeindex>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ /* This will be true on all flat address space platforms and allows us to reduce the
30
+ whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
31
+ and dimension types (e.g. shape, strides, indexing), instead of inflicting this
32
+ upon the library user. */
33
+ static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
34
+ static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
35
+ // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
36
+
37
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
38
+
39
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
40
+
41
+ class array; // Forward declaration
42
+
43
+ PYBIND11_NAMESPACE_BEGIN(detail)
44
+
45
+ template <>
46
+ struct handle_type_name<array> {
47
+ static constexpr auto name = const_name("numpy.ndarray");
48
+ };
49
+
50
+ template <typename type, typename SFINAE = void>
51
+ struct npy_format_descriptor;
52
+
53
+ struct PyArrayDescr_Proxy {
54
+ PyObject_HEAD
55
+ PyObject *typeobj;
56
+ char kind;
57
+ char type;
58
+ char byteorder;
59
+ char flags;
60
+ int type_num;
61
+ int elsize;
62
+ int alignment;
63
+ char *subarray;
64
+ PyObject *fields;
65
+ PyObject *names;
66
+ };
67
+
68
+ struct PyArray_Proxy {
69
+ PyObject_HEAD
70
+ char *data;
71
+ int nd;
72
+ ssize_t *dimensions;
73
+ ssize_t *strides;
74
+ PyObject *base;
75
+ PyObject *descr;
76
+ int flags;
77
+ };
78
+
79
+ struct PyVoidScalarObject_Proxy {
80
+ PyObject_VAR_HEAD char *obval;
81
+ PyArrayDescr_Proxy *descr;
82
+ int flags;
83
+ PyObject *base;
84
+ };
85
+
86
+ struct numpy_type_info {
87
+ PyObject *dtype_ptr;
88
+ std::string format_str;
89
+ };
90
+
91
+ struct numpy_internals {
92
+ std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
93
+
94
+ numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) {
95
+ auto it = registered_dtypes.find(std::type_index(tinfo));
96
+ if (it != registered_dtypes.end()) {
97
+ return &(it->second);
98
+ }
99
+ if (throw_if_missing) {
100
+ pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
101
+ }
102
+ return nullptr;
103
+ }
104
+
105
+ template <typename T>
106
+ numpy_type_info *get_type_info(bool throw_if_missing = true) {
107
+ return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
108
+ }
109
+ };
110
+
111
+ PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr) {
112
+ ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
113
+ }
114
+
115
+ inline numpy_internals &get_numpy_internals() {
116
+ static numpy_internals *ptr = nullptr;
117
+ if (!ptr) {
118
+ load_numpy_internals(ptr);
119
+ }
120
+ return *ptr;
121
+ }
122
+
123
+ template <typename T>
124
+ struct same_size {
125
+ template <typename U>
126
+ using as = bool_constant<sizeof(T) == sizeof(U)>;
127
+ };
128
+
129
+ template <typename Concrete>
130
+ constexpr int platform_lookup() {
131
+ return -1;
132
+ }
133
+
134
+ // Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
135
+ template <typename Concrete, typename T, typename... Ts, typename... Ints>
136
+ constexpr int platform_lookup(int I, Ints... Is) {
137
+ return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
138
+ }
139
+
140
+ struct npy_api {
141
+ enum constants {
142
+ NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
143
+ NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,
144
+ NPY_ARRAY_OWNDATA_ = 0x0004,
145
+ NPY_ARRAY_FORCECAST_ = 0x0010,
146
+ NPY_ARRAY_ENSUREARRAY_ = 0x0040,
147
+ NPY_ARRAY_ALIGNED_ = 0x0100,
148
+ NPY_ARRAY_WRITEABLE_ = 0x0400,
149
+ NPY_BOOL_ = 0,
150
+ NPY_BYTE_,
151
+ NPY_UBYTE_,
152
+ NPY_SHORT_,
153
+ NPY_USHORT_,
154
+ NPY_INT_,
155
+ NPY_UINT_,
156
+ NPY_LONG_,
157
+ NPY_ULONG_,
158
+ NPY_LONGLONG_,
159
+ NPY_ULONGLONG_,
160
+ NPY_FLOAT_,
161
+ NPY_DOUBLE_,
162
+ NPY_LONGDOUBLE_,
163
+ NPY_CFLOAT_,
164
+ NPY_CDOUBLE_,
165
+ NPY_CLONGDOUBLE_,
166
+ NPY_OBJECT_ = 17,
167
+ NPY_STRING_,
168
+ NPY_UNICODE_,
169
+ NPY_VOID_,
170
+ // Platform-dependent normalization
171
+ NPY_INT8_ = NPY_BYTE_,
172
+ NPY_UINT8_ = NPY_UBYTE_,
173
+ NPY_INT16_ = NPY_SHORT_,
174
+ NPY_UINT16_ = NPY_USHORT_,
175
+ // `npy_common.h` defines the integer aliases. In order, it checks:
176
+ // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
177
+ // and assigns the alias to the first matching size, so we should check in this order.
178
+ NPY_INT32_
179
+ = platform_lookup<std::int32_t, long, int, short>(NPY_LONG_, NPY_INT_, NPY_SHORT_),
180
+ NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
181
+ NPY_ULONG_, NPY_UINT_, NPY_USHORT_),
182
+ NPY_INT64_
183
+ = platform_lookup<std::int64_t, long, long long, int>(NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
184
+ NPY_UINT64_
185
+ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
186
+ NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),
187
+ };
188
+
189
+ struct PyArray_Dims {
190
+ Py_intptr_t *ptr;
191
+ int len;
192
+ };
193
+
194
+ static npy_api &get() {
195
+ static npy_api api = lookup();
196
+ return api;
197
+ }
198
+
199
+ bool PyArray_Check_(PyObject *obj) const {
200
+ return PyObject_TypeCheck(obj, PyArray_Type_) != 0;
201
+ }
202
+ bool PyArrayDescr_Check_(PyObject *obj) const {
203
+ return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0;
204
+ }
205
+
206
+ unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
207
+ PyObject *(*PyArray_DescrFromType_)(int);
208
+ PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,
209
+ PyObject *,
210
+ int,
211
+ Py_intptr_t const *,
212
+ Py_intptr_t const *,
213
+ void *,
214
+ int,
215
+ PyObject *);
216
+ // Unused. Not removed because that affects ABI of the class.
217
+ PyObject *(*PyArray_DescrNewFromType_)(int);
218
+ int (*PyArray_CopyInto_)(PyObject *, PyObject *);
219
+ PyObject *(*PyArray_NewCopy_)(PyObject *, int);
220
+ PyTypeObject *PyArray_Type_;
221
+ PyTypeObject *PyVoidArrType_Type_;
222
+ PyTypeObject *PyArrayDescr_Type_;
223
+ PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
224
+ PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *);
225
+ int (*PyArray_DescrConverter_)(PyObject *, PyObject **);
226
+ bool (*PyArray_EquivTypes_)(PyObject *, PyObject *);
227
+ int (*PyArray_GetArrayParamsFromObject_)(PyObject *,
228
+ PyObject *,
229
+ unsigned char,
230
+ PyObject **,
231
+ int *,
232
+ Py_intptr_t *,
233
+ PyObject **,
234
+ PyObject *);
235
+ PyObject *(*PyArray_Squeeze_)(PyObject *);
236
+ // Unused. Not removed because that affects ABI of the class.
237
+ int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
238
+ PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int);
239
+ PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int);
240
+ PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);
241
+
242
+ private:
243
+ enum functions {
244
+ API_PyArray_GetNDArrayCFeatureVersion = 211,
245
+ API_PyArray_Type = 2,
246
+ API_PyArrayDescr_Type = 3,
247
+ API_PyVoidArrType_Type = 39,
248
+ API_PyArray_DescrFromType = 45,
249
+ API_PyArray_DescrFromScalar = 57,
250
+ API_PyArray_FromAny = 69,
251
+ API_PyArray_Resize = 80,
252
+ API_PyArray_CopyInto = 82,
253
+ API_PyArray_NewCopy = 85,
254
+ API_PyArray_NewFromDescr = 94,
255
+ API_PyArray_DescrNewFromType = 96,
256
+ API_PyArray_Newshape = 135,
257
+ API_PyArray_Squeeze = 136,
258
+ API_PyArray_View = 137,
259
+ API_PyArray_DescrConverter = 174,
260
+ API_PyArray_EquivTypes = 182,
261
+ API_PyArray_GetArrayParamsFromObject = 278,
262
+ API_PyArray_SetBaseObject = 282
263
+ };
264
+
265
+ static npy_api lookup() {
266
+ module_ m = module_::import("numpy.core.multiarray");
267
+ auto c = m.attr("_ARRAY_API");
268
+ void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), nullptr);
269
+ npy_api api;
270
+ #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
271
+ DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
272
+ if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7) {
273
+ pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
274
+ }
275
+ DECL_NPY_API(PyArray_Type);
276
+ DECL_NPY_API(PyVoidArrType_Type);
277
+ DECL_NPY_API(PyArrayDescr_Type);
278
+ DECL_NPY_API(PyArray_DescrFromType);
279
+ DECL_NPY_API(PyArray_DescrFromScalar);
280
+ DECL_NPY_API(PyArray_FromAny);
281
+ DECL_NPY_API(PyArray_Resize);
282
+ DECL_NPY_API(PyArray_CopyInto);
283
+ DECL_NPY_API(PyArray_NewCopy);
284
+ DECL_NPY_API(PyArray_NewFromDescr);
285
+ DECL_NPY_API(PyArray_DescrNewFromType);
286
+ DECL_NPY_API(PyArray_Newshape);
287
+ DECL_NPY_API(PyArray_Squeeze);
288
+ DECL_NPY_API(PyArray_View);
289
+ DECL_NPY_API(PyArray_DescrConverter);
290
+ DECL_NPY_API(PyArray_EquivTypes);
291
+ DECL_NPY_API(PyArray_GetArrayParamsFromObject);
292
+ DECL_NPY_API(PyArray_SetBaseObject);
293
+
294
+ #undef DECL_NPY_API
295
+ return api;
296
+ }
297
+ };
298
+
299
+ inline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast<PyArray_Proxy *>(ptr); }
300
+
301
+ inline const PyArray_Proxy *array_proxy(const void *ptr) {
302
+ return reinterpret_cast<const PyArray_Proxy *>(ptr);
303
+ }
304
+
305
+ inline PyArrayDescr_Proxy *array_descriptor_proxy(PyObject *ptr) {
306
+ return reinterpret_cast<PyArrayDescr_Proxy *>(ptr);
307
+ }
308
+
309
+ inline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) {
310
+ return reinterpret_cast<const PyArrayDescr_Proxy *>(ptr);
311
+ }
312
+
313
+ inline bool check_flags(const void *ptr, int flag) {
314
+ return (flag == (array_proxy(ptr)->flags & flag));
315
+ }
316
+
317
+ template <typename T>
318
+ struct is_std_array : std::false_type {};
319
+ template <typename T, size_t N>
320
+ struct is_std_array<std::array<T, N>> : std::true_type {};
321
+ template <typename T>
322
+ struct is_complex : std::false_type {};
323
+ template <typename T>
324
+ struct is_complex<std::complex<T>> : std::true_type {};
325
+
326
+ template <typename T>
327
+ struct array_info_scalar {
328
+ using type = T;
329
+ static constexpr bool is_array = false;
330
+ static constexpr bool is_empty = false;
331
+ static constexpr auto extents = const_name("");
332
+ static void append_extents(list & /* shape */) {}
333
+ };
334
+ // Computes underlying type and a comma-separated list of extents for array
335
+ // types (any mix of std::array and built-in arrays). An array of char is
336
+ // treated as scalar because it gets special handling.
337
+ template <typename T>
338
+ struct array_info : array_info_scalar<T> {};
339
+ template <typename T, size_t N>
340
+ struct array_info<std::array<T, N>> {
341
+ using type = typename array_info<T>::type;
342
+ static constexpr bool is_array = true;
343
+ static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
344
+ static constexpr size_t extent = N;
345
+
346
+ // appends the extents to shape
347
+ static void append_extents(list &shape) {
348
+ shape.append(N);
349
+ array_info<T>::append_extents(shape);
350
+ }
351
+
352
+ static constexpr auto extents = const_name<array_info<T>::is_array>(
353
+ concat(const_name<N>(), array_info<T>::extents), const_name<N>());
354
+ };
355
+ // For numpy we have special handling for arrays of characters, so we don't include
356
+ // the size in the array extents.
357
+ template <size_t N>
358
+ struct array_info<char[N]> : array_info_scalar<char[N]> {};
359
+ template <size_t N>
360
+ struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> {};
361
+ template <typename T, size_t N>
362
+ struct array_info<T[N]> : array_info<std::array<T, N>> {};
363
+ template <typename T>
364
+ using remove_all_extents_t = typename array_info<T>::type;
365
+
366
+ template <typename T>
367
+ using is_pod_struct
368
+ = all_of<std::is_standard_layout<T>, // since we're accessing directly in memory
369
+ // we need a standard layout type
370
+ #if defined(__GLIBCXX__) \
371
+ && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \
372
+ || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
373
+ // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after
374
+ // 5) don't implement is_trivially_copyable, so approximate it
375
+ std::is_trivially_destructible<T>,
376
+ satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
377
+ #else
378
+ std::is_trivially_copyable<T>,
379
+ #endif
380
+ satisfies_none_of<T,
381
+ std::is_reference,
382
+ std::is_array,
383
+ is_std_array,
384
+ std::is_arithmetic,
385
+ is_complex,
386
+ std::is_enum>>;
387
+
388
+ // Replacement for std::is_pod (deprecated in C++20)
389
+ template <typename T>
390
+ using is_pod = all_of<std::is_standard_layout<T>, std::is_trivial<T>>;
391
+
392
+ template <ssize_t Dim = 0, typename Strides>
393
+ ssize_t byte_offset_unsafe(const Strides &) {
394
+ return 0;
395
+ }
396
+ template <ssize_t Dim = 0, typename Strides, typename... Ix>
397
+ ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
398
+ return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
399
+ }
400
+
401
+ /**
402
+ * Proxy class providing unsafe, unchecked const access to array data. This is constructed through
403
+ * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
404
+ * will be -1 for dimensions determined at runtime.
405
+ */
406
+ template <typename T, ssize_t Dims>
407
+ class unchecked_reference {
408
+ protected:
409
+ static constexpr bool Dynamic = Dims < 0;
410
+ const unsigned char *data_;
411
+ // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
412
+ // make large performance gains on big, nested loops, but requires compile-time dimensions
413
+ conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_;
414
+ const ssize_t dims_;
415
+
416
+ friend class pybind11::array;
417
+ // Constructor for compile-time dimensions:
418
+ template <bool Dyn = Dynamic>
419
+ unchecked_reference(const void *data,
420
+ const ssize_t *shape,
421
+ const ssize_t *strides,
422
+ enable_if_t<!Dyn, ssize_t>)
423
+ : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
424
+ for (size_t i = 0; i < (size_t) dims_; i++) {
425
+ shape_[i] = shape[i];
426
+ strides_[i] = strides[i];
427
+ }
428
+ }
429
+ // Constructor for runtime dimensions:
430
+ template <bool Dyn = Dynamic>
431
+ unchecked_reference(const void *data,
432
+ const ssize_t *shape,
433
+ const ssize_t *strides,
434
+ enable_if_t<Dyn, ssize_t> dims)
435
+ : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},
436
+ dims_{dims} {}
437
+
438
+ public:
439
+ /**
440
+ * Unchecked const reference access to data at the given indices. For a compile-time known
441
+ * number of dimensions, this requires the correct number of arguments; for run-time
442
+ * dimensionality, this is not checked (and so is up to the caller to use safely).
443
+ */
444
+ template <typename... Ix>
445
+ const T &operator()(Ix... index) const {
446
+ static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
447
+ "Invalid number of indices for unchecked array reference");
448
+ return *reinterpret_cast<const T *>(data_
449
+ + byte_offset_unsafe(strides_, ssize_t(index)...));
450
+ }
451
+ /**
452
+ * Unchecked const reference access to data; this operator only participates if the reference
453
+ * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
454
+ */
455
+ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
456
+ const T &operator[](ssize_t index) const {
457
+ return operator()(index);
458
+ }
459
+
460
+ /// Pointer access to the data at the given indices.
461
+ template <typename... Ix>
462
+ const T *data(Ix... ix) const {
463
+ return &operator()(ssize_t(ix)...);
464
+ }
465
+
466
+ /// Returns the item size, i.e. sizeof(T)
467
+ constexpr static ssize_t itemsize() { return sizeof(T); }
468
+
469
+ /// Returns the shape (i.e. size) of dimension `dim`
470
+ ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
471
+
472
+ /// Returns the number of dimensions of the array
473
+ ssize_t ndim() const { return dims_; }
474
+
475
+ /// Returns the total number of elements in the referenced array, i.e. the product of the
476
+ /// shapes
477
+ template <bool Dyn = Dynamic>
478
+ enable_if_t<!Dyn, ssize_t> size() const {
479
+ return std::accumulate(
480
+ shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
481
+ }
482
+ template <bool Dyn = Dynamic>
483
+ enable_if_t<Dyn, ssize_t> size() const {
484
+ return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
485
+ }
486
+
487
+ /// Returns the total number of bytes used by the referenced data. Note that the actual span
488
+ /// in memory may be larger if the referenced array has non-contiguous strides (e.g. for a
489
+ /// slice).
490
+ ssize_t nbytes() const { return size() * itemsize(); }
491
+ };
492
+
493
+ template <typename T, ssize_t Dims>
494
+ class unchecked_mutable_reference : public unchecked_reference<T, Dims> {
495
+ friend class pybind11::array;
496
+ using ConstBase = unchecked_reference<T, Dims>;
497
+ using ConstBase::ConstBase;
498
+ using ConstBase::Dynamic;
499
+
500
+ public:
501
+ // Bring in const-qualified versions from base class
502
+ using ConstBase::operator();
503
+ using ConstBase::operator[];
504
+
505
+ /// Mutable, unchecked access to data at the given indices.
506
+ template <typename... Ix>
507
+ T &operator()(Ix... index) {
508
+ static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
509
+ "Invalid number of indices for unchecked array reference");
510
+ return const_cast<T &>(ConstBase::operator()(index...));
511
+ }
512
+ /**
513
+ * Mutable, unchecked access data at the given index; this operator only participates if the
514
+ * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is
515
+ * exactly equivalent to `obj(index)`.
516
+ */
517
+ template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
518
+ T &operator[](ssize_t index) {
519
+ return operator()(index);
520
+ }
521
+
522
+ /// Mutable pointer access to the data at the given indices.
523
+ template <typename... Ix>
524
+ T *mutable_data(Ix... ix) {
525
+ return &operator()(ssize_t(ix)...);
526
+ }
527
+ };
528
+
529
+ template <typename T, ssize_t Dim>
530
+ struct type_caster<unchecked_reference<T, Dim>> {
531
+ static_assert(Dim == 0 && Dim > 0 /* always fail */,
532
+ "unchecked array proxy object is not castable");
533
+ };
534
+ template <typename T, ssize_t Dim>
535
+ struct type_caster<unchecked_mutable_reference<T, Dim>>
536
+ : type_caster<unchecked_reference<T, Dim>> {};
537
+
538
+ PYBIND11_NAMESPACE_END(detail)
539
+
540
+ class dtype : public object {
541
+ public:
542
+ PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_)
543
+
544
+ explicit dtype(const buffer_info &info) {
545
+ dtype descr(_dtype_from_pep3118()(pybind11::str(info.format)));
546
+ // If info.itemsize == 0, use the value calculated from the format string
547
+ m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize())
548
+ .release()
549
+ .ptr();
550
+ }
551
+
552
+ explicit dtype(const pybind11::str &format) : dtype(from_args(format)) {}
553
+
554
+ explicit dtype(const std::string &format) : dtype(pybind11::str(format)) {}
555
+
556
+ explicit dtype(const char *format) : dtype(pybind11::str(format)) {}
557
+
558
+ dtype(list names, list formats, list offsets, ssize_t itemsize) {
559
+ dict args;
560
+ args["names"] = std::move(names);
561
+ args["formats"] = std::move(formats);
562
+ args["offsets"] = std::move(offsets);
563
+ args["itemsize"] = pybind11::int_(itemsize);
564
+ m_ptr = from_args(args).release().ptr();
565
+ }
566
+
567
+ /// Return dtype for the given typenum (one of the NPY_TYPES).
568
+ /// https://numpy.org/devdocs/reference/c-api/array.html#c.PyArray_DescrFromType
569
+ explicit dtype(int typenum)
570
+ : object(detail::npy_api::get().PyArray_DescrFromType_(typenum), stolen_t{}) {
571
+ if (m_ptr == nullptr) {
572
+ throw error_already_set();
573
+ }
574
+ }
575
+
576
+ /// This is essentially the same as calling numpy.dtype(args) in Python.
577
+ static dtype from_args(const object &args) {
578
+ PyObject *ptr = nullptr;
579
+ if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) {
580
+ throw error_already_set();
581
+ }
582
+ return reinterpret_steal<dtype>(ptr);
583
+ }
584
+
585
+ /// Return dtype associated with a C++ type.
586
+ template <typename T>
587
+ static dtype of() {
588
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
589
+ }
590
+
591
+ /// Size of the data type in bytes.
592
+ ssize_t itemsize() const { return detail::array_descriptor_proxy(m_ptr)->elsize; }
593
+
594
+ /// Returns true for structured data types.
595
+ bool has_fields() const { return detail::array_descriptor_proxy(m_ptr)->names != nullptr; }
596
+
597
+ /// Single-character code for dtype's kind.
598
+ /// For example, floating point types are 'f' and integral types are 'i'.
599
+ char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; }
600
+
601
+ /// Single-character for dtype's type.
602
+ /// For example, ``float`` is 'f', ``double`` 'd', ``int`` 'i', and ``long`` 'l'.
603
+ char char_() const {
604
+ // Note: The signature, `dtype::char_` follows the naming of NumPy's
605
+ // public Python API (i.e., ``dtype.char``), rather than its internal
606
+ // C API (``PyArray_Descr::type``).
607
+ return detail::array_descriptor_proxy(m_ptr)->type;
608
+ }
609
+
610
+ /// type number of dtype.
611
+ int num() const {
612
+ // Note: The signature, `dtype::num` follows the naming of NumPy's public
613
+ // Python API (i.e., ``dtype.num``), rather than its internal
614
+ // C API (``PyArray_Descr::type_num``).
615
+ return detail::array_descriptor_proxy(m_ptr)->type_num;
616
+ }
617
+
618
+ /// Single character for byteorder
619
+ char byteorder() const { return detail::array_descriptor_proxy(m_ptr)->byteorder; }
620
+
621
+ /// Alignment of the data type
622
+ int alignment() const { return detail::array_descriptor_proxy(m_ptr)->alignment; }
623
+
624
+ /// Flags for the array descriptor
625
+ char flags() const { return detail::array_descriptor_proxy(m_ptr)->flags; }
626
+
627
+ private:
628
+ static object _dtype_from_pep3118() {
629
+ static PyObject *obj = module_::import("numpy.core._internal")
630
+ .attr("_dtype_from_pep3118")
631
+ .cast<object>()
632
+ .release()
633
+ .ptr();
634
+ return reinterpret_borrow<object>(obj);
635
+ }
636
+
637
+ dtype strip_padding(ssize_t itemsize) {
638
+ // Recursively strip all void fields with empty names that are generated for
639
+ // padding fields (as of NumPy v1.11).
640
+ if (!has_fields()) {
641
+ return *this;
642
+ }
643
+
644
+ struct field_descr {
645
+ pybind11::str name;
646
+ object format;
647
+ pybind11::int_ offset;
648
+ field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset)
649
+ : name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {};
650
+ };
651
+ auto field_dict = attr("fields").cast<dict>();
652
+ std::vector<field_descr> field_descriptors;
653
+ field_descriptors.reserve(field_dict.size());
654
+
655
+ for (auto field : field_dict.attr("items")()) {
656
+ auto spec = field.cast<tuple>();
657
+ auto name = spec[0].cast<pybind11::str>();
658
+ auto spec_fo = spec[1].cast<tuple>();
659
+ auto format = spec_fo[0].cast<dtype>();
660
+ auto offset = spec_fo[1].cast<pybind11::int_>();
661
+ if ((len(name) == 0u) && format.kind() == 'V') {
662
+ continue;
663
+ }
664
+ field_descriptors.emplace_back(
665
+ std::move(name), format.strip_padding(format.itemsize()), std::move(offset));
666
+ }
667
+
668
+ std::sort(field_descriptors.begin(),
669
+ field_descriptors.end(),
670
+ [](const field_descr &a, const field_descr &b) {
671
+ return a.offset.cast<int>() < b.offset.cast<int>();
672
+ });
673
+
674
+ list names, formats, offsets;
675
+ for (auto &descr : field_descriptors) {
676
+ names.append(std::move(descr.name));
677
+ formats.append(std::move(descr.format));
678
+ offsets.append(std::move(descr.offset));
679
+ }
680
+ return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize);
681
+ }
682
+ };
683
+
684
+ class array : public buffer {
685
+ public:
686
+ PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
687
+
688
+ enum {
689
+ c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
690
+ f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
691
+ forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
692
+ };
693
+
694
+ array() : array(0, static_cast<const double *>(nullptr)) {}
695
+
696
+ using ShapeContainer = detail::any_container<ssize_t>;
697
+ using StridesContainer = detail::any_container<ssize_t>;
698
+
699
+ // Constructs an array taking shape/strides from arbitrary container types
700
+ array(const pybind11::dtype &dt,
701
+ ShapeContainer shape,
702
+ StridesContainer strides,
703
+ const void *ptr = nullptr,
704
+ handle base = handle()) {
705
+
706
+ if (strides->empty()) {
707
+ *strides = detail::c_strides(*shape, dt.itemsize());
708
+ }
709
+
710
+ auto ndim = shape->size();
711
+ if (ndim != strides->size()) {
712
+ pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
713
+ }
714
+ auto descr = dt;
715
+
716
+ int flags = 0;
717
+ if (base && ptr) {
718
+ if (isinstance<array>(base)) {
719
+ /* Copy flags from base (except ownership bit) */
720
+ flags = reinterpret_borrow<array>(base).flags()
721
+ & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
722
+ } else {
723
+ /* Writable by default, easy to downgrade later on if needed */
724
+ flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
725
+ }
726
+ }
727
+
728
+ auto &api = detail::npy_api::get();
729
+ auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
730
+ api.PyArray_Type_,
731
+ descr.release().ptr(),
732
+ (int) ndim,
733
+ // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
734
+ reinterpret_cast<Py_intptr_t *>(shape->data()),
735
+ reinterpret_cast<Py_intptr_t *>(strides->data()),
736
+ const_cast<void *>(ptr),
737
+ flags,
738
+ nullptr));
739
+ if (!tmp) {
740
+ throw error_already_set();
741
+ }
742
+ if (ptr) {
743
+ if (base) {
744
+ api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
745
+ } else {
746
+ tmp = reinterpret_steal<object>(
747
+ api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
748
+ }
749
+ }
750
+ m_ptr = tmp.release().ptr();
751
+ }
752
+
753
+ array(const pybind11::dtype &dt,
754
+ ShapeContainer shape,
755
+ const void *ptr = nullptr,
756
+ handle base = handle())
757
+ : array(dt, std::move(shape), {}, ptr, base) {}
758
+
759
+ template <typename T,
760
+ typename
761
+ = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
762
+ array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
763
+ : array(dt, {{count}}, ptr, base) {}
764
+
765
+ template <typename T>
766
+ array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
767
+ : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) {}
768
+
769
+ template <typename T>
770
+ array(ShapeContainer shape, const T *ptr, handle base = handle())
771
+ : array(std::move(shape), {}, ptr, base) {}
772
+
773
+ template <typename T>
774
+ explicit array(ssize_t count, const T *ptr, handle base = handle())
775
+ : array({count}, {}, ptr, base) {}
776
+
777
+ explicit array(const buffer_info &info, handle base = handle())
778
+ : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) {}
779
+
780
+ /// Array descriptor (dtype)
781
+ pybind11::dtype dtype() const {
782
+ return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
783
+ }
784
+
785
+ /// Total number of elements
786
+ ssize_t size() const {
787
+ return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
788
+ }
789
+
790
+ /// Byte size of a single element
791
+ ssize_t itemsize() const {
792
+ return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize;
793
+ }
794
+
795
+ /// Total number of bytes
796
+ ssize_t nbytes() const { return size() * itemsize(); }
797
+
798
+ /// Number of dimensions
799
+ ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }
800
+
801
+ /// Base object
802
+ object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }
803
+
804
+ /// Dimensions of the array
805
+ const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }
806
+
807
+ /// Dimension along a given axis
808
+ ssize_t shape(ssize_t dim) const {
809
+ if (dim >= ndim()) {
810
+ fail_dim_check(dim, "invalid axis");
811
+ }
812
+ return shape()[dim];
813
+ }
814
+
815
+ /// Strides of the array
816
+ const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }
817
+
818
+ /// Stride along a given axis
819
+ ssize_t strides(ssize_t dim) const {
820
+ if (dim >= ndim()) {
821
+ fail_dim_check(dim, "invalid axis");
822
+ }
823
+ return strides()[dim];
824
+ }
825
+
826
+ /// Return the NumPy array flags
827
+ int flags() const { return detail::array_proxy(m_ptr)->flags; }
828
+
829
+ /// If set, the array is writeable (otherwise the buffer is read-only)
830
+ bool writeable() const {
831
+ return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
832
+ }
833
+
834
+ /// If set, the array owns the data (will be freed when the array is deleted)
835
+ bool owndata() const {
836
+ return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
837
+ }
838
+
839
+ /// Pointer to the contained data. If index is not provided, points to the
840
+ /// beginning of the buffer. May throw if the index would lead to out of bounds access.
841
+ template <typename... Ix>
842
+ const void *data(Ix... index) const {
843
+ return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
844
+ }
845
+
846
+ /// Mutable pointer to the contained data. If index is not provided, points to the
847
+ /// beginning of the buffer. May throw if the index would lead to out of bounds access.
848
+ /// May throw if the array is not writeable.
849
+ template <typename... Ix>
850
+ void *mutable_data(Ix... index) {
851
+ check_writeable();
852
+ return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
853
+ }
854
+
855
+ /// Byte offset from beginning of the array to a given index (full or partial).
856
+ /// May throw if the index would lead to out of bounds access.
857
+ template <typename... Ix>
858
+ ssize_t offset_at(Ix... index) const {
859
+ if ((ssize_t) sizeof...(index) > ndim()) {
860
+ fail_dim_check(sizeof...(index), "too many indices for an array");
861
+ }
862
+ return byte_offset(ssize_t(index)...);
863
+ }
864
+
865
+ ssize_t offset_at() const { return 0; }
866
+
867
+ /// Item count from beginning of the array to a given index (full or partial).
868
+ /// May throw if the index would lead to out of bounds access.
869
+ template <typename... Ix>
870
+ ssize_t index_at(Ix... index) const {
871
+ return offset_at(index...) / itemsize();
872
+ }
873
+
874
+ /**
875
+ * Returns a proxy object that provides access to the array's data without bounds or
876
+ * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
877
+ * care: the array must not be destroyed or reshaped for the duration of the returned object,
878
+ * and the caller must take care not to access invalid dimensions or dimension indices.
879
+ */
880
+ template <typename T, ssize_t Dims = -1>
881
+ detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
882
+ if (Dims >= 0 && ndim() != Dims) {
883
+ throw std::domain_error("array has incorrect number of dimensions: "
884
+ + std::to_string(ndim()) + "; expected "
885
+ + std::to_string(Dims));
886
+ }
887
+ return detail::unchecked_mutable_reference<T, Dims>(
888
+ mutable_data(), shape(), strides(), ndim());
889
+ }
890
+
891
+ /**
892
+ * Returns a proxy object that provides const access to the array's data without bounds or
893
+ * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
894
+ * underlying array have the `writable` flag. Use with care: the array must not be destroyed
895
+ * or reshaped for the duration of the returned object, and the caller must take care not to
896
+ * access invalid dimensions or dimension indices.
897
+ */
898
+ template <typename T, ssize_t Dims = -1>
899
+ detail::unchecked_reference<T, Dims> unchecked() const & {
900
+ if (Dims >= 0 && ndim() != Dims) {
901
+ throw std::domain_error("array has incorrect number of dimensions: "
902
+ + std::to_string(ndim()) + "; expected "
903
+ + std::to_string(Dims));
904
+ }
905
+ return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
906
+ }
907
+
908
+ /// Return a new view with all of the dimensions of length 1 removed
909
+ array squeeze() {
910
+ auto &api = detail::npy_api::get();
911
+ return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
912
+ }
913
+
914
+ /// Resize array to given shape
915
+ /// If refcheck is true and more that one reference exist to this array
916
+ /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
917
+ void resize(ShapeContainer new_shape, bool refcheck = true) {
918
+ detail::npy_api::PyArray_Dims d
919
+ = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
920
+ reinterpret_cast<Py_intptr_t *>(new_shape->data()),
921
+ int(new_shape->size())};
922
+ // try to resize, set ordering param to -1 cause it's not used anyway
923
+ auto new_array = reinterpret_steal<object>(
924
+ detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));
925
+ if (!new_array) {
926
+ throw error_already_set();
927
+ }
928
+ if (isinstance<array>(new_array)) {
929
+ *this = std::move(new_array);
930
+ }
931
+ }
932
+
933
+ /// Optional `order` parameter omitted, to be added as needed.
934
+ array reshape(ShapeContainer new_shape) {
935
+ detail::npy_api::PyArray_Dims d
936
+ = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};
937
+ auto new_array
938
+ = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));
939
+ if (!new_array) {
940
+ throw error_already_set();
941
+ }
942
+ return new_array;
943
+ }
944
+
945
+ /// Create a view of an array in a different data type.
946
+ /// This function may fundamentally reinterpret the data in the array.
947
+ /// It is the responsibility of the caller to ensure that this is safe.
948
+ /// Only supports the `dtype` argument, the `type` argument is omitted,
949
+ /// to be added as needed.
950
+ array view(const std::string &dtype) {
951
+ auto &api = detail::npy_api::get();
952
+ auto new_view = reinterpret_steal<array>(api.PyArray_View_(
953
+ m_ptr, dtype::from_args(pybind11::str(dtype)).release().ptr(), nullptr));
954
+ if (!new_view) {
955
+ throw error_already_set();
956
+ }
957
+ return new_view;
958
+ }
959
+
960
+ /// Ensure that the argument is a NumPy array
961
+ /// In case of an error, nullptr is returned and the Python error is cleared.
962
+ static array ensure(handle h, int ExtraFlags = 0) {
963
+ auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
964
+ if (!result) {
965
+ PyErr_Clear();
966
+ }
967
+ return result;
968
+ }
969
+
970
+ protected:
971
+ template <typename, typename>
972
+ friend struct detail::npy_format_descriptor;
973
+
974
+ void fail_dim_check(ssize_t dim, const std::string &msg) const {
975
+ throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim())
976
+ + ')');
977
+ }
978
+
979
+ template <typename... Ix>
980
+ ssize_t byte_offset(Ix... index) const {
981
+ check_dimensions(index...);
982
+ return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
983
+ }
984
+
985
+ void check_writeable() const {
986
+ if (!writeable()) {
987
+ throw std::domain_error("array is not writeable");
988
+ }
989
+ }
990
+
991
+ template <typename... Ix>
992
+ void check_dimensions(Ix... index) const {
993
+ check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
994
+ }
995
+
996
+ void check_dimensions_impl(ssize_t, const ssize_t *) const {}
997
+
998
+ template <typename... Ix>
999
+ void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
1000
+ if (i >= *shape) {
1001
+ throw index_error(std::string("index ") + std::to_string(i)
1002
+ + " is out of bounds for axis " + std::to_string(axis)
1003
+ + " with size " + std::to_string(*shape));
1004
+ }
1005
+ check_dimensions_impl(axis + 1, shape + 1, index...);
1006
+ }
1007
+
1008
+ /// Create array from any object -- always returns a new reference
1009
+ static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
1010
+ if (ptr == nullptr) {
1011
+ PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
1012
+ return nullptr;
1013
+ }
1014
+ return detail::npy_api::get().PyArray_FromAny_(
1015
+ ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
1016
+ }
1017
+ };
1018
+
1019
+ template <typename T, int ExtraFlags = array::forcecast>
1020
+ class array_t : public array {
1021
+ private:
1022
+ struct private_ctor {};
1023
+ // Delegating constructor needed when both moving and accessing in the same constructor
1024
+ array_t(private_ctor,
1025
+ ShapeContainer &&shape,
1026
+ StridesContainer &&strides,
1027
+ const T *ptr,
1028
+ handle base)
1029
+ : array(std::move(shape), std::move(strides), ptr, base) {}
1030
+
1031
+ public:
1032
+ static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
1033
+
1034
+ using value_type = T;
1035
+
1036
+ array_t() : array(0, static_cast<const T *>(nullptr)) {}
1037
+ array_t(handle h, borrowed_t) : array(h, borrowed_t{}) {}
1038
+ array_t(handle h, stolen_t) : array(h, stolen_t{}) {}
1039
+
1040
+ PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
1041
+ array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
1042
+ if (!m_ptr) {
1043
+ PyErr_Clear();
1044
+ }
1045
+ if (!is_borrowed) {
1046
+ Py_XDECREF(h.ptr());
1047
+ }
1048
+ }
1049
+
1050
+ // NOLINTNEXTLINE(google-explicit-constructor)
1051
+ array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
1052
+ if (!m_ptr) {
1053
+ throw error_already_set();
1054
+ }
1055
+ }
1056
+
1057
+ explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}
1058
+
1059
+ array_t(ShapeContainer shape,
1060
+ StridesContainer strides,
1061
+ const T *ptr = nullptr,
1062
+ handle base = handle())
1063
+ : array(std::move(shape), std::move(strides), ptr, base) {}
1064
+
1065
+ explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
1066
+ : array_t(private_ctor{},
1067
+ std::move(shape),
1068
+ (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())
1069
+ : detail::c_strides(*shape, itemsize()),
1070
+ ptr,
1071
+ base) {}
1072
+
1073
+ explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
1074
+ : array({count}, {}, ptr, base) {}
1075
+
1076
+ constexpr ssize_t itemsize() const { return sizeof(T); }
1077
+
1078
+ template <typename... Ix>
1079
+ ssize_t index_at(Ix... index) const {
1080
+ return offset_at(index...) / itemsize();
1081
+ }
1082
+
1083
+ template <typename... Ix>
1084
+ const T *data(Ix... index) const {
1085
+ return static_cast<const T *>(array::data(index...));
1086
+ }
1087
+
1088
+ template <typename... Ix>
1089
+ T *mutable_data(Ix... index) {
1090
+ return static_cast<T *>(array::mutable_data(index...));
1091
+ }
1092
+
1093
+ // Reference to element at a given index
1094
+ template <typename... Ix>
1095
+ const T &at(Ix... index) const {
1096
+ if ((ssize_t) sizeof...(index) != ndim()) {
1097
+ fail_dim_check(sizeof...(index), "index dimension mismatch");
1098
+ }
1099
+ return *(static_cast<const T *>(array::data())
1100
+ + byte_offset(ssize_t(index)...) / itemsize());
1101
+ }
1102
+
1103
+ // Mutable reference to element at a given index
1104
+ template <typename... Ix>
1105
+ T &mutable_at(Ix... index) {
1106
+ if ((ssize_t) sizeof...(index) != ndim()) {
1107
+ fail_dim_check(sizeof...(index), "index dimension mismatch");
1108
+ }
1109
+ return *(static_cast<T *>(array::mutable_data())
1110
+ + byte_offset(ssize_t(index)...) / itemsize());
1111
+ }
1112
+
1113
+ /**
1114
+ * Returns a proxy object that provides access to the array's data without bounds or
1115
+ * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
1116
+ * care: the array must not be destroyed or reshaped for the duration of the returned object,
1117
+ * and the caller must take care not to access invalid dimensions or dimension indices.
1118
+ */
1119
+ template <ssize_t Dims = -1>
1120
+ detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1121
+ return array::mutable_unchecked<T, Dims>();
1122
+ }
1123
+
1124
+ /**
1125
+ * Returns a proxy object that provides const access to the array's data without bounds or
1126
+ * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
1127
+ * underlying array have the `writable` flag. Use with care: the array must not be destroyed
1128
+ * or reshaped for the duration of the returned object, and the caller must take care not to
1129
+ * access invalid dimensions or dimension indices.
1130
+ */
1131
+ template <ssize_t Dims = -1>
1132
+ detail::unchecked_reference<T, Dims> unchecked() const & {
1133
+ return array::unchecked<T, Dims>();
1134
+ }
1135
+
1136
+ /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
1137
+ /// it). In case of an error, nullptr is returned and the Python error is cleared.
1138
+ static array_t ensure(handle h) {
1139
+ auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
1140
+ if (!result) {
1141
+ PyErr_Clear();
1142
+ }
1143
+ return result;
1144
+ }
1145
+
1146
+ static bool check_(handle h) {
1147
+ const auto &api = detail::npy_api::get();
1148
+ return api.PyArray_Check_(h.ptr())
1149
+ && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,
1150
+ dtype::of<T>().ptr())
1151
+ && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
1152
+ }
1153
+
1154
+ protected:
1155
+ /// Create array from any object -- always returns a new reference
1156
+ static PyObject *raw_array_t(PyObject *ptr) {
1157
+ if (ptr == nullptr) {
1158
+ PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
1159
+ return nullptr;
1160
+ }
1161
+ return detail::npy_api::get().PyArray_FromAny_(ptr,
1162
+ dtype::of<T>().release().ptr(),
1163
+ 0,
1164
+ 0,
1165
+ detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1166
+ | ExtraFlags,
1167
+ nullptr);
1168
+ }
1169
+ };
1170
+
1171
+ template <typename T>
1172
+ struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1173
+ static std::string format() {
1174
+ return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
1175
+ }
1176
+ };
1177
+
1178
+ template <size_t N>
1179
+ struct format_descriptor<char[N]> {
1180
+ static std::string format() { return std::to_string(N) + 's'; }
1181
+ };
1182
+ template <size_t N>
1183
+ struct format_descriptor<std::array<char, N>> {
1184
+ static std::string format() { return std::to_string(N) + 's'; }
1185
+ };
1186
+
1187
+ template <typename T>
1188
+ struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
1189
+ static std::string format() {
1190
+ return format_descriptor<
1191
+ typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
1192
+ }
1193
+ };
1194
+
1195
+ template <typename T>
1196
+ struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
1197
+ static std::string format() {
1198
+ using namespace detail;
1199
+ static constexpr auto extents = const_name("(") + array_info<T>::extents + const_name(")");
1200
+ return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
1201
+ }
1202
+ };
1203
+
1204
+ PYBIND11_NAMESPACE_BEGIN(detail)
1205
+ template <typename T, int ExtraFlags>
1206
+ struct pyobject_caster<array_t<T, ExtraFlags>> {
1207
+ using type = array_t<T, ExtraFlags>;
1208
+
1209
+ bool load(handle src, bool convert) {
1210
+ if (!convert && !type::check_(src)) {
1211
+ return false;
1212
+ }
1213
+ value = type::ensure(src);
1214
+ return static_cast<bool>(value);
1215
+ }
1216
+
1217
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1218
+ return src.inc_ref();
1219
+ }
1220
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1221
+ };
1222
+
1223
+ template <typename T>
1224
+ struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1225
+ static bool compare(const buffer_info &b) {
1226
+ return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1227
+ }
1228
+ };
1229
+
1230
+ template <typename T, typename = void>
1231
+ struct npy_format_descriptor_name;
1232
+
1233
+ template <typename T>
1234
+ struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
1235
+ static constexpr auto name = const_name<std::is_same<T, bool>::value>(
1236
+ const_name("bool"),
1237
+ const_name<std::is_signed<T>::value>("numpy.int", "numpy.uint")
1238
+ + const_name<sizeof(T) * 8>());
1239
+ };
1240
+
1241
+ template <typename T>
1242
+ struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
1243
+ static constexpr auto name = const_name < std::is_same<T, float>::value
1244
+ || std::is_same<T, const float>::value
1245
+ || std::is_same<T, double>::value
1246
+ || std::is_same<T, const double>::value
1247
+ > (const_name("numpy.float") + const_name<sizeof(T) * 8>(),
1248
+ const_name("numpy.longdouble"));
1249
+ };
1250
+
1251
+ template <typename T>
1252
+ struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {
1253
+ static constexpr auto name = const_name < std::is_same<typename T::value_type, float>::value
1254
+ || std::is_same<typename T::value_type, const float>::value
1255
+ || std::is_same<typename T::value_type, double>::value
1256
+ || std::is_same<typename T::value_type, const double>::value
1257
+ > (const_name("numpy.complex")
1258
+ + const_name<sizeof(typename T::value_type) * 16>(),
1259
+ const_name("numpy.longcomplex"));
1260
+ };
1261
+
1262
+ template <typename T>
1263
+ struct npy_format_descriptor<
1264
+ T,
1265
+ enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
1266
+ : npy_format_descriptor_name<T> {
1267
+ private:
1268
+ // NB: the order here must match the one in common.h
1269
+ constexpr static const int values[15] = {npy_api::NPY_BOOL_,
1270
+ npy_api::NPY_BYTE_,
1271
+ npy_api::NPY_UBYTE_,
1272
+ npy_api::NPY_INT16_,
1273
+ npy_api::NPY_UINT16_,
1274
+ npy_api::NPY_INT32_,
1275
+ npy_api::NPY_UINT32_,
1276
+ npy_api::NPY_INT64_,
1277
+ npy_api::NPY_UINT64_,
1278
+ npy_api::NPY_FLOAT_,
1279
+ npy_api::NPY_DOUBLE_,
1280
+ npy_api::NPY_LONGDOUBLE_,
1281
+ npy_api::NPY_CFLOAT_,
1282
+ npy_api::NPY_CDOUBLE_,
1283
+ npy_api::NPY_CLONGDOUBLE_};
1284
+
1285
+ public:
1286
+ static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1287
+
1288
+ static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1289
+ };
1290
+
1291
+ template <typename T>
1292
+ struct npy_format_descriptor<T, enable_if_t<is_same_ignoring_cvref<T, PyObject *>::value>> {
1293
+ static constexpr auto name = const_name("object");
1294
+
1295
+ static constexpr int value = npy_api::NPY_OBJECT_;
1296
+
1297
+ static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1298
+ };
1299
+
1300
+ #define PYBIND11_DECL_CHAR_FMT \
1301
+ static constexpr auto name = const_name("S") + const_name<N>(); \
1302
+ static pybind11::dtype dtype() { \
1303
+ return pybind11::dtype(std::string("S") + std::to_string(N)); \
1304
+ }
1305
+ template <size_t N>
1306
+ struct npy_format_descriptor<char[N]> {
1307
+ PYBIND11_DECL_CHAR_FMT
1308
+ };
1309
+ template <size_t N>
1310
+ struct npy_format_descriptor<std::array<char, N>> {
1311
+ PYBIND11_DECL_CHAR_FMT
1312
+ };
1313
+ #undef PYBIND11_DECL_CHAR_FMT
1314
+
1315
+ template <typename T>
1316
+ struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
1317
+ private:
1318
+ using base_descr = npy_format_descriptor<typename array_info<T>::type>;
1319
+
1320
+ public:
1321
+ static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1322
+
1323
+ static constexpr auto name
1324
+ = const_name("(") + array_info<T>::extents + const_name(")") + base_descr::name;
1325
+ static pybind11::dtype dtype() {
1326
+ list shape;
1327
+ array_info<T>::append_extents(shape);
1328
+ return pybind11::dtype::from_args(
1329
+ pybind11::make_tuple(base_descr::dtype(), std::move(shape)));
1330
+ }
1331
+ };
1332
+
1333
+ template <typename T>
1334
+ struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
1335
+ private:
1336
+ using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
1337
+
1338
+ public:
1339
+ static constexpr auto name = base_descr::name;
1340
+ static pybind11::dtype dtype() { return base_descr::dtype(); }
1341
+ };
1342
+
1343
+ struct field_descriptor {
1344
+ const char *name;
1345
+ ssize_t offset;
1346
+ ssize_t size;
1347
+ std::string format;
1348
+ dtype descr;
1349
+ };
1350
+
1351
+ PYBIND11_NOINLINE void register_structured_dtype(any_container<field_descriptor> fields,
1352
+ const std::type_info &tinfo,
1353
+ ssize_t itemsize,
1354
+ bool (*direct_converter)(PyObject *, void *&)) {
1355
+
1356
+ auto &numpy_internals = get_numpy_internals();
1357
+ if (numpy_internals.get_type_info(tinfo, false)) {
1358
+ pybind11_fail("NumPy: dtype is already registered");
1359
+ }
1360
+
1361
+ // Use ordered fields because order matters as of NumPy 1.14:
1362
+ // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1363
+ std::vector<field_descriptor> ordered_fields(std::move(fields));
1364
+ std::sort(
1365
+ ordered_fields.begin(),
1366
+ ordered_fields.end(),
1367
+ [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1368
+
1369
+ list names, formats, offsets;
1370
+ for (auto &field : ordered_fields) {
1371
+ if (!field.descr) {
1372
+ pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ "
1373
+ + tinfo.name());
1374
+ }
1375
+ names.append(pybind11::str(field.name));
1376
+ formats.append(field.descr);
1377
+ offsets.append(pybind11::int_(field.offset));
1378
+ }
1379
+ auto *dtype_ptr
1380
+ = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)
1381
+ .release()
1382
+ .ptr();
1383
+
1384
+ // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1385
+ // not encoded explicitly into the format string. This will supposedly
1386
+ // get fixed in v1.12; for further details, see these:
1387
+ // - https://github.com/numpy/numpy/issues/7797
1388
+ // - https://github.com/numpy/numpy/pull/7798
1389
+ // Because of this, we won't use numpy's logic to generate buffer format
1390
+ // strings and will just do it ourselves.
1391
+ ssize_t offset = 0;
1392
+ std::ostringstream oss;
1393
+ // mark the structure as unaligned with '^', because numpy and C++ don't
1394
+ // always agree about alignment (particularly for complex), and we're
1395
+ // explicitly listing all our padding. This depends on none of the fields
1396
+ // overriding the endianness. Putting the ^ in front of individual fields
1397
+ // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1398
+ oss << "^T{";
1399
+ for (auto &field : ordered_fields) {
1400
+ if (field.offset > offset) {
1401
+ oss << (field.offset - offset) << 'x';
1402
+ }
1403
+ oss << field.format << ':' << field.name << ':';
1404
+ offset = field.offset + field.size;
1405
+ }
1406
+ if (itemsize > offset) {
1407
+ oss << (itemsize - offset) << 'x';
1408
+ }
1409
+ oss << '}';
1410
+ auto format_str = oss.str();
1411
+
1412
+ // Smoke test: verify that NumPy properly parses our buffer format string
1413
+ auto &api = npy_api::get();
1414
+ auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
1415
+ if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {
1416
+ pybind11_fail("NumPy: invalid buffer descriptor!");
1417
+ }
1418
+
1419
+ auto tindex = std::type_index(tinfo);
1420
+ numpy_internals.registered_dtypes[tindex] = {dtype_ptr, std::move(format_str)};
1421
+ get_internals().direct_conversions[tindex].push_back(direct_converter);
1422
+ }
1423
+
1424
+ template <typename T, typename SFINAE>
1425
+ struct npy_format_descriptor {
1426
+ static_assert(is_pod_struct<T>::value,
1427
+ "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1428
+
1429
+ static constexpr auto name = make_caster<T>::name;
1430
+
1431
+ static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }
1432
+
1433
+ static std::string format() {
1434
+ static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1435
+ return format_str;
1436
+ }
1437
+
1438
+ static void register_dtype(any_container<field_descriptor> fields) {
1439
+ register_structured_dtype(std::move(fields),
1440
+ typeid(typename std::remove_cv<T>::type),
1441
+ sizeof(T),
1442
+ &direct_converter);
1443
+ }
1444
+
1445
+ private:
1446
+ static PyObject *dtype_ptr() {
1447
+ static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1448
+ return ptr;
1449
+ }
1450
+
1451
+ static bool direct_converter(PyObject *obj, void *&value) {
1452
+ auto &api = npy_api::get();
1453
+ if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {
1454
+ return false;
1455
+ }
1456
+ if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1457
+ if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1458
+ value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1459
+ return true;
1460
+ }
1461
+ }
1462
+ return false;
1463
+ }
1464
+ };
1465
+
1466
+ #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1467
+ # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1468
+ # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1469
+ #else
1470
+
1471
+ # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1472
+ ::pybind11::detail::field_descriptor { \
1473
+ Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1474
+ ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1475
+ ::pybind11::detail::npy_format_descriptor< \
1476
+ decltype(std::declval<T>().Field)>::dtype() \
1477
+ }
1478
+
1479
+ // Extract name, offset and format descriptor for a struct field
1480
+ # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1481
+
1482
+ // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1483
+ // (C) William Swanson, Paul Fultz
1484
+ # define PYBIND11_EVAL0(...) __VA_ARGS__
1485
+ # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1486
+ # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1487
+ # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1488
+ # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1489
+ # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1490
+ # define PYBIND11_MAP_END(...)
1491
+ # define PYBIND11_MAP_OUT
1492
+ # define PYBIND11_MAP_COMMA ,
1493
+ # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1494
+ # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1495
+ # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1496
+ # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1497
+ # if defined(_MSC_VER) \
1498
+ && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1499
+ # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1500
+ PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1501
+ # else
1502
+ # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1503
+ PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1504
+ # endif
1505
+ # define PYBIND11_MAP_LIST_NEXT(test, next) \
1506
+ PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1507
+ # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1508
+ f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1509
+ # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1510
+ f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1511
+ // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1512
+ # define PYBIND11_MAP_LIST(f, t, ...) \
1513
+ PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1514
+
1515
+ # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1516
+ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1517
+ ::std::vector<::pybind11::detail::field_descriptor>{ \
1518
+ PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1519
+
1520
+ # if defined(_MSC_VER) && !defined(__clang__)
1521
+ # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1522
+ PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1523
+ # else
1524
+ # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1525
+ PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1526
+ # endif
1527
+ # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1528
+ PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1529
+ # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1530
+ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1531
+ # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1532
+ f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1533
+ // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1534
+ # define PYBIND11_MAP2_LIST(f, t, ...) \
1535
+ PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1536
+
1537
+ # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1538
+ ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1539
+ ::std::vector<::pybind11::detail::field_descriptor>{ \
1540
+ PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1541
+
1542
+ #endif // __CLION_IDE__
1543
+
1544
+ class common_iterator {
1545
+ public:
1546
+ using container_type = std::vector<ssize_t>;
1547
+ using value_type = container_type::value_type;
1548
+ using size_type = container_type::size_type;
1549
+
1550
+ common_iterator() : m_strides() {}
1551
+
1552
+ common_iterator(void *ptr, const container_type &strides, const container_type &shape)
1553
+ : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {
1554
+ m_strides.back() = static_cast<value_type>(strides.back());
1555
+ for (size_type i = m_strides.size() - 1; i != 0; --i) {
1556
+ size_type j = i - 1;
1557
+ auto s = static_cast<value_type>(shape[i]);
1558
+ m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1559
+ }
1560
+ }
1561
+
1562
+ void increment(size_type dim) { p_ptr += m_strides[dim]; }
1563
+
1564
+ void *data() const { return p_ptr; }
1565
+
1566
+ private:
1567
+ char *p_ptr{nullptr};
1568
+ container_type m_strides;
1569
+ };
1570
+
1571
+ template <size_t N>
1572
+ class multi_array_iterator {
1573
+ public:
1574
+ using container_type = std::vector<ssize_t>;
1575
+
1576
+ multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)
1577
+ : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {
1578
+
1579
+ // Manual copy to avoid conversion warning if using std::copy
1580
+ for (size_t i = 0; i < shape.size(); ++i) {
1581
+ m_shape[i] = shape[i];
1582
+ }
1583
+
1584
+ container_type strides(shape.size());
1585
+ for (size_t i = 0; i < N; ++i) {
1586
+ init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1587
+ }
1588
+ }
1589
+
1590
+ multi_array_iterator &operator++() {
1591
+ for (size_t j = m_index.size(); j != 0; --j) {
1592
+ size_t i = j - 1;
1593
+ if (++m_index[i] != m_shape[i]) {
1594
+ increment_common_iterator(i);
1595
+ break;
1596
+ }
1597
+ m_index[i] = 0;
1598
+ }
1599
+ return *this;
1600
+ }
1601
+
1602
+ template <size_t K, class T = void>
1603
+ T *data() const {
1604
+ return reinterpret_cast<T *>(m_common_iterator[K].data());
1605
+ }
1606
+
1607
+ private:
1608
+ using common_iter = common_iterator;
1609
+
1610
+ void init_common_iterator(const buffer_info &buffer,
1611
+ const container_type &shape,
1612
+ common_iter &iterator,
1613
+ container_type &strides) {
1614
+ auto buffer_shape_iter = buffer.shape.rbegin();
1615
+ auto buffer_strides_iter = buffer.strides.rbegin();
1616
+ auto shape_iter = shape.rbegin();
1617
+ auto strides_iter = strides.rbegin();
1618
+
1619
+ while (buffer_shape_iter != buffer.shape.rend()) {
1620
+ if (*shape_iter == *buffer_shape_iter) {
1621
+ *strides_iter = *buffer_strides_iter;
1622
+ } else {
1623
+ *strides_iter = 0;
1624
+ }
1625
+
1626
+ ++buffer_shape_iter;
1627
+ ++buffer_strides_iter;
1628
+ ++shape_iter;
1629
+ ++strides_iter;
1630
+ }
1631
+
1632
+ std::fill(strides_iter, strides.rend(), 0);
1633
+ iterator = common_iter(buffer.ptr, strides, shape);
1634
+ }
1635
+
1636
+ void increment_common_iterator(size_t dim) {
1637
+ for (auto &iter : m_common_iterator) {
1638
+ iter.increment(dim);
1639
+ }
1640
+ }
1641
+
1642
+ container_type m_shape;
1643
+ container_type m_index;
1644
+ std::array<common_iter, N> m_common_iterator;
1645
+ };
1646
+
1647
+ enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
1648
+
1649
+ // Populates the shape and number of dimensions for the set of buffers. Returns a
1650
+ // broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each
1651
+ // buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous
1652
+ // (`f_trivial`) storage buffer; returns `non_trivial` otherwise.
1653
+ template <size_t N>
1654
+ broadcast_trivial
1655
+ broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1656
+ ndim = std::accumulate(
1657
+ buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1658
+ return std::max(res, buf.ndim);
1659
+ });
1660
+
1661
+ shape.clear();
1662
+ shape.resize((size_t) ndim, 1);
1663
+
1664
+ // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1
1665
+ // or the full size).
1666
+ for (size_t i = 0; i < N; ++i) {
1667
+ auto res_iter = shape.rbegin();
1668
+ auto end = buffers[i].shape.rend();
1669
+ for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;
1670
+ ++shape_iter, ++res_iter) {
1671
+ const auto &dim_size_in = *shape_iter;
1672
+ auto &dim_size_out = *res_iter;
1673
+
1674
+ // Each input dimension can either be 1 or `n`, but `n` values must match across
1675
+ // buffers
1676
+ if (dim_size_out == 1) {
1677
+ dim_size_out = dim_size_in;
1678
+ } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
1679
+ pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1680
+ }
1681
+ }
1682
+ }
1683
+
1684
+ bool trivial_broadcast_c = true;
1685
+ bool trivial_broadcast_f = true;
1686
+ for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1687
+ if (buffers[i].size == 1) {
1688
+ continue;
1689
+ }
1690
+
1691
+ // Require the same number of dimensions:
1692
+ if (buffers[i].ndim != ndim) {
1693
+ return broadcast_trivial::non_trivial;
1694
+ }
1695
+
1696
+ // Require all dimensions be full-size:
1697
+ if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {
1698
+ return broadcast_trivial::non_trivial;
1699
+ }
1700
+
1701
+ // Check for C contiguity (but only if previous inputs were also C contiguous)
1702
+ if (trivial_broadcast_c) {
1703
+ ssize_t expect_stride = buffers[i].itemsize;
1704
+ auto end = buffers[i].shape.crend();
1705
+ for (auto shape_iter = buffers[i].shape.crbegin(),
1706
+ stride_iter = buffers[i].strides.crbegin();
1707
+ trivial_broadcast_c && shape_iter != end;
1708
+ ++shape_iter, ++stride_iter) {
1709
+ if (expect_stride == *stride_iter) {
1710
+ expect_stride *= *shape_iter;
1711
+ } else {
1712
+ trivial_broadcast_c = false;
1713
+ }
1714
+ }
1715
+ }
1716
+
1717
+ // Check for Fortran contiguity (if previous inputs were also F contiguous)
1718
+ if (trivial_broadcast_f) {
1719
+ ssize_t expect_stride = buffers[i].itemsize;
1720
+ auto end = buffers[i].shape.cend();
1721
+ for (auto shape_iter = buffers[i].shape.cbegin(),
1722
+ stride_iter = buffers[i].strides.cbegin();
1723
+ trivial_broadcast_f && shape_iter != end;
1724
+ ++shape_iter, ++stride_iter) {
1725
+ if (expect_stride == *stride_iter) {
1726
+ expect_stride *= *shape_iter;
1727
+ } else {
1728
+ trivial_broadcast_f = false;
1729
+ }
1730
+ }
1731
+ }
1732
+ }
1733
+
1734
+ return trivial_broadcast_c ? broadcast_trivial::c_trivial
1735
+ : trivial_broadcast_f ? broadcast_trivial::f_trivial
1736
+ : broadcast_trivial::non_trivial;
1737
+ }
1738
+
1739
+ template <typename T>
1740
+ struct vectorize_arg {
1741
+ static_assert(!std::is_rvalue_reference<T>::value,
1742
+ "Functions with rvalue reference arguments cannot be vectorized");
1743
+ // The wrapped function gets called with this type:
1744
+ using call_type = remove_reference_t<T>;
1745
+ // Is this a vectorized argument?
1746
+ static constexpr bool vectorize
1747
+ = satisfies_any_of<call_type, std::is_arithmetic, is_complex, is_pod>::value
1748
+ && satisfies_none_of<call_type,
1749
+ std::is_pointer,
1750
+ std::is_array,
1751
+ is_std_array,
1752
+ std::is_enum>::value
1753
+ && (!std::is_reference<T>::value
1754
+ || (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
1755
+ // Accept this type: an array for vectorized types, otherwise the type as-is:
1756
+ using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
1757
+ };
1758
+
1759
+ // py::vectorize when a return type is present
1760
+ template <typename Func, typename Return, typename... Args>
1761
+ struct vectorize_returned_array {
1762
+ using Type = array_t<Return>;
1763
+
1764
+ static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
1765
+ if (trivial == broadcast_trivial::f_trivial) {
1766
+ return array_t<Return, array::f_style>(shape);
1767
+ }
1768
+ return array_t<Return>(shape);
1769
+ }
1770
+
1771
+ static Return *mutable_data(Type &array) { return array.mutable_data(); }
1772
+
1773
+ static Return call(Func &f, Args &...args) { return f(args...); }
1774
+
1775
+ static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }
1776
+ };
1777
+
1778
+ // py::vectorize when a return type is not present
1779
+ template <typename Func, typename... Args>
1780
+ struct vectorize_returned_array<Func, void, Args...> {
1781
+ using Type = none;
1782
+
1783
+ static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }
1784
+
1785
+ static void *mutable_data(Type &) { return nullptr; }
1786
+
1787
+ static detail::void_type call(Func &f, Args &...args) {
1788
+ f(args...);
1789
+ return {};
1790
+ }
1791
+
1792
+ static void call(void *, size_t, Func &f, Args &...args) { f(args...); }
1793
+ };
1794
+
1795
+ template <typename Func, typename Return, typename... Args>
1796
+ struct vectorize_helper {
1797
+
1798
+ // NVCC for some reason breaks if NVectorized is private
1799
+ #ifdef __CUDACC__
1800
+ public:
1801
+ #else
1802
+ private:
1803
+ #endif
1804
+
1805
+ static constexpr size_t N = sizeof...(Args);
1806
+ static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1807
+ static_assert(
1808
+ NVectorized >= 1,
1809
+ "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1810
+
1811
+ public:
1812
+ template <typename T,
1813
+ // SFINAE to prevent shadowing the copy constructor.
1814
+ typename = detail::enable_if_t<
1815
+ !std::is_same<vectorize_helper, typename std::decay<T>::type>::value>>
1816
+ explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}
1817
+
1818
+ object operator()(typename vectorize_arg<Args>::type... args) {
1819
+ return run(args...,
1820
+ make_index_sequence<N>(),
1821
+ select_indices<vectorize_arg<Args>::vectorize...>(),
1822
+ make_index_sequence<NVectorized>());
1823
+ }
1824
+
1825
+ private:
1826
+ remove_reference_t<Func> f;
1827
+
1828
+ // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling
1829
+ // with "/permissive-" flag when arg_call_types is manually inlined.
1830
+ using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
1831
+ template <size_t Index>
1832
+ using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
1833
+
1834
+ using returned_array = vectorize_returned_array<Func, Return, Args...>;
1835
+
1836
+ // Runs a vectorized function given arguments tuple and three index sequences:
1837
+ // - Index is the full set of 0 ... (N-1) argument indices;
1838
+ // - VIndex is the subset of argument indices with vectorized parameters, letting us access
1839
+ // vectorized arguments (anything not in this sequence is passed through)
1840
+ // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1841
+ // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1842
+ // index BIndex in the array).
1843
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
1844
+ object run(typename vectorize_arg<Args>::type &...args,
1845
+ index_sequence<Index...> i_seq,
1846
+ index_sequence<VIndex...> vi_seq,
1847
+ index_sequence<BIndex...> bi_seq) {
1848
+
1849
+ // Pointers to values the function was called with; the vectorized ones set here will start
1850
+ // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1851
+ // call the wrapped function. Non-vectorized pointers are left as-is.
1852
+ std::array<void *, N> params{{&args...}};
1853
+
1854
+ // The array of `buffer_info`s of vectorized arguments:
1855
+ std::array<buffer_info, NVectorized> buffers{
1856
+ {reinterpret_cast<array *>(params[VIndex])->request()...}};
1857
+
1858
+ /* Determine dimensions parameters of output array */
1859
+ ssize_t nd = 0;
1860
+ std::vector<ssize_t> shape(0);
1861
+ auto trivial = broadcast(buffers, nd, shape);
1862
+ auto ndim = (size_t) nd;
1863
+
1864
+ size_t size
1865
+ = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
1866
+
1867
+ // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
1868
+ // not wrapped in an array).
1869
+ if (size == 1 && ndim == 0) {
1870
+ PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
1871
+ return cast(
1872
+ returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
1873
+ }
1874
+
1875
+ auto result = returned_array::create(trivial, shape);
1876
+
1877
+ PYBIND11_WARNING_PUSH
1878
+ #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
1879
+ PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move")
1880
+ #endif
1881
+
1882
+ if (size == 0) {
1883
+ return result;
1884
+ }
1885
+
1886
+ /* Call the function */
1887
+ auto *mutable_data = returned_array::mutable_data(result);
1888
+ if (trivial == broadcast_trivial::non_trivial) {
1889
+ apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
1890
+ } else {
1891
+ apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
1892
+ }
1893
+
1894
+ return result;
1895
+ PYBIND11_WARNING_POP
1896
+ }
1897
+
1898
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
1899
+ void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
1900
+ std::array<void *, N> &params,
1901
+ Return *out,
1902
+ size_t size,
1903
+ index_sequence<Index...>,
1904
+ index_sequence<VIndex...>,
1905
+ index_sequence<BIndex...>) {
1906
+
1907
+ // Initialize an array of mutable byte references and sizes with references set to the
1908
+ // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
1909
+ // (except for singletons, which get an increment of 0).
1910
+ std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
1911
+ {std::pair<unsigned char *&, const size_t>(
1912
+ reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
1913
+ buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};
1914
+
1915
+ for (size_t i = 0; i < size; ++i) {
1916
+ returned_array::call(
1917
+ out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
1918
+ for (auto &x : vecparams) {
1919
+ x.first += x.second;
1920
+ }
1921
+ }
1922
+ }
1923
+
1924
+ template <size_t... Index, size_t... VIndex, size_t... BIndex>
1925
+ void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
1926
+ std::array<void *, N> &params,
1927
+ Return *out,
1928
+ size_t size,
1929
+ const std::vector<ssize_t> &output_shape,
1930
+ index_sequence<Index...>,
1931
+ index_sequence<VIndex...>,
1932
+ index_sequence<BIndex...>) {
1933
+
1934
+ multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
1935
+
1936
+ for (size_t i = 0; i < size; ++i, ++input_iter) {
1937
+ PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));
1938
+ returned_array::call(
1939
+ out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
1940
+ }
1941
+ }
1942
+ };
1943
+
1944
+ template <typename Func, typename Return, typename... Args>
1945
+ vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {
1946
+ return detail::vectorize_helper<Func, Return, Args...>(f);
1947
+ }
1948
+
1949
+ template <typename T, int Flags>
1950
+ struct handle_type_name<array_t<T, Flags>> {
1951
+ static constexpr auto name
1952
+ = const_name("numpy.ndarray[") + npy_format_descriptor<T>::name + const_name("]");
1953
+ };
1954
+
1955
+ PYBIND11_NAMESPACE_END(detail)
1956
+
1957
+ // Vanilla pointer vectorizer:
1958
+ template <typename Return, typename... Args>
1959
+ detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {
1960
+ return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
1961
+ }
1962
+
1963
+ // lambda vectorizer:
1964
+ template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
1965
+ auto vectorize(Func &&f)
1966
+ -> decltype(detail::vectorize_extractor(std::forward<Func>(f),
1967
+ (detail::function_signature_t<Func> *) nullptr)) {
1968
+ return detail::vectorize_extractor(std::forward<Func>(f),
1969
+ (detail::function_signature_t<Func> *) nullptr);
1970
+ }
1971
+
1972
+ // Vectorize a class method (non-const):
1973
+ template <typename Return,
1974
+ typename Class,
1975
+ typename... Args,
1976
+ typename Helper = detail::vectorize_helper<
1977
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
1978
+ Return,
1979
+ Class *,
1980
+ Args...>>
1981
+ Helper vectorize(Return (Class::*f)(Args...)) {
1982
+ return Helper(std::mem_fn(f));
1983
+ }
1984
+
1985
+ // Vectorize a class method (const):
1986
+ template <typename Return,
1987
+ typename Class,
1988
+ typename... Args,
1989
+ typename Helper = detail::vectorize_helper<
1990
+ decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),
1991
+ Return,
1992
+ const Class *,
1993
+ Args...>>
1994
+ Helper vectorize(Return (Class::*f)(Args...) const) {
1995
+ return Helper(std::mem_fn(f));
1996
+ }
1997
+
1998
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)