Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/__init__.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/anomaly_mode.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/forward_ad.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/function.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/functional.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/grad_mode.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/gradcheck.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/graph.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/profiler.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/profiler_legacy.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/profiler_util.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/variable.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__init__.py +1 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__pycache__/__init__.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__pycache__/tensor.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__pycache__/utils.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/tensor.py +65 -0
- data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/utils.py +63 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/__init__.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/_remove_effect_tokens_pass.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/_tree_utils.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/custom_obj.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/dynamic_shapes.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/exported_program.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/graph_signature.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/unflatten.cpython-38.pyc +0 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/class.h +748 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/common.h +1267 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/descr.h +171 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/init.h +434 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/internals.h +667 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/type_caster_base.h +1218 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/typeid.h +65 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/eigen/common.h +9 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/eigen/matrix.h +714 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/eigen/tensor.h +517 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h +57 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h +255 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h +63 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateless.h +82 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/base.h +103 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/chunk.h +529 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/map.h +118 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/mnist.h +48 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/shared.h +83 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/stateful.h +70 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/tensor.h +38 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/data_shuttle.h +87 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/queue.h +84 -0
- data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/sequencers.h +113 -0
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/anomaly_mode.cpython-38.pyc
ADDED
|
Binary file (5.52 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/forward_ad.cpython-38.pyc
ADDED
|
Binary file (7.2 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/function.cpython-38.pyc
ADDED
|
Binary file (32.3 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/functional.cpython-38.pyc
ADDED
|
Binary file (35.9 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/grad_mode.cpython-38.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/gradcheck.cpython-38.pyc
ADDED
|
Binary file (61.5 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/graph.cpython-38.pyc
ADDED
|
Binary file (26.4 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/profiler.cpython-38.pyc
ADDED
|
Binary file (37.1 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/profiler_legacy.cpython-38.pyc
ADDED
|
Binary file (7.73 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/profiler_util.cpython-38.pyc
ADDED
|
Binary file (29.4 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/__pycache__/variable.cpython-38.pyc
ADDED
|
Binary file (809 Bytes). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .tensor import * # noqa: F403
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (184 Bytes). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__pycache__/tensor.cpython-38.pyc
ADDED
|
Binary file (2.2 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/__pycache__/utils.cpython-38.pyc
ADDED
|
Binary file (1.47 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/tensor.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from functools import reduce
|
| 4 |
+
from typing_extensions import deprecated
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch._utils
|
| 8 |
+
from ..function import Function
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Type(Function):
|
| 12 |
+
@staticmethod
|
| 13 |
+
@deprecated(
|
| 14 |
+
"`torch.autograd._functions.Type` is deprecated as of PyTorch 2.1, "
|
| 15 |
+
"please use `torch.tensor.to(dtype=dtype)` instead.",
|
| 16 |
+
category=FutureWarning,
|
| 17 |
+
)
|
| 18 |
+
def forward(ctx, i, dest_type):
|
| 19 |
+
ctx.input_type = type(i)
|
| 20 |
+
ctx.input_device = -1 if not i.is_cuda else i.get_device()
|
| 21 |
+
return i.type(dest_type)
|
| 22 |
+
|
| 23 |
+
@staticmethod
|
| 24 |
+
def backward(ctx, grad_output):
|
| 25 |
+
if ctx.input_device == -1:
|
| 26 |
+
return grad_output.type(ctx.input_type), None
|
| 27 |
+
else:
|
| 28 |
+
with torch.cuda.device(ctx.input_device):
|
| 29 |
+
return grad_output.type(ctx.input_type), None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# TODO: deprecate this
|
| 33 |
+
class Resize(Function):
|
| 34 |
+
@staticmethod
|
| 35 |
+
def forward(ctx, tensor, sizes):
|
| 36 |
+
ctx.sizes = sizes
|
| 37 |
+
ctx.numel = reduce(operator.mul, sizes, 1)
|
| 38 |
+
if tensor.numel() != ctx.numel:
|
| 39 |
+
raise RuntimeError(
|
| 40 |
+
(
|
| 41 |
+
"requested resize to {} ({} elements in total), "
|
| 42 |
+
"but the given tensor has a size of {} ({} elements). "
|
| 43 |
+
"autograd's resize can only change the shape of a given "
|
| 44 |
+
"tensor, while preserving the number of elements. "
|
| 45 |
+
).format(
|
| 46 |
+
"x".join(map(str, sizes)),
|
| 47 |
+
ctx.numel,
|
| 48 |
+
"x".join(map(str, tensor.size())),
|
| 49 |
+
tensor.numel(),
|
| 50 |
+
)
|
| 51 |
+
)
|
| 52 |
+
ctx.input_sizes = tensor.size()
|
| 53 |
+
if tensor.is_quantized:
|
| 54 |
+
tensor.copy_(tensor)
|
| 55 |
+
return tensor.contiguous().view(*sizes)
|
| 56 |
+
if tensor.is_contiguous():
|
| 57 |
+
result = tensor.new(tensor).contiguous().view(*sizes)
|
| 58 |
+
return result
|
| 59 |
+
else:
|
| 60 |
+
return tensor.contiguous().view(*sizes)
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def backward(ctx, grad_output):
|
| 64 |
+
assert grad_output.numel() == ctx.numel
|
| 65 |
+
return grad_output.contiguous().view(ctx.input_sizes), None
|
data/home/.local/lib/python3.8/site-packages/torch/autograd/_functions/utils.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from functools import reduce
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def maybe_view(tensor, size, check_same_size=True):
|
| 7 |
+
if check_same_size and tensor.size() == size:
|
| 8 |
+
return tensor
|
| 9 |
+
return tensor.contiguous().view(size)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def maybe_unexpand(tensor, old_size, check_same_size=True):
|
| 13 |
+
if check_same_size and tensor.size() == old_size:
|
| 14 |
+
return tensor
|
| 15 |
+
num_unsqueezed = tensor.dim() - len(old_size)
|
| 16 |
+
expanded_dims = [
|
| 17 |
+
dim
|
| 18 |
+
for dim, (expanded, original) in enumerate(
|
| 19 |
+
zip(tensor.size()[num_unsqueezed:], old_size)
|
| 20 |
+
)
|
| 21 |
+
if expanded != original
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
for _ in range(num_unsqueezed):
|
| 25 |
+
tensor = tensor.sum(0, keepdim=False)
|
| 26 |
+
for dim in expanded_dims:
|
| 27 |
+
tensor = tensor.sum(dim, keepdim=True)
|
| 28 |
+
return tensor
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Check whether the op enable broadcasting, and whether it is supported by ONNX.
|
| 32 |
+
# If dims1 and dims2 are different, then broadcast is True.
|
| 33 |
+
# We always assume the combination of dims1 and dims2 is broadcastable.
|
| 34 |
+
# The following types of broadcasting are supported in ONNX:
|
| 35 |
+
# 1) Only one element in dims2, such as dims2 = [1, 1]
|
| 36 |
+
# 2) dims2 is suffix of dims1, such as dims1 = [2, 3, 4], and dims2 = [3, 4]
|
| 37 |
+
# Details can be found here: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm
|
| 38 |
+
def check_onnx_broadcast(dims1, dims2):
|
| 39 |
+
broadcast = False
|
| 40 |
+
supported = True
|
| 41 |
+
len1 = len(dims1)
|
| 42 |
+
len2 = len(dims2)
|
| 43 |
+
numel1 = reduce(operator.mul, dims1)
|
| 44 |
+
numel2 = reduce(operator.mul, dims2)
|
| 45 |
+
if len1 < len2:
|
| 46 |
+
broadcast = True
|
| 47 |
+
if numel2 != 1:
|
| 48 |
+
supported = False
|
| 49 |
+
elif len1 > len2:
|
| 50 |
+
broadcast = True
|
| 51 |
+
if numel2 != 1 and dims1[len1 - len2 :] != dims2:
|
| 52 |
+
supported = False
|
| 53 |
+
else:
|
| 54 |
+
if dims1 != dims2:
|
| 55 |
+
broadcast = True
|
| 56 |
+
if numel2 != 1:
|
| 57 |
+
supported = False
|
| 58 |
+
|
| 59 |
+
if not supported:
|
| 60 |
+
raise ValueError(
|
| 61 |
+
f"Numpy style broadcasting is not supported in ONNX. Input dims are: {dims1}, {dims2}"
|
| 62 |
+
)
|
| 63 |
+
return broadcast
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/_remove_effect_tokens_pass.cpython-38.pyc
ADDED
|
Binary file (3.18 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/_tree_utils.cpython-38.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/custom_obj.cpython-38.pyc
ADDED
|
Binary file (537 Bytes). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/dynamic_shapes.cpython-38.pyc
ADDED
|
Binary file (31.1 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/exported_program.cpython-38.pyc
ADDED
|
Binary file (25.4 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/graph_signature.cpython-38.pyc
ADDED
|
Binary file (17.1 kB). View file
|
|
|
data/home/.local/lib/python3.8/site-packages/torch/export/__pycache__/unflatten.cp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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 PY_VERSION_HEX >= 0x030C0000
|
| 90 |
+
// Since Python-3.12 property-derived types are required to
|
| 91 |
+
// have dynamic attributes (to set `__doc__`)
|
| 92 |
+
enable_dynamic_attributes(heap_type);
|
| 93 |
+
# endif
|
| 94 |
+
|
| 95 |
+
if (PyType_Ready(type) < 0) {
|
| 96 |
+
pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
| 100 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
| 101 |
+
|
| 102 |
+
return type;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
#else // PYPY
|
| 106 |
+
|
| 107 |
+
/** PyPy has some issues with the above C API, so we evaluate Python code instead.
|
| 108 |
+
This function will only be called once so performance isn't really a concern.
|
| 109 |
+
Return value: New reference. */
|
| 110 |
+
inline PyTypeObject *make_static_property_type() {
|
| 111 |
+
auto d = dict();
|
| 112 |
+
PyObject *result = PyRun_String(R"(\
|
| 113 |
+
class pybind11_static_property(property):
|
| 114 |
+
def __get__(self, obj, cls):
|
| 115 |
+
return property.__get__(self, cls, cls)
|
| 116 |
+
|
| 117 |
+
def __set__(self, obj, value):
|
| 118 |
+
cls = obj if isinstance(obj, type) else type(obj)
|
| 119 |
+
property.__set__(self, cls, value)
|
| 120 |
+
)",
|
| 121 |
+
Py_file_input,
|
| 122 |
+
d.ptr(),
|
| 123 |
+
d.ptr());
|
| 124 |
+
if (result == nullptr)
|
| 125 |
+
throw error_already_set();
|
| 126 |
+
Py_DECREF(result);
|
| 127 |
+
return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
#endif // PYPY
|
| 131 |
+
|
| 132 |
+
/** Types with static properties need to handle `Type.static_prop = x` in a specific way.
|
| 133 |
+
By default, Python replaces the `static_property` itself, but for wrapped C++ types
|
| 134 |
+
we need to call `static_property.__set__()` in order to propagate the new value to
|
| 135 |
+
the underlying C++ data structure. */
|
| 136 |
+
extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
|
| 137 |
+
// Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
|
| 138 |
+
// descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
|
| 139 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
| 140 |
+
|
| 141 |
+
// The following assignment combinations are possible:
|
| 142 |
+
// 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
|
| 143 |
+
// 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
|
| 144 |
+
// 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
|
| 145 |
+
auto *const static_prop = (PyObject *) get_internals().static_property_type;
|
| 146 |
+
const auto call_descr_set = (descr != nullptr) && (value != nullptr)
|
| 147 |
+
&& (PyObject_IsInstance(descr, static_prop) != 0)
|
| 148 |
+
&& (PyObject_IsInstance(value, static_prop) == 0);
|
| 149 |
+
if (call_descr_set) {
|
| 150 |
+
// Call `static_property.__set__()` instead of replacing the `static_property`.
|
| 151 |
+
#if !defined(PYPY_VERSION)
|
| 152 |
+
return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
|
| 153 |
+
#else
|
| 154 |
+
if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
|
| 155 |
+
Py_DECREF(result);
|
| 156 |
+
return 0;
|
| 157 |
+
} else {
|
| 158 |
+
return -1;
|
| 159 |
+
}
|
| 160 |
+
#endif
|
| 161 |
+
} else {
|
| 162 |
+
// Replace existing attribute.
|
| 163 |
+
return PyType_Type.tp_setattro(obj, name, value);
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/**
|
| 168 |
+
* Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
|
| 169 |
+
* methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
|
| 170 |
+
* when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
|
| 171 |
+
* to do a special case bypass for PyInstanceMethod_Types.
|
| 172 |
+
*/
|
| 173 |
+
extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
|
| 174 |
+
PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
|
| 175 |
+
if (descr && PyInstanceMethod_Check(descr)) {
|
| 176 |
+
Py_INCREF(descr);
|
| 177 |
+
return descr;
|
| 178 |
+
}
|
| 179 |
+
return PyType_Type.tp_getattro(obj, name);
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/// metaclass `__call__` function that is used to create all pybind11 objects.
|
| 183 |
+
extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
|
| 184 |
+
|
| 185 |
+
// use the default metaclass call to create/initialize the object
|
| 186 |
+
PyObject *self = PyType_Type.tp_call(type, args, kwargs);
|
| 187 |
+
if (self == nullptr) {
|
| 188 |
+
return nullptr;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
// Ensure that the base __init__ function(s) were called
|
| 192 |
+
values_and_holders vhs(self);
|
| 193 |
+
for (const auto &vh : vhs) {
|
| 194 |
+
if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
|
| 195 |
+
PyErr_Format(PyExc_TypeError,
|
| 196 |
+
"%.200s.__init__() must be called when overriding __init__",
|
| 197 |
+
get_fully_qualified_tp_name(vh.type->type).c_str());
|
| 198 |
+
Py_DECREF(self);
|
| 199 |
+
return nullptr;
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
return self;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
/// Cleanup the type-info for a pybind11-registered type.
|
| 207 |
+
extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
|
| 208 |
+
auto *type = (PyTypeObject *) obj;
|
| 209 |
+
auto &internals = get_internals();
|
| 210 |
+
|
| 211 |
+
// A pybind11-registered type will:
|
| 212 |
+
// 1) be found in internals.registered_types_py
|
| 213 |
+
// 2) have exactly one associated `detail::type_info`
|
| 214 |
+
auto found_type = internals.registered_types_py.find(type);
|
| 215 |
+
if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
|
| 216 |
+
&& found_type->second[0]->type == type) {
|
| 217 |
+
|
| 218 |
+
auto *tinfo = found_type->second[0];
|
| 219 |
+
auto tindex = std::type_index(*tinfo->cpptype);
|
| 220 |
+
internals.direct_conversions.erase(tindex);
|
| 221 |
+
|
| 222 |
+
if (tinfo->module_local) {
|
| 223 |
+
get_local_internals().registered_types_cpp.erase(tindex);
|
| 224 |
+
} else {
|
| 225 |
+
internals.registered_types_cpp.erase(tindex);
|
| 226 |
+
}
|
| 227 |
+
internals.registered_types_py.erase(tinfo->type);
|
| 228 |
+
|
| 229 |
+
// Actually just `std::erase_if`, but that's only available in C++20
|
| 230 |
+
auto &cache = internals.inactive_override_cache;
|
| 231 |
+
for (auto it = cache.begin(), last = cache.end(); it != last;) {
|
| 232 |
+
if (it->first == (PyObject *) tinfo->type) {
|
| 233 |
+
it = cache.erase(it);
|
| 234 |
+
} else {
|
| 235 |
+
++it;
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
delete tinfo;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
PyType_Type.tp_dealloc(obj);
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/** This metaclass is assigned by default to all pybind11 types and is required in order
|
| 246 |
+
for static properties to function correctly. Users may override this using `py::metaclass`.
|
| 247 |
+
Return value: New reference. */
|
| 248 |
+
inline PyTypeObject *make_default_metaclass() {
|
| 249 |
+
constexpr auto *name = "pybind11_type";
|
| 250 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
| 251 |
+
|
| 252 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 253 |
+
issue no Python C API calls which could potentially invoke the
|
| 254 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 255 |
+
turn find the newly constructed type in an invalid state) */
|
| 256 |
+
auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
|
| 257 |
+
if (!heap_type) {
|
| 258 |
+
pybind11_fail("make_default_metaclass(): error allocating metaclass!");
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
| 262 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
| 263 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
| 264 |
+
#endif
|
| 265 |
+
|
| 266 |
+
auto *type = &heap_type->ht_type;
|
| 267 |
+
type->tp_name = name;
|
| 268 |
+
type->tp_base = type_incref(&PyType_Type);
|
| 269 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
| 270 |
+
|
| 271 |
+
type->tp_call = pybind11_meta_call;
|
| 272 |
+
|
| 273 |
+
type->tp_setattro = pybind11_meta_setattro;
|
| 274 |
+
type->tp_getattro = pybind11_meta_getattro;
|
| 275 |
+
|
| 276 |
+
type->tp_dealloc = pybind11_meta_dealloc;
|
| 277 |
+
|
| 278 |
+
if (PyType_Ready(type) < 0) {
|
| 279 |
+
pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
| 283 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
| 284 |
+
|
| 285 |
+
return type;
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/// For multiple inheritance types we need to recursively register/deregister base pointers for any
|
| 289 |
+
/// base classes with pointers that are difference from the instance value pointer so that we can
|
| 290 |
+
/// correctly recognize an offset base class pointer. This calls a function with any offset base
|
| 291 |
+
/// ptrs.
|
| 292 |
+
inline void traverse_offset_bases(void *valueptr,
|
| 293 |
+
const detail::type_info *tinfo,
|
| 294 |
+
instance *self,
|
| 295 |
+
bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
|
| 296 |
+
for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
|
| 297 |
+
if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
|
| 298 |
+
for (auto &c : parent_tinfo->implicit_casts) {
|
| 299 |
+
if (c.first == tinfo->cpptype) {
|
| 300 |
+
auto *parentptr = c.second(valueptr);
|
| 301 |
+
if (parentptr != valueptr) {
|
| 302 |
+
f(parentptr, self);
|
| 303 |
+
}
|
| 304 |
+
traverse_offset_bases(parentptr, parent_tinfo, self, f);
|
| 305 |
+
break;
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
inline bool register_instance_impl(void *ptr, instance *self) {
|
| 313 |
+
get_internals().registered_instances.emplace(ptr, self);
|
| 314 |
+
return true; // unused, but gives the same signature as the deregister func
|
| 315 |
+
}
|
| 316 |
+
inline bool deregister_instance_impl(void *ptr, instance *self) {
|
| 317 |
+
auto ®istered_instances = get_internals().registered_instances;
|
| 318 |
+
auto range = registered_instances.equal_range(ptr);
|
| 319 |
+
for (auto it = range.first; it != range.second; ++it) {
|
| 320 |
+
if (self == it->second) {
|
| 321 |
+
registered_instances.erase(it);
|
| 322 |
+
return true;
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
return false;
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
|
| 329 |
+
register_instance_impl(valptr, self);
|
| 330 |
+
if (!tinfo->simple_ancestors) {
|
| 331 |
+
traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
|
| 332 |
+
}
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
|
| 336 |
+
bool ret = deregister_instance_impl(valptr, self);
|
| 337 |
+
if (!tinfo->simple_ancestors) {
|
| 338 |
+
traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
|
| 339 |
+
}
|
| 340 |
+
return ret;
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
/// Instance creation function for all pybind11 types. It allocates the internal instance layout
|
| 344 |
+
/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
|
| 345 |
+
/// cast to a reference or pointer), and initialization is done by an `__init__` function.
|
| 346 |
+
inline PyObject *make_new_instance(PyTypeObject *type) {
|
| 347 |
+
#if defined(PYPY_VERSION)
|
| 348 |
+
// PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
|
| 349 |
+
// inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
|
| 350 |
+
ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
|
| 351 |
+
if (type->tp_basicsize < instance_size) {
|
| 352 |
+
type->tp_basicsize = instance_size;
|
| 353 |
+
}
|
| 354 |
+
#endif
|
| 355 |
+
PyObject *self = type->tp_alloc(type, 0);
|
| 356 |
+
auto *inst = reinterpret_cast<instance *>(self);
|
| 357 |
+
// Allocate the value/holder internals:
|
| 358 |
+
inst->allocate_layout();
|
| 359 |
+
|
| 360 |
+
return self;
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
/// Instance creation function for all pybind11 types. It only allocates space for the
|
| 364 |
+
/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
|
| 365 |
+
extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
|
| 366 |
+
return make_new_instance(type);
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
/// An `__init__` function constructs the C++ object. Users should provide at least one
|
| 370 |
+
/// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
|
| 371 |
+
/// following default function will be used which simply throws an exception.
|
| 372 |
+
extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
|
| 373 |
+
PyTypeObject *type = Py_TYPE(self);
|
| 374 |
+
std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
|
| 375 |
+
set_error(PyExc_TypeError, msg.c_str());
|
| 376 |
+
return -1;
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
inline void add_patient(PyObject *nurse, PyObject *patient) {
|
| 380 |
+
auto &internals = get_internals();
|
| 381 |
+
auto *instance = reinterpret_cast<detail::instance *>(nurse);
|
| 382 |
+
instance->has_patients = true;
|
| 383 |
+
Py_INCREF(patient);
|
| 384 |
+
internals.patients[nurse].push_back(patient);
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
inline void clear_patients(PyObject *self) {
|
| 388 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
| 389 |
+
auto &internals = get_internals();
|
| 390 |
+
auto pos = internals.patients.find(self);
|
| 391 |
+
assert(pos != internals.patients.end());
|
| 392 |
+
// Clearing the patients can cause more Python code to run, which
|
| 393 |
+
// can invalidate the iterator. Extract the vector of patients
|
| 394 |
+
// from the unordered_map first.
|
| 395 |
+
auto patients = std::move(pos->second);
|
| 396 |
+
internals.patients.erase(pos);
|
| 397 |
+
instance->has_patients = false;
|
| 398 |
+
for (PyObject *&patient : patients) {
|
| 399 |
+
Py_CLEAR(patient);
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
/// Clears all internal data from the instance and removes it from registered instances in
|
| 404 |
+
/// preparation for deallocation.
|
| 405 |
+
inline void clear_instance(PyObject *self) {
|
| 406 |
+
auto *instance = reinterpret_cast<detail::instance *>(self);
|
| 407 |
+
|
| 408 |
+
// Deallocate any values/holders, if present:
|
| 409 |
+
for (auto &v_h : values_and_holders(instance)) {
|
| 410 |
+
if (v_h) {
|
| 411 |
+
|
| 412 |
+
// We have to deregister before we call dealloc because, for virtual MI types, we still
|
| 413 |
+
// need to be able to get the parent pointers.
|
| 414 |
+
if (v_h.instance_registered()
|
| 415 |
+
&& !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
|
| 416 |
+
pybind11_fail(
|
| 417 |
+
"pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
if (instance->owned || v_h.holder_constructed()) {
|
| 421 |
+
v_h.type->dealloc(v_h);
|
| 422 |
+
}
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
// Deallocate the value/holder layout internals:
|
| 426 |
+
instance->deallocate_layout();
|
| 427 |
+
|
| 428 |
+
if (instance->weakrefs) {
|
| 429 |
+
PyObject_ClearWeakRefs(self);
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
PyObject **dict_ptr = _PyObject_GetDictPtr(self);
|
| 433 |
+
if (dict_ptr) {
|
| 434 |
+
Py_CLEAR(*dict_ptr);
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
if (instance->has_patients) {
|
| 438 |
+
clear_patients(self);
|
| 439 |
+
}
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
|
| 443 |
+
/// to destroy the C++ object itself, while the rest is Python bookkeeping.
|
| 444 |
+
extern "C" inline void pybind11_object_dealloc(PyObject *self) {
|
| 445 |
+
auto *type = Py_TYPE(self);
|
| 446 |
+
|
| 447 |
+
// If this is a GC tracked object, untrack it first
|
| 448 |
+
// Note that the track call is implicitly done by the
|
| 449 |
+
// default tp_alloc, which we never override.
|
| 450 |
+
if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
|
| 451 |
+
PyObject_GC_UnTrack(self);
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
clear_instance(self);
|
| 455 |
+
|
| 456 |
+
type->tp_free(self);
|
| 457 |
+
|
| 458 |
+
#if PY_VERSION_HEX < 0x03080000
|
| 459 |
+
// `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
|
| 460 |
+
// as part of a derived type's dealloc, in which case we're not allowed to decref
|
| 461 |
+
// the type here. For cross-module compatibility, we shouldn't compare directly
|
| 462 |
+
// with `pybind11_object_dealloc`, but with the common one stashed in internals.
|
| 463 |
+
auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
|
| 464 |
+
if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
|
| 465 |
+
Py_DECREF(type);
|
| 466 |
+
#else
|
| 467 |
+
// This was not needed before Python 3.8 (Python issue 35810)
|
| 468 |
+
// https://github.com/pybind/pybind11/issues/1946
|
| 469 |
+
Py_DECREF(type);
|
| 470 |
+
#endif
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
std::string error_string();
|
| 474 |
+
|
| 475 |
+
/** Create the type which can be used as a common base for all classes. This is
|
| 476 |
+
needed in order to satisfy Python's requirements for multiple inheritance.
|
| 477 |
+
Return value: New reference. */
|
| 478 |
+
inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
|
| 479 |
+
constexpr auto *name = "pybind11_object";
|
| 480 |
+
auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
|
| 481 |
+
|
| 482 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 483 |
+
issue no Python C API calls which could potentially invoke the
|
| 484 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 485 |
+
turn find the newly constructed type in an invalid state) */
|
| 486 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
| 487 |
+
if (!heap_type) {
|
| 488 |
+
pybind11_fail("make_object_base_type(): error allocating type!");
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
heap_type->ht_name = name_obj.inc_ref().ptr();
|
| 492 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
| 493 |
+
heap_type->ht_qualname = name_obj.inc_ref().ptr();
|
| 494 |
+
#endif
|
| 495 |
+
|
| 496 |
+
auto *type = &heap_type->ht_type;
|
| 497 |
+
type->tp_name = name;
|
| 498 |
+
type->tp_base = type_incref(&PyBaseObject_Type);
|
| 499 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
| 500 |
+
type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
|
| 501 |
+
|
| 502 |
+
type->tp_new = pybind11_object_new;
|
| 503 |
+
type->tp_init = pybind11_object_init;
|
| 504 |
+
type->tp_dealloc = pybind11_object_dealloc;
|
| 505 |
+
|
| 506 |
+
/* Support weak references (needed for the keep_alive feature) */
|
| 507 |
+
type->tp_weaklistoffset = offsetof(instance, weakrefs);
|
| 508 |
+
|
| 509 |
+
if (PyType_Ready(type) < 0) {
|
| 510 |
+
pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
|
| 514 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
|
| 515 |
+
|
| 516 |
+
assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
| 517 |
+
return (PyObject *) heap_type;
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
|
| 521 |
+
extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
|
| 522 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
| 523 |
+
PyObject_VisitManagedDict(self, visit, arg);
|
| 524 |
+
#else
|
| 525 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
| 526 |
+
Py_VISIT(dict);
|
| 527 |
+
#endif
|
| 528 |
+
// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
|
| 529 |
+
#if PY_VERSION_HEX >= 0x03090000
|
| 530 |
+
Py_VISIT(Py_TYPE(self));
|
| 531 |
+
#endif
|
| 532 |
+
return 0;
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
/// dynamic_attr: Allow the GC to clear the dictionary.
|
| 536 |
+
extern "C" inline int pybind11_clear(PyObject *self) {
|
| 537 |
+
#if PY_VERSION_HEX >= 0x030D0000
|
| 538 |
+
PyObject_ClearManagedDict(self);
|
| 539 |
+
#else
|
| 540 |
+
PyObject *&dict = *_PyObject_GetDictPtr(self);
|
| 541 |
+
Py_CLEAR(dict);
|
| 542 |
+
#endif
|
| 543 |
+
return 0;
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
/// Give instances of this type a `__dict__` and opt into garbage collection.
|
| 547 |
+
inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
|
| 548 |
+
auto *type = &heap_type->ht_type;
|
| 549 |
+
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
|
| 550 |
+
#if PY_VERSION_HEX < 0x030B0000
|
| 551 |
+
type->tp_dictoffset = type->tp_basicsize; // place dict at the end
|
| 552 |
+
type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
|
| 553 |
+
#else
|
| 554 |
+
type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
|
| 555 |
+
#endif
|
| 556 |
+
type->tp_traverse = pybind11_traverse;
|
| 557 |
+
type->tp_clear = pybind11_clear;
|
| 558 |
+
|
| 559 |
+
static PyGetSetDef getset[] = {{
|
| 560 |
+
#if PY_VERSION_HEX < 0x03070000
|
| 561 |
+
const_cast<char *>("__dict__"),
|
| 562 |
+
#else
|
| 563 |
+
"__dict__",
|
| 564 |
+
#endif
|
| 565 |
+
PyObject_GenericGetDict,
|
| 566 |
+
PyObject_GenericSetDict,
|
| 567 |
+
nullptr,
|
| 568 |
+
nullptr},
|
| 569 |
+
{nullptr, nullptr, nullptr, nullptr, nullptr}};
|
| 570 |
+
type->tp_getset = getset;
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
/// buffer_protocol: Fill in the view as specified by flags.
|
| 574 |
+
extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
|
| 575 |
+
// Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
|
| 576 |
+
type_info *tinfo = nullptr;
|
| 577 |
+
for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
|
| 578 |
+
tinfo = get_type_info((PyTypeObject *) type.ptr());
|
| 579 |
+
if (tinfo && tinfo->get_buffer) {
|
| 580 |
+
break;
|
| 581 |
+
}
|
| 582 |
+
}
|
| 583 |
+
if (view == nullptr || !tinfo || !tinfo->get_buffer) {
|
| 584 |
+
if (view) {
|
| 585 |
+
view->obj = nullptr;
|
| 586 |
+
}
|
| 587 |
+
set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
|
| 588 |
+
return -1;
|
| 589 |
+
}
|
| 590 |
+
std::memset(view, 0, sizeof(Py_buffer));
|
| 591 |
+
buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
|
| 592 |
+
if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
|
| 593 |
+
delete info;
|
| 594 |
+
// view->obj = nullptr; // Was just memset to 0, so not necessary
|
| 595 |
+
set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
|
| 596 |
+
return -1;
|
| 597 |
+
}
|
| 598 |
+
view->obj = obj;
|
| 599 |
+
view->ndim = 1;
|
| 600 |
+
view->internal = info;
|
| 601 |
+
view->buf = info->ptr;
|
| 602 |
+
view->itemsize = info->itemsize;
|
| 603 |
+
view->len = view->itemsize;
|
| 604 |
+
for (auto s : info->shape) {
|
| 605 |
+
view->len *= s;
|
| 606 |
+
}
|
| 607 |
+
view->readonly = static_cast<int>(info->readonly);
|
| 608 |
+
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
|
| 609 |
+
view->format = const_cast<char *>(info->format.c_str());
|
| 610 |
+
}
|
| 611 |
+
if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
|
| 612 |
+
view->ndim = (int) info->ndim;
|
| 613 |
+
view->strides = info->strides.data();
|
| 614 |
+
view->shape = info->shape.data();
|
| 615 |
+
}
|
| 616 |
+
Py_INCREF(view->obj);
|
| 617 |
+
return 0;
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
/// buffer_protocol: Release the resources of the buffer.
|
| 621 |
+
extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
|
| 622 |
+
delete (buffer_info *) view->internal;
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
/// Give this type a buffer interface.
|
| 626 |
+
inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
|
| 627 |
+
heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
|
| 628 |
+
|
| 629 |
+
heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
|
| 630 |
+
heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
/** Create a brand new Python type according to the `type_record` specification.
|
| 634 |
+
Return value: New reference. */
|
| 635 |
+
inline PyObject *make_new_python_type(const type_record &rec) {
|
| 636 |
+
auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
|
| 637 |
+
|
| 638 |
+
auto qualname = name;
|
| 639 |
+
if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
|
| 640 |
+
qualname = reinterpret_steal<object>(
|
| 641 |
+
PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
object module_;
|
| 645 |
+
if (rec.scope) {
|
| 646 |
+
if (hasattr(rec.scope, "__module__")) {
|
| 647 |
+
module_ = rec.scope.attr("__module__");
|
| 648 |
+
} else if (hasattr(rec.scope, "__name__")) {
|
| 649 |
+
module_ = rec.scope.attr("__name__");
|
| 650 |
+
}
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
const auto *full_name = c_str(
|
| 654 |
+
#if !defined(PYPY_VERSION)
|
| 655 |
+
module_ ? str(module_).cast<std::string>() + "." + rec.name :
|
| 656 |
+
#endif
|
| 657 |
+
rec.name);
|
| 658 |
+
|
| 659 |
+
char *tp_doc = nullptr;
|
| 660 |
+
if (rec.doc && options::show_user_defined_docstrings()) {
|
| 661 |
+
/* Allocate memory for docstring (using PyObject_MALLOC, since
|
| 662 |
+
Python will free this later on) */
|
| 663 |
+
size_t size = std::strlen(rec.doc) + 1;
|
| 664 |
+
tp_doc = (char *) PyObject_MALLOC(size);
|
| 665 |
+
std::memcpy((void *) tp_doc, rec.doc, size);
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
auto &internals = get_internals();
|
| 669 |
+
auto bases = tuple(rec.bases);
|
| 670 |
+
auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
|
| 671 |
+
|
| 672 |
+
/* Danger zone: from now (and until PyType_Ready), make sure to
|
| 673 |
+
issue no Python C API calls which could potentially invoke the
|
| 674 |
+
garbage collector (the GC will call type_traverse(), which will in
|
| 675 |
+
turn find the newly constructed type in an invalid state) */
|
| 676 |
+
auto *metaclass
|
| 677 |
+
= rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
|
| 678 |
+
|
| 679 |
+
auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
|
| 680 |
+
if (!heap_type) {
|
| 681 |
+
pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
heap_type->ht_name = name.release().ptr();
|
| 685 |
+
#ifdef PYBIND11_BUILTIN_QUALNAME
|
| 686 |
+
heap_type->ht_qualname = qualname.inc_ref().ptr();
|
| 687 |
+
#endif
|
| 688 |
+
|
| 689 |
+
auto *type = &heap_type->ht_type;
|
| 690 |
+
type->tp_name = full_name;
|
| 691 |
+
type->tp_doc = tp_doc;
|
| 692 |
+
type->tp_base = type_incref((PyTypeObject *) base);
|
| 693 |
+
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
|
| 694 |
+
if (!bases.empty()) {
|
| 695 |
+
type->tp_bases = bases.release().ptr();
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
/* Don't inherit base __init__ */
|
| 699 |
+
type->tp_init = pybind11_object_init;
|
| 700 |
+
|
| 701 |
+
/* Supported protocols */
|
| 702 |
+
type->tp_as_number = &heap_type->as_number;
|
| 703 |
+
type->tp_as_sequence = &heap_type->as_sequence;
|
| 704 |
+
type->tp_as_mapping = &heap_type->as_mapping;
|
| 705 |
+
type->tp_as_async = &heap_type->as_async;
|
| 706 |
+
|
| 707 |
+
/* Flags */
|
| 708 |
+
type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
|
| 709 |
+
if (!rec.is_final) {
|
| 710 |
+
type->tp_flags |= Py_TPFLAGS_BASETYPE;
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
if (rec.dynamic_attr) {
|
| 714 |
+
enable_dynamic_attributes(heap_type);
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
if (rec.buffer_protocol) {
|
| 718 |
+
enable_buffer_protocol(heap_type);
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
if (rec.custom_type_setup_callback) {
|
| 722 |
+
rec.custom_type_setup_callback(heap_type);
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
if (PyType_Ready(type) < 0) {
|
| 726 |
+
pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
|
| 730 |
+
|
| 731 |
+
/* Register type with the parent scope */
|
| 732 |
+
if (rec.scope) {
|
| 733 |
+
setattr(rec.scope, rec.name, (PyObject *) type);
|
| 734 |
+
} else {
|
| 735 |
+
Py_INCREF(type); // Keep it alive forever (reference leak)
|
| 736 |
+
}
|
| 737 |
+
|
| 738 |
+
if (module_) { // Needed by pydoc
|
| 739 |
+
setattr((PyObject *) type, "__module__", module_);
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
|
| 743 |
+
|
| 744 |
+
return (PyObject *) type;
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 748 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
data/home/.local/lib/python3.8/site-pack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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 12
|
| 14 |
+
#define PYBIND11_VERSION_PATCH 0
|
| 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 0x020C0000
|
| 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 |
+
#if defined(PYBIND11_CPP20)
|
| 122 |
+
# define PYBIND11_CONSTINIT constinit
|
| 123 |
+
# define PYBIND11_DTOR_CONSTEXPR constexpr
|
| 124 |
+
#else
|
| 125 |
+
# define PYBIND11_CONSTINIT
|
| 126 |
+
# define PYBIND11_DTOR_CONSTEXPR
|
| 127 |
+
#endif
|
| 128 |
+
|
| 129 |
+
// Compiler version assertions
|
| 130 |
+
#if defined(__INTEL_COMPILER)
|
| 131 |
+
# if __INTEL_COMPILER < 1800
|
| 132 |
+
# error pybind11 requires Intel C++ compiler v18 or newer
|
| 133 |
+
# elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
|
| 134 |
+
# error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
|
| 135 |
+
# endif
|
| 136 |
+
/* The following pragma cannot be pop'ed:
|
| 137 |
+
https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
|
| 138 |
+
# pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
|
| 139 |
+
#elif defined(__clang__) && !defined(__apple_build_version__)
|
| 140 |
+
# if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
|
| 141 |
+
# error pybind11 requires clang 3.3 or newer
|
| 142 |
+
# endif
|
| 143 |
+
#elif defined(__clang__)
|
| 144 |
+
// Apple changes clang version macros to its Xcode version; the first Xcode release based on
|
| 145 |
+
// (upstream) clang 3.3 was Xcode 5:
|
| 146 |
+
# if __clang_major__ < 5
|
| 147 |
+
# error pybind11 requires Xcode/clang 5.0 or newer
|
| 148 |
+
# endif
|
| 149 |
+
#elif defined(__GNUG__)
|
| 150 |
+
# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
|
| 151 |
+
# error pybind11 requires gcc 4.8 or newer
|
| 152 |
+
# endif
|
| 153 |
+
#elif defined(_MSC_VER)
|
| 154 |
+
# if _MSC_VER < 1910
|
| 155 |
+
# error pybind11 2.10+ requires MSVC 2017 or newer
|
| 156 |
+
# endif
|
| 157 |
+
#endif
|
| 158 |
+
|
| 159 |
+
#if !defined(PYBIND11_EXPORT)
|
| 160 |
+
# if defined(WIN32) || defined(_WIN32)
|
| 161 |
+
# define PYBIND11_EXPORT __declspec(dllexport)
|
| 162 |
+
# else
|
| 163 |
+
# define PYBIND11_EXPORT __attribute__((visibility("default")))
|
| 164 |
+
# endif
|
| 165 |
+
#endif
|
| 166 |
+
|
| 167 |
+
#if !defined(PYBIND11_EXPORT_EXCEPTION)
|
| 168 |
+
# if defined(__apple_build_version__)
|
| 169 |
+
# define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
|
| 170 |
+
# else
|
| 171 |
+
# define PYBIND11_EXPORT_EXCEPTION
|
| 172 |
+
# endif
|
| 173 |
+
#endif
|
| 174 |
+
|
| 175 |
+
// For CUDA, GCC7, GCC8:
|
| 176 |
+
// PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
|
| 177 |
+
// When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
|
| 178 |
+
// However, the measured shared-library size saving when using noinline are only
|
| 179 |
+
// 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
|
| 180 |
+
// the default under pybind11/tests).
|
| 181 |
+
#if !defined(PYBIND11_NOINLINE_FORCED) \
|
| 182 |
+
&& (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
|
| 183 |
+
# define PYBIND11_NOINLINE_DISABLED
|
| 184 |
+
#endif
|
| 185 |
+
|
| 186 |
+
// The PYBIND11_NOINLINE macro is for function DEFINITIONS.
|
| 187 |
+
// In contrast, FORWARD DECLARATIONS should never use this macro:
|
| 188 |
+
// https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
|
| 189 |
+
#if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
|
| 190 |
+
# define PYBIND11_NOINLINE inline
|
| 191 |
+
#elif defined(_MSC_VER)
|
| 192 |
+
# define PYBIND11_NOINLINE __declspec(noinline) inline
|
| 193 |
+
#else
|
| 194 |
+
# define PYBIND11_NOINLINE __attribute__((noinline)) inline
|
| 195 |
+
#endif
|
| 196 |
+
|
| 197 |
+
#if defined(__MINGW32__)
|
| 198 |
+
// For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
|
| 199 |
+
// whether it is used or not
|
| 200 |
+
# define PYBIND11_DEPRECATED(reason)
|
| 201 |
+
#elif defined(PYBIND11_CPP14)
|
| 202 |
+
# define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
|
| 203 |
+
#else
|
| 204 |
+
# define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
|
| 205 |
+
#endif
|
| 206 |
+
|
| 207 |
+
#if defined(PYBIND11_CPP17)
|
| 208 |
+
# define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
|
| 209 |
+
#elif defined(_MSC_VER) && !defined(__clang__)
|
| 210 |
+
# define PYBIND11_MAYBE_UNUSED
|
| 211 |
+
#else
|
| 212 |
+
# define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
|
| 213 |
+
#endif
|
| 214 |
+
|
| 215 |
+
/* Don't let Python.h #define (v)snprintf as macro because they are implemented
|
| 216 |
+
properly in Visual Studio since 2015. */
|
| 217 |
+
#if defined(_MSC_VER)
|
| 218 |
+
# define HAVE_SNPRINTF 1
|
| 219 |
+
#endif
|
| 220 |
+
|
| 221 |
+
/// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
|
| 222 |
+
#if defined(_MSC_VER)
|
| 223 |
+
PYBIND11_WARNING_PUSH
|
| 224 |
+
PYBIND11_WARNING_DISABLE_MSVC(4505)
|
| 225 |
+
// C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
|
| 226 |
+
# if defined(_DEBUG) && !defined(Py_DEBUG)
|
| 227 |
+
// Workaround for a VS 2022 issue.
|
| 228 |
+
// NOTE: This workaround knowingly violates the Python.h include order requirement:
|
| 229 |
+
// https://docs.python.org/3/c-api/intro.html#include-files
|
| 230 |
+
// See https://github.com/pybind/pybind11/pull/3497 for full context.
|
| 231 |
+
# include <yvals.h>
|
| 232 |
+
# if _MSVC_STL_VERSION >= 143
|
| 233 |
+
# include <crtdefs.h>
|
| 234 |
+
# endif
|
| 235 |
+
# define PYBIND11_DEBUG_MARKER
|
| 236 |
+
# undef _DEBUG
|
| 237 |
+
# endif
|
| 238 |
+
#endif
|
| 239 |
+
|
| 240 |
+
// https://en.cppreference.com/w/c/chrono/localtime
|
| 241 |
+
#if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
|
| 242 |
+
# define __STDC_WANT_LIB_EXT1__
|
| 243 |
+
#endif
|
| 244 |
+
|
| 245 |
+
#ifdef __has_include
|
| 246 |
+
// std::optional (but including it in c++14 mode isn't allowed)
|
| 247 |
+
# if defined(PYBIND11_CPP17) && __has_include(<optional>)
|
| 248 |
+
# define PYBIND11_HAS_OPTIONAL 1
|
| 249 |
+
# endif
|
| 250 |
+
// std::experimental::optional (but not allowed in c++11 mode)
|
| 251 |
+
# if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
|
| 252 |
+
!__has_include(<optional>))
|
| 253 |
+
# define PYBIND11_HAS_EXP_OPTIONAL 1
|
| 254 |
+
# endif
|
| 255 |
+
// std::variant
|
| 256 |
+
# if defined(PYBIND11_CPP17) && __has_include(<variant>)
|
| 257 |
+
# define PYBIND11_HAS_VARIANT 1
|
| 258 |
+
# endif
|
| 259 |
+
#elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
|
| 260 |
+
# define PYBIND11_HAS_OPTIONAL 1
|
| 261 |
+
# define PYBIND11_HAS_VARIANT 1
|
| 262 |
+
#endif
|
| 263 |
+
|
| 264 |
+
#if defined(PYBIND11_CPP17)
|
| 265 |
+
# if defined(__has_include)
|
| 266 |
+
# if __has_include(<string_view>)
|
| 267 |
+
# define PYBIND11_HAS_STRING_VIEW
|
| 268 |
+
# endif
|
| 269 |
+
# elif defined(_MSC_VER)
|
| 270 |
+
# define PYBIND11_HAS_STRING_VIEW
|
| 271 |
+
# endif
|
| 272 |
+
#endif
|
| 273 |
+
|
| 274 |
+
#include <Python.h>
|
| 275 |
+
// Reminder: WITH_THREAD is always defined if PY_VERSION_HEX >= 0x03070000
|
| 276 |
+
#if PY_VERSION_HEX < 0x03060000
|
| 277 |
+
# error "PYTHON < 3.6 IS UNSUPPORTED. pybind11 v2.9 was the last to support Python 2 and 3.5."
|
| 278 |
+
#endif
|
| 279 |
+
#include <frameobject.h>
|
| 280 |
+
#include <pythread.h>
|
| 281 |
+
|
| 282 |
+
/* Python #defines overrides on all sorts of core functions, which
|
| 283 |
+
tends to weak havok in C++ codebases that expect these to work
|
| 284 |
+
like regular functions (potentially with several overloads) */
|
| 285 |
+
#if defined(isalnum)
|
| 286 |
+
# undef isalnum
|
| 287 |
+
# undef isalpha
|
| 288 |
+
# undef islower
|
| 289 |
+
# undef isspace
|
| 290 |
+
# undef isupper
|
| 291 |
+
# undef tolower
|
| 292 |
+
# undef toupper
|
| 293 |
+
#endif
|
| 294 |
+
|
| 295 |
+
#if defined(copysign)
|
| 296 |
+
# undef copysign
|
| 297 |
+
#endif
|
| 298 |
+
|
| 299 |
+
#if defined(PYBIND11_NUMPY_1_ONLY)
|
| 300 |
+
# define PYBIND11_INTERNAL_NUMPY_1_ONLY_DETECTED
|
| 301 |
+
#endif
|
| 302 |
+
|
| 303 |
+
#if defined(PYPY_VERSION) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
|
| 304 |
+
# define PYBIND11_SIMPLE_GIL_MANAGEMENT
|
| 305 |
+
#endif
|
| 306 |
+
|
| 307 |
+
#if defined(_MSC_VER)
|
| 308 |
+
# if defined(PYBIND11_DEBUG_MARKER)
|
| 309 |
+
# define _DEBUG
|
| 310 |
+
# undef PYBIND11_DEBUG_MARKER
|
| 311 |
+
# endif
|
| 312 |
+
PYBIND11_WARNING_POP
|
| 313 |
+
#endif
|
| 314 |
+
|
| 315 |
+
#include <cstddef>
|
| 316 |
+
#include <cstring>
|
| 317 |
+
#include <exception>
|
| 318 |
+
#include <forward_list>
|
| 319 |
+
#include <memory>
|
| 320 |
+
#include <stdexcept>
|
| 321 |
+
#include <string>
|
| 322 |
+
#include <type_traits>
|
| 323 |
+
#include <typeindex>
|
| 324 |
+
#include <unordered_map>
|
| 325 |
+
#include <unordered_set>
|
| 326 |
+
#include <vector>
|
| 327 |
+
#if defined(__has_include)
|
| 328 |
+
# if __has_include(<version>)
|
| 329 |
+
# include <version>
|
| 330 |
+
# endif
|
| 331 |
+
#endif
|
| 332 |
+
|
| 333 |
+
// Must be after including <version> or one of the other headers specified by the standard
|
| 334 |
+
#if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
|
| 335 |
+
# define PYBIND11_HAS_U8STRING
|
| 336 |
+
#endif
|
| 337 |
+
|
| 338 |
+
// See description of PR #4246:
|
| 339 |
+
#if !defined(PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF) && !defined(NDEBUG) \
|
| 340 |
+
&& !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
|
| 341 |
+
# define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
|
| 342 |
+
#endif
|
| 343 |
+
|
| 344 |
+
// #define PYBIND11_STR_LEGACY_PERMISSIVE
|
| 345 |
+
// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
|
| 346 |
+
// (probably surprising and never documented, but this was the
|
| 347 |
+
// legacy behavior until and including v2.6.x). As a side-effect,
|
| 348 |
+
// pybind11::isinstance<str>() is true for both pybind11::str and
|
| 349 |
+
// pybind11::bytes.
|
| 350 |
+
// If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
|
| 351 |
+
// pybind11::isinstance<str>() is true only for pybind11::str.
|
| 352 |
+
// However, for Python 2 only (!), the pybind11::str caster
|
| 353 |
+
// implicitly decoded bytes to PyUnicodeObject. This was to ease
|
| 354 |
+
// the transition from the legacy behavior to the non-permissive
|
| 355 |
+
// behavior.
|
| 356 |
+
|
| 357 |
+
/// Compatibility macros for Python 2 / Python 3 versions TODO: remove
|
| 358 |
+
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
|
| 359 |
+
#define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
|
| 360 |
+
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
|
| 361 |
+
#define PYBIND11_BYTES_CHECK PyBytes_Check
|
| 362 |
+
#define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
|
| 363 |
+
#define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
|
| 364 |
+
#define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
|
| 365 |
+
#define PYBIND11_BYTES_AS_STRING PyBytes_AsString
|
| 366 |
+
#define PYBIND11_BYTES_SIZE PyBytes_Size
|
| 367 |
+
#define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
|
| 368 |
+
#define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
|
| 369 |
+
#define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
|
| 370 |
+
#define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
|
| 371 |
+
#define PYBIND11_BYTES_NAME "bytes"
|
| 372 |
+
#define PYBIND11_STRING_NAME "str"
|
| 373 |
+
#define PYBIND11_SLICE_OBJECT PyObject
|
| 374 |
+
#define PYBIND11_FROM_STRING PyUnicode_FromString
|
| 375 |
+
#define PYBIND11_STR_TYPE ::pybind11::str
|
| 376 |
+
#define PYBIND11_BOOL_ATTR "__bool__"
|
| 377 |
+
#define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
|
| 378 |
+
#define PYBIND11_BUILTINS_MODULE "builtins"
|
| 379 |
+
// Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
|
| 380 |
+
// See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
|
| 381 |
+
#define PYBIND11_PLUGIN_IMPL(name) \
|
| 382 |
+
extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
|
| 383 |
+
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
|
| 384 |
+
|
| 385 |
+
#define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
|
| 386 |
+
#define PYBIND11_STRINGIFY(x) #x
|
| 387 |
+
#define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
|
| 388 |
+
#define PYBIND11_CONCAT(first, second) first##second
|
| 389 |
+
#define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
|
| 390 |
+
|
| 391 |
+
#define PYBIND11_CHECK_PYTHON_VERSION \
|
| 392 |
+
{ \
|
| 393 |
+
const char *compiled_ver \
|
| 394 |
+
= PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
|
| 395 |
+
const char *runtime_ver = Py_GetVersion(); \
|
| 396 |
+
size_t len = std::strlen(compiled_ver); \
|
| 397 |
+
if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
|
| 398 |
+
|| (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
|
| 399 |
+
PyErr_Format(PyExc_ImportError, \
|
| 400 |
+
"Python version mismatch: module was compiled for Python %s, " \
|
| 401 |
+
"but the interpreter version is incompatible: %s.", \
|
| 402 |
+
compiled_ver, \
|
| 403 |
+
runtime_ver); \
|
| 404 |
+
return nullptr; \
|
| 405 |
+
} \
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
#define PYBIND11_CATCH_INIT_EXCEPTIONS \
|
| 409 |
+
catch (pybind11::error_already_set & e) { \
|
| 410 |
+
pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
|
| 411 |
+
return nullptr; \
|
| 412 |
+
} \
|
| 413 |
+
catch (const std::exception &e) { \
|
| 414 |
+
::pybind11::set_error(PyExc_ImportError, e.what()); \
|
| 415 |
+
return nullptr; \
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
/** \rst
|
| 419 |
+
***Deprecated in favor of PYBIND11_MODULE***
|
| 420 |
+
|
| 421 |
+
This macro creates the entry point that will be invoked when the Python interpreter
|
| 422 |
+
imports a plugin library. Please create a `module_` in the function body and return
|
| 423 |
+
the pointer to its underlying Python object at the end.
|
| 424 |
+
|
| 425 |
+
.. code-block:: cpp
|
| 426 |
+
|
| 427 |
+
PYBIND11_PLUGIN(example) {
|
| 428 |
+
pybind11::module_ m("example", "pybind11 example plugin");
|
| 429 |
+
/// Set up bindings here
|
| 430 |
+
return m.ptr();
|
| 431 |
+
}
|
| 432 |
+
\endrst */
|
| 433 |
+
#define PYBIND11_PLUGIN(name) \
|
| 434 |
+
PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
|
| 435 |
+
static PyObject *pybind11_init(); \
|
| 436 |
+
PYBIND11_PLUGIN_IMPL(name) { \
|
| 437 |
+
PYBIND11_CHECK_PYTHON_VERSION \
|
| 438 |
+
PYBIND11_ENSURE_INTERNALS_READY \
|
| 439 |
+
try { \
|
| 440 |
+
return pybind11_init(); \
|
| 441 |
+
} \
|
| 442 |
+
PYBIND11_CATCH_INIT_EXCEPTIONS \
|
| 443 |
+
} \
|
| 444 |
+
PyObject *pybind11_init()
|
| 445 |
+
|
| 446 |
+
/** \rst
|
| 447 |
+
This macro creates the entry point that will be invoked when the Python interpreter
|
| 448 |
+
imports an extension module. The module name is given as the first argument and it
|
| 449 |
+
should not be in quotes. The second macro argument defines a variable of type
|
| 450 |
+
`py::module_` which can be used to initialize the module.
|
| 451 |
+
|
| 452 |
+
The entry point is marked as "maybe unused" to aid dead-code detection analysis:
|
| 453 |
+
since the entry point is typically only looked up at runtime and not referenced
|
| 454 |
+
during translation, it would otherwise appear as unused ("dead") code.
|
| 455 |
+
|
| 456 |
+
.. code-block:: cpp
|
| 457 |
+
|
| 458 |
+
PYBIND11_MODULE(example, m) {
|
| 459 |
+
m.doc() = "pybind11 example module";
|
| 460 |
+
|
| 461 |
+
// Add bindings here
|
| 462 |
+
m.def("foo", []() {
|
| 463 |
+
return "Hello, World!";
|
| 464 |
+
});
|
| 465 |
+
}
|
| 466 |
+
\endrst */
|
| 467 |
+
#define PYBIND11_MODULE(name, variable) \
|
| 468 |
+
static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
|
| 469 |
+
PYBIND11_MAYBE_UNUSED; \
|
| 470 |
+
PYBIND11_MAYBE_UNUSED \
|
| 471 |
+
static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
|
| 472 |
+
PYBIND11_PLUGIN_IMPL(name) { \
|
| 473 |
+
PYBIND11_CHECK_PYTHON_VERSION \
|
| 474 |
+
PYBIND11_ENSURE_INTERNALS_READY \
|
| 475 |
+
auto m = ::pybind11::module_::create_extension_module( \
|
| 476 |
+
PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
|
| 477 |
+
try { \
|
| 478 |
+
PYBIND11_CONCAT(pybind11_init_, name)(m); \
|
| 479 |
+
return m.ptr(); \
|
| 480 |
+
} \
|
| 481 |
+
PYBIND11_CATCH_INIT_EXCEPTIONS \
|
| 482 |
+
} \
|
| 483 |
+
void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
|
| 484 |
+
|
| 485 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
| 486 |
+
|
| 487 |
+
using ssize_t = Py_ssize_t;
|
| 488 |
+
using size_t = std::size_t;
|
| 489 |
+
|
| 490 |
+
template <typename IntType>
|
| 491 |
+
inline ssize_t ssize_t_cast(const IntType &val) {
|
| 492 |
+
static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
|
| 493 |
+
return static_cast<ssize_t>(val);
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
/// Approach used to cast a previously unknown C++ instance into a Python object
|
| 497 |
+
enum class return_value_policy : uint8_t {
|
| 498 |
+
/** This is the default return value policy, which falls back to the policy
|
| 499 |
+
return_value_policy::take_ownership when the return value is a pointer.
|
| 500 |
+
Otherwise, it uses return_value::move or return_value::copy for rvalue
|
| 501 |
+
and lvalue references, respectively. See below for a description of what
|
| 502 |
+
all of these different policies do. */
|
| 503 |
+
automatic = 0,
|
| 504 |
+
|
| 505 |
+
/** As above, but use policy return_value_policy::reference when the return
|
| 506 |
+
value is a pointer. This is the default conversion policy for function
|
| 507 |
+
arguments when calling Python functions manually from C++ code (i.e. via
|
| 508 |
+
handle::operator()). You probably won't need to use this. */
|
| 509 |
+
automatic_reference,
|
| 510 |
+
|
| 511 |
+
/** Reference an existing object (i.e. do not create a new copy) and take
|
| 512 |
+
ownership. Python will call the destructor and delete operator when the
|
| 513 |
+
object's reference count reaches zero. Undefined behavior ensues when
|
| 514 |
+
the C++ side does the same.. */
|
| 515 |
+
take_ownership,
|
| 516 |
+
|
| 517 |
+
/** Create a new copy of the returned object, which will be owned by
|
| 518 |
+
Python. This policy is comparably safe because the lifetimes of the two
|
| 519 |
+
instances are decoupled. */
|
| 520 |
+
copy,
|
| 521 |
+
|
| 522 |
+
/** Use std::move to move the return value contents into a new instance
|
| 523 |
+
that will be owned by Python. This policy is comparably safe because the
|
| 524 |
+
lifetimes of the two instances (move source and destination) are
|
| 525 |
+
decoupled. */
|
| 526 |
+
move,
|
| 527 |
+
|
| 528 |
+
/** Reference an existing object, but do not take ownership. The C++ side
|
| 529 |
+
is responsible for managing the object's lifetime and deallocating it
|
| 530 |
+
when it is no longer used. Warning: undefined behavior will ensue when
|
| 531 |
+
the C++ side deletes an object that is still referenced and used by
|
| 532 |
+
Python. */
|
| 533 |
+
reference,
|
| 534 |
+
|
| 535 |
+
/** This policy only applies to methods and properties. It references the
|
| 536 |
+
object without taking ownership similar to the above
|
| 537 |
+
return_value_policy::reference policy. In contrast to that policy, the
|
| 538 |
+
function or property's implicit this argument (called the parent) is
|
| 539 |
+
considered to be the the owner of the return value (the child).
|
| 540 |
+
pybind11 then couples the lifetime of the parent to the child via a
|
| 541 |
+
reference relationship that ensures that the parent cannot be garbage
|
| 542 |
+
collected while Python is still using the child. More advanced
|
| 543 |
+
variations of this scheme are also possible using combinations of
|
| 544 |
+
return_value_policy::reference and the keep_alive call policy */
|
| 545 |
+
reference_internal
|
| 546 |
+
};
|
| 547 |
+
|
| 548 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 549 |
+
|
| 550 |
+
inline static constexpr int log2(size_t n, int k = 0) {
|
| 551 |
+
return (n <= 1) ? k : log2(n >> 1, k + 1);
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
// Returns the size as a multiple of sizeof(void *), rounded up.
|
| 555 |
+
inline static constexpr size_t size_in_ptrs(size_t s) {
|
| 556 |
+
return 1 + ((s - 1) >> log2(sizeof(void *)));
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
/**
|
| 560 |
+
* The space to allocate for simple layout instance holders (see below) in multiple of the size of
|
| 561 |
+
* a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
|
| 562 |
+
* to holder either a std::unique_ptr or std::shared_ptr (which is almost always
|
| 563 |
+
* sizeof(std::shared_ptr<T>)).
|
| 564 |
+
*/
|
| 565 |
+
constexpr size_t instance_simple_holder_in_ptrs() {
|
| 566 |
+
static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
|
| 567 |
+
"pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
|
| 568 |
+
return size_in_ptrs(sizeof(std::shared_ptr<int>));
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
// Forward declarations
|
| 572 |
+
struct type_info;
|
| 573 |
+
struct value_and_holder;
|
| 574 |
+
|
| 575 |
+
struct nonsimple_values_and_holders {
|
| 576 |
+
void **values_and_holders;
|
| 577 |
+
uint8_t *status;
|
| 578 |
+
};
|
| 579 |
+
|
| 580 |
+
/// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
|
| 581 |
+
struct instance {
|
| 582 |
+
PyObject_HEAD
|
| 583 |
+
/// Storage for pointers and holder; see simple_layout, below, for a description
|
| 584 |
+
union {
|
| 585 |
+
void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
|
| 586 |
+
nonsimple_values_and_holders nonsimple;
|
| 587 |
+
};
|
| 588 |
+
/// Weak references
|
| 589 |
+
PyObject *weakrefs;
|
| 590 |
+
/// If true, the pointer is owned which means we're free to manage it with a holder.
|
| 591 |
+
bool owned : 1;
|
| 592 |
+
/**
|
| 593 |
+
* An instance has two possible value/holder layouts.
|
| 594 |
+
*
|
| 595 |
+
* Simple layout (when this flag is true), means the `simple_value_holder` is set with a
|
| 596 |
+
* pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
|
| 597 |
+
* applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
|
| 598 |
+
* type's holder will fit in the default space (which is large enough to hold either a
|
| 599 |
+
* std::unique_ptr or std::shared_ptr).
|
| 600 |
+
*
|
| 601 |
+
* Non-simple layout applies when using custom holders that require more space than
|
| 602 |
+
* `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
|
| 603 |
+
* used on the python side. Non-simple layout allocates the required amount of memory to have
|
| 604 |
+
* multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
|
| 605 |
+
* set to a pointer to allocated space of the required space to hold a sequence of value
|
| 606 |
+
* pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
|
| 607 |
+
* [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
|
| 608 |
+
* of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
|
| 609 |
+
* the [bb...] block (but not independently allocated).
|
| 610 |
+
*
|
| 611 |
+
* Status bits indicate whether the associated holder is constructed (&
|
| 612 |
+
* status_holder_constructed) and whether the value pointer is registered (&
|
| 613 |
+
* status_instance_registered) in `registered_instances`.
|
| 614 |
+
*/
|
| 615 |
+
bool simple_layout : 1;
|
| 616 |
+
/// For simple layout, tracks whether the holder has been constructed
|
| 617 |
+
bool simple_holder_constructed : 1;
|
| 618 |
+
/// For simple layout, tracks whether the instance is registered in `registered_instances`
|
| 619 |
+
bool simple_instance_registered : 1;
|
| 620 |
+
/// If true, get_internals().patients has an entry for this object
|
| 621 |
+
bool has_patients : 1;
|
| 622 |
+
|
| 623 |
+
/// Initializes all of the above type/values/holders data (but not the instance values
|
| 624 |
+
/// themselves)
|
| 625 |
+
void allocate_layout();
|
| 626 |
+
|
| 627 |
+
/// Destroys/deallocates all of the above
|
| 628 |
+
void deallocate_layout();
|
| 629 |
+
|
| 630 |
+
/// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
|
| 631 |
+
/// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
|
| 632 |
+
/// `throw_if_missing` is false.
|
| 633 |
+
value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
|
| 634 |
+
bool throw_if_missing = true);
|
| 635 |
+
|
| 636 |
+
/// Bit values for the non-simple status flags
|
| 637 |
+
static constexpr uint8_t status_holder_constructed = 1;
|
| 638 |
+
static constexpr uint8_t status_instance_registered = 2;
|
| 639 |
+
};
|
| 640 |
+
|
| 641 |
+
static_assert(std::is_standard_layout<instance>::value,
|
| 642 |
+
"Internal error: `pybind11::detail::instance` is not standard layout!");
|
| 643 |
+
|
| 644 |
+
/// from __cpp_future__ import (convenient aliases from C++14/17)
|
| 645 |
+
#if defined(PYBIND11_CPP14)
|
| 646 |
+
using std::conditional_t;
|
| 647 |
+
using std::enable_if_t;
|
| 648 |
+
using std::remove_cv_t;
|
| 649 |
+
using std::remove_reference_t;
|
| 650 |
+
#else
|
| 651 |
+
template <bool B, typename T = void>
|
| 652 |
+
using enable_if_t = typename std::enable_if<B, T>::type;
|
| 653 |
+
template <bool B, typename T, typename F>
|
| 654 |
+
using conditional_t = typename std::conditional<B, T, F>::type;
|
| 655 |
+
template <typename T>
|
| 656 |
+
using remove_cv_t = typename std::remove_cv<T>::type;
|
| 657 |
+
template <typename T>
|
| 658 |
+
using remove_reference_t = typename std::remove_reference<T>::type;
|
| 659 |
+
#endif
|
| 660 |
+
|
| 661 |
+
#if defined(PYBIND11_CPP20)
|
| 662 |
+
using std::remove_cvref;
|
| 663 |
+
using std::remove_cvref_t;
|
| 664 |
+
#else
|
| 665 |
+
template <class T>
|
| 666 |
+
struct remove_cvref {
|
| 667 |
+
using type = remove_cv_t<remove_reference_t<T>>;
|
| 668 |
+
};
|
| 669 |
+
template <class T>
|
| 670 |
+
using remove_cvref_t = typename remove_cvref<T>::type;
|
| 671 |
+
#endif
|
| 672 |
+
|
| 673 |
+
/// Example usage: is_same_ignoring_cvref<T, PyObject *>::value
|
| 674 |
+
template <typename T, typename U>
|
| 675 |
+
using is_same_ignoring_cvref = std::is_same<detail::remove_cvref_t<T>, U>;
|
| 676 |
+
|
| 677 |
+
/// Index sequences
|
| 678 |
+
#if defined(PYBIND11_CPP14)
|
| 679 |
+
using std::index_sequence;
|
| 680 |
+
using std::make_index_sequence;
|
| 681 |
+
#else
|
| 682 |
+
template <size_t...>
|
| 683 |
+
struct index_sequence {};
|
| 684 |
+
template <size_t N, size_t... S>
|
| 685 |
+
struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
|
| 686 |
+
template <size_t... S>
|
| 687 |
+
struct make_index_sequence_impl<0, S...> {
|
| 688 |
+
using type = index_sequence<S...>;
|
| 689 |
+
};
|
| 690 |
+
template <size_t N>
|
| 691 |
+
using make_index_sequence = typename make_index_sequence_impl<N>::type;
|
| 692 |
+
#endif
|
| 693 |
+
|
| 694 |
+
/// Make an index sequence of the indices of true arguments
|
| 695 |
+
template <typename ISeq, size_t, bool...>
|
| 696 |
+
struct select_indices_impl {
|
| 697 |
+
using type = ISeq;
|
| 698 |
+
};
|
| 699 |
+
template <size_t... IPrev, size_t I, bool B, bool... Bs>
|
| 700 |
+
struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
|
| 701 |
+
: select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
|
| 702 |
+
I + 1,
|
| 703 |
+
Bs...> {};
|
| 704 |
+
template <bool... Bs>
|
| 705 |
+
using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
|
| 706 |
+
|
| 707 |
+
/// Backports of std::bool_constant and std::negation to accommodate older compilers
|
| 708 |
+
template <bool B>
|
| 709 |
+
using bool_constant = std::integral_constant<bool, B>;
|
| 710 |
+
template <typename T>
|
| 711 |
+
struct negation : bool_constant<!T::value> {};
|
| 712 |
+
|
| 713 |
+
// PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
|
| 714 |
+
// using the new one (C++14 defect, so generally works on newer compilers, even
|
| 715 |
+
// if not in C++17 mode)
|
| 716 |
+
#if defined(__PGIC__) || defined(__INTEL_COMPILER)
|
| 717 |
+
template <typename...>
|
| 718 |
+
using void_t = void;
|
| 719 |
+
#else
|
| 720 |
+
template <typename...>
|
| 721 |
+
struct void_t_impl {
|
| 722 |
+
using type = void;
|
| 723 |
+
};
|
| 724 |
+
template <typename... Ts>
|
| 725 |
+
using void_t = typename void_t_impl<Ts...>::type;
|
| 726 |
+
#endif
|
| 727 |
+
|
| 728 |
+
/// Compile-time all/any/none of that check the boolean value of all template types
|
| 729 |
+
#if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
|
| 730 |
+
template <class... Ts>
|
| 731 |
+
using all_of = bool_constant<(Ts::value && ...)>;
|
| 732 |
+
template <class... Ts>
|
| 733 |
+
using any_of = bool_constant<(Ts::value || ...)>;
|
| 734 |
+
#elif !defined(_MSC_VER)
|
| 735 |
+
template <bool...>
|
| 736 |
+
struct bools {};
|
| 737 |
+
template <class... Ts>
|
| 738 |
+
using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
|
| 739 |
+
template <class... Ts>
|
| 740 |
+
using any_of = negation<all_of<negation<Ts>...>>;
|
| 741 |
+
#else
|
| 742 |
+
// MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
|
| 743 |
+
// at a slight loss of compilation efficiency).
|
| 744 |
+
template <class... Ts>
|
| 745 |
+
using all_of = std::conjunction<Ts...>;
|
| 746 |
+
template <class... Ts>
|
| 747 |
+
using any_of = std::disjunction<Ts...>;
|
| 748 |
+
#endif
|
| 749 |
+
template <class... Ts>
|
| 750 |
+
using none_of = negation<any_of<Ts...>>;
|
| 751 |
+
|
| 752 |
+
template <class T, template <class> class... Predicates>
|
| 753 |
+
using satisfies_all_of = all_of<Predicates<T>...>;
|
| 754 |
+
template <class T, template <class> class... Predicates>
|
| 755 |
+
using satisfies_any_of = any_of<Predicates<T>...>;
|
| 756 |
+
template <class T, template <class> class... Predicates>
|
| 757 |
+
using satisfies_none_of = none_of<Predicates<T>...>;
|
| 758 |
+
|
| 759 |
+
/// Strip the class from a method type
|
| 760 |
+
template <typename T>
|
| 761 |
+
struct remove_class {};
|
| 762 |
+
template <typename C, typename R, typename... A>
|
| 763 |
+
struct remove_class<R (C::*)(A...)> {
|
| 764 |
+
using type = R(A...);
|
| 765 |
+
};
|
| 766 |
+
template <typename C, typename R, typename... A>
|
| 767 |
+
struct remove_class<R (C::*)(A...) const> {
|
| 768 |
+
using type = R(A...);
|
| 769 |
+
};
|
| 770 |
+
#ifdef __cpp_noexcept_function_type
|
| 771 |
+
template <typename C, typename R, typename... A>
|
| 772 |
+
struct remove_class<R (C::*)(A...) noexcept> {
|
| 773 |
+
using type = R(A...);
|
| 774 |
+
};
|
| 775 |
+
template <typename C, typename R, typename... A>
|
| 776 |
+
struct remove_class<R (C::*)(A...) const noexcept> {
|
| 777 |
+
using type = R(A...);
|
| 778 |
+
};
|
| 779 |
+
#endif
|
| 780 |
+
/// Helper template to strip away type modifiers
|
| 781 |
+
template <typename T>
|
| 782 |
+
struct intrinsic_type {
|
| 783 |
+
using type = T;
|
| 784 |
+
};
|
| 785 |
+
template <typename T>
|
| 786 |
+
struct intrinsic_type<const T> {
|
| 787 |
+
using type = typename intrinsic_type<T>::type;
|
| 788 |
+
};
|
| 789 |
+
template <typename T>
|
| 790 |
+
struct intrinsic_type<T *> {
|
| 791 |
+
using type = typename intrinsic_type<T>::type;
|
| 792 |
+
};
|
| 793 |
+
template <typename T>
|
| 794 |
+
struct intrinsic_type<T &> {
|
| 795 |
+
using type = typename intrinsic_type<T>::type;
|
| 796 |
+
};
|
| 797 |
+
template <typename T>
|
| 798 |
+
struct intrinsic_type<T &&> {
|
| 799 |
+
using type = typename intrinsic_type<T>::type;
|
| 800 |
+
};
|
| 801 |
+
template <typename T, size_t N>
|
| 802 |
+
struct intrinsic_type<const T[N]> {
|
| 803 |
+
using type = typename intrinsic_type<T>::type;
|
| 804 |
+
};
|
| 805 |
+
template <typename T, size_t N>
|
| 806 |
+
struct intrinsic_type<T[N]> {
|
| 807 |
+
using type = typename intrinsic_type<T>::type;
|
| 808 |
+
};
|
| 809 |
+
template <typename T>
|
| 810 |
+
using intrinsic_t = typename intrinsic_type<T>::type;
|
| 811 |
+
|
| 812 |
+
/// Helper type to replace 'void' in some expressions
|
| 813 |
+
struct void_type {};
|
| 814 |
+
|
| 815 |
+
/// Helper template which holds a list of types
|
| 816 |
+
template <typename...>
|
| 817 |
+
struct type_list {};
|
| 818 |
+
|
| 819 |
+
/// Compile-time integer sum
|
| 820 |
+
#ifdef __cpp_fold_expressions
|
| 821 |
+
template <typename... Ts>
|
| 822 |
+
constexpr size_t constexpr_sum(Ts... ns) {
|
| 823 |
+
return (0 + ... + size_t{ns});
|
| 824 |
+
}
|
| 825 |
+
#else
|
| 826 |
+
constexpr size_t constexpr_sum() { return 0; }
|
| 827 |
+
template <typename T, typename... Ts>
|
| 828 |
+
constexpr size_t constexpr_sum(T n, Ts... ns) {
|
| 829 |
+
return size_t{n} + constexpr_sum(ns...);
|
| 830 |
+
}
|
| 831 |
+
#endif
|
| 832 |
+
|
| 833 |
+
PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
|
| 834 |
+
/// Implementation details for constexpr functions
|
| 835 |
+
constexpr int first(int i) { return i; }
|
| 836 |
+
template <typename T, typename... Ts>
|
| 837 |
+
constexpr int first(int i, T v, Ts... vs) {
|
| 838 |
+
return v ? i : first(i + 1, vs...);
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
constexpr int last(int /*i*/, int result) { return result; }
|
| 842 |
+
template <typename T, typename... Ts>
|
| 843 |
+
constexpr int last(int i, int result, T v, Ts... vs) {
|
| 844 |
+
return last(i + 1, v ? i : result, vs...);
|
| 845 |
+
}
|
| 846 |
+
PYBIND11_NAMESPACE_END(constexpr_impl)
|
| 847 |
+
|
| 848 |
+
/// Return the index of the first type in Ts which satisfies Predicate<T>.
|
| 849 |
+
/// Returns sizeof...(Ts) if none match.
|
| 850 |
+
template <template <typename> class Predicate, typename... Ts>
|
| 851 |
+
constexpr int constexpr_first() {
|
| 852 |
+
return constexpr_impl::first(0, Predicate<Ts>::value...);
|
| 853 |
+
}
|
| 854 |
+
|
| 855 |
+
/// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
|
| 856 |
+
template <template <typename> class Predicate, typename... Ts>
|
| 857 |
+
constexpr int constexpr_last() {
|
| 858 |
+
return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
|
| 859 |
+
}
|
| 860 |
+
|
| 861 |
+
/// Return the Nth element from the parameter pack
|
| 862 |
+
template <size_t N, typename T, typename... Ts>
|
| 863 |
+
struct pack_element {
|
| 864 |
+
using type = typename pack_element<N - 1, Ts...>::type;
|
| 865 |
+
};
|
| 866 |
+
template <typename T, typename... Ts>
|
| 867 |
+
struct pack_element<0, T, Ts...> {
|
| 868 |
+
using type = T;
|
| 869 |
+
};
|
| 870 |
+
|
| 871 |
+
/// Return the one and only type which matches the predicate, or Default if none match.
|
| 872 |
+
/// If more than one type matches the predicate, fail at compile-time.
|
| 873 |
+
template <template <typename> class Predicate, typename Default, typename... Ts>
|
| 874 |
+
struct exactly_one {
|
| 875 |
+
static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
|
| 876 |
+
static_assert(found <= 1, "Found more than one type matching the predicate");
|
| 877 |
+
|
| 878 |
+
static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
|
| 879 |
+
using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
|
| 880 |
+
};
|
| 881 |
+
template <template <typename> class P, typename Default>
|
| 882 |
+
struct exactly_one<P, Default> {
|
| 883 |
+
using type = Default;
|
| 884 |
+
};
|
| 885 |
+
|
| 886 |
+
template <template <typename> class Predicate, typename Default, typename... Ts>
|
| 887 |
+
using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
|
| 888 |
+
|
| 889 |
+
/// Defer the evaluation of type T until types Us are instantiated
|
| 890 |
+
template <typename T, typename... /*Us*/>
|
| 891 |
+
struct deferred_type {
|
| 892 |
+
using type = T;
|
| 893 |
+
};
|
| 894 |
+
template <typename T, typename... Us>
|
| 895 |
+
using deferred_t = typename deferred_type<T, Us...>::type;
|
| 896 |
+
|
| 897 |
+
/// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
|
| 898 |
+
/// unlike `std::is_base_of`)
|
| 899 |
+
template <typename Base, typename Derived>
|
| 900 |
+
using is_strict_base_of
|
| 901 |
+
= bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
|
| 902 |
+
|
| 903 |
+
/// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
|
| 904 |
+
/// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
|
| 905 |
+
/// we need to check `is_same` as well.
|
| 906 |
+
template <typename Base, typename Derived>
|
| 907 |
+
using is_accessible_base_of
|
| 908 |
+
= bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
|
| 909 |
+
&& std::is_convertible<Derived *, Base *>::value>;
|
| 910 |
+
|
| 911 |
+
template <template <typename...> class Base>
|
| 912 |
+
struct is_template_base_of_impl {
|
| 913 |
+
template <typename... Us>
|
| 914 |
+
static std::true_type check(Base<Us...> *);
|
| 915 |
+
static std::false_type check(...);
|
| 916 |
+
};
|
| 917 |
+
|
| 918 |
+
/// Check if a template is the base of a type. For example:
|
| 919 |
+
/// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
|
| 920 |
+
template <template <typename...> class Base, typename T>
|
| 921 |
+
// Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
|
| 922 |
+
// See also: https://github.com/pybind/pybind11/pull/3741
|
| 923 |
+
#if !defined(_MSC_VER)
|
| 924 |
+
using is_template_base_of
|
| 925 |
+
= decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
|
| 926 |
+
#else
|
| 927 |
+
struct is_template_base_of
|
| 928 |
+
: decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)) {
|
| 929 |
+
};
|
| 930 |
+
#endif
|
| 931 |
+
|
| 932 |
+
/// Check if T is an instantiation of the template `Class`. For example:
|
| 933 |
+
/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
|
| 934 |
+
template <template <typename...> class Class, typename T>
|
| 935 |
+
struct is_instantiation : std::false_type {};
|
| 936 |
+
template <template <typename...> class Class, typename... Us>
|
| 937 |
+
struct is_instantiation<Class, Class<Us...>> : std::true_type {};
|
| 938 |
+
|
| 939 |
+
/// Check if T is std::shared_ptr<U> where U can be anything
|
| 940 |
+
template <typename T>
|
| 941 |
+
using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
|
| 942 |
+
|
| 943 |
+
/// Check if T looks like an input iterator
|
| 944 |
+
template <typename T, typename = void>
|
| 945 |
+
struct is_input_iterator : std::false_type {};
|
| 946 |
+
template <typename T>
|
| 947 |
+
struct is_input_iterator<T,
|
| 948 |
+
void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
|
| 949 |
+
: std::true_type {};
|
| 950 |
+
|
| 951 |
+
template <typename T>
|
| 952 |
+
using is_function_pointer
|
| 953 |
+
= bool_constant<std::is_pointer<T>::value
|
| 954 |
+
&& std::is_function<typename std::remove_pointer<T>::type>::value>;
|
| 955 |
+
|
| 956 |
+
template <typename F>
|
| 957 |
+
struct strip_function_object {
|
| 958 |
+
// If you are encountering an
|
| 959 |
+
// 'error: name followed by "::" must be a class or namespace name'
|
| 960 |
+
// with the Intel compiler and a noexcept function here,
|
| 961 |
+
// try to use noexcept(true) instead of plain noexcept.
|
| 962 |
+
using type = typename remove_class<decltype(&F::operator())>::type;
|
| 963 |
+
};
|
| 964 |
+
|
| 965 |
+
// Extracts the function signature from a function, function pointer or lambda.
|
| 966 |
+
template <typename Function, typename F = remove_reference_t<Function>>
|
| 967 |
+
using function_signature_t = conditional_t<
|
| 968 |
+
std::is_function<F>::value,
|
| 969 |
+
F,
|
| 970 |
+
typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
|
| 971 |
+
std::remove_pointer<F>,
|
| 972 |
+
strip_function_object<F>>::type>;
|
| 973 |
+
|
| 974 |
+
/// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
|
| 975 |
+
/// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
|
| 976 |
+
/// in a place where passing a lambda makes sense.
|
| 977 |
+
template <typename T>
|
| 978 |
+
using is_lambda = satisfies_none_of<remove_reference_t<T>,
|
| 979 |
+
std::is_function,
|
| 980 |
+
std::is_pointer,
|
| 981 |
+
std::is_member_pointer>;
|
| 982 |
+
|
| 983 |
+
// [workaround(intel)] Internal error on fold expression
|
| 984 |
+
/// Apply a function over each element of a parameter pack
|
| 985 |
+
#if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
|
| 986 |
+
// Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
|
| 987 |
+
# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
|
| 988 |
+
#else
|
| 989 |
+
using expand_side_effects = bool[];
|
| 990 |
+
# define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
|
| 991 |
+
(void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
|
| 992 |
+
#endif
|
| 993 |
+
|
| 994 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 995 |
+
|
| 996 |
+
/// C++ bindings of builtin Python exceptions
|
| 997 |
+
class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
|
| 998 |
+
public:
|
| 999 |
+
using std::runtime_error::runtime_error;
|
| 1000 |
+
/// Set the error using the Python C API
|
| 1001 |
+
virtual void set_error() const = 0;
|
| 1002 |
+
};
|
| 1003 |
+
|
| 1004 |
+
#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
|
| 1005 |
+
class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
|
| 1006 |
+
public: \
|
| 1007 |
+
using builtin_exception::builtin_exception; \
|
| 1008 |
+
name() : name("") {} \
|
| 1009 |
+
void set_error() const override { PyErr_SetString(type, what()); } \
|
| 1010 |
+
};
|
| 1011 |
+
|
| 1012 |
+
PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
|
| 1013 |
+
PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
|
| 1014 |
+
PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
|
| 1015 |
+
PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
|
| 1016 |
+
PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
|
| 1017 |
+
PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
|
| 1018 |
+
PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
|
| 1019 |
+
PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
|
| 1020 |
+
PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
|
| 1021 |
+
/// handle::call fail due to a type
|
| 1022 |
+
/// casting error
|
| 1023 |
+
PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
|
| 1024 |
+
|
| 1025 |
+
[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
|
| 1026 |
+
assert(!PyErr_Occurred());
|
| 1027 |
+
throw std::runtime_error(reason);
|
| 1028 |
+
}
|
| 1029 |
+
[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
|
| 1030 |
+
assert(!PyErr_Occurred());
|
| 1031 |
+
throw std::runtime_error(reason);
|
| 1032 |
+
}
|
| 1033 |
+
|
| 1034 |
+
template <typename T, typename SFINAE = void>
|
| 1035 |
+
struct format_descriptor {};
|
| 1036 |
+
|
| 1037 |
+
template <typename T>
|
| 1038 |
+
struct format_descriptor<
|
| 1039 |
+
T,
|
| 1040 |
+
detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value>> {
|
| 1041 |
+
static constexpr const char c = 'O';
|
| 1042 |
+
static constexpr const char value[2] = {c, '\0'};
|
| 1043 |
+
static std::string format() { return std::string(1, c); }
|
| 1044 |
+
};
|
| 1045 |
+
|
| 1046 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 1047 |
+
// Returns the index of the given type in the type char array below, and in the list in numpy.h
|
| 1048 |
+
// The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
|
| 1049 |
+
// complex float,double,long double. Note that the long double types only participate when long
|
| 1050 |
+
// double is actually longer than double (it isn't under MSVC).
|
| 1051 |
+
// NB: not only the string below but also complex.h and numpy.h rely on this order.
|
| 1052 |
+
template <typename T, typename SFINAE = void>
|
| 1053 |
+
struct is_fmt_numeric {
|
| 1054 |
+
static constexpr bool value = false;
|
| 1055 |
+
};
|
| 1056 |
+
template <typename T>
|
| 1057 |
+
struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
|
| 1058 |
+
static constexpr bool value = true;
|
| 1059 |
+
static constexpr int index
|
| 1060 |
+
= std::is_same<T, bool>::value
|
| 1061 |
+
? 0
|
| 1062 |
+
: 1
|
| 1063 |
+
+ (std::is_integral<T>::value
|
| 1064 |
+
? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
|
| 1065 |
+
: 8
|
| 1066 |
+
+ (std::is_same<T, double>::value ? 1
|
| 1067 |
+
: std::is_same<T, long double>::value ? 2
|
| 1068 |
+
: 0));
|
| 1069 |
+
};
|
| 1070 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 1071 |
+
|
| 1072 |
+
template <typename T>
|
| 1073 |
+
struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
|
| 1074 |
+
static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
|
| 1075 |
+
static constexpr const char value[2] = {c, '\0'};
|
| 1076 |
+
static std::string format() { return std::string(1, c); }
|
| 1077 |
+
};
|
| 1078 |
+
|
| 1079 |
+
#if !defined(PYBIND11_CPP17)
|
| 1080 |
+
|
| 1081 |
+
template <typename T>
|
| 1082 |
+
constexpr const char
|
| 1083 |
+
format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
|
| 1084 |
+
|
| 1085 |
+
#endif
|
| 1086 |
+
|
| 1087 |
+
/// RAII wrapper that temporarily clears any Python error state
|
| 1088 |
+
struct error_scope {
|
| 1089 |
+
PyObject *type, *value, *trace;
|
| 1090 |
+
error_scope() { PyErr_Fetch(&type, &value, &trace); }
|
| 1091 |
+
error_scope(const error_scope &) = delete;
|
| 1092 |
+
error_scope &operator=(const error_scope &) = delete;
|
| 1093 |
+
~error_scope() { PyErr_Restore(type, value, trace); }
|
| 1094 |
+
};
|
| 1095 |
+
|
| 1096 |
+
/// Dummy destructor wrapper that can be used to expose classes with a private destructor
|
| 1097 |
+
struct nodelete {
|
| 1098 |
+
template <typename T>
|
| 1099 |
+
void operator()(T *) {}
|
| 1100 |
+
};
|
| 1101 |
+
|
| 1102 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 1103 |
+
template <typename... Args>
|
| 1104 |
+
struct overload_cast_impl {
|
| 1105 |
+
template <typename Return>
|
| 1106 |
+
constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
|
| 1107 |
+
return pf;
|
| 1108 |
+
}
|
| 1109 |
+
|
| 1110 |
+
template <typename Return, typename Class>
|
| 1111 |
+
constexpr auto operator()(Return (Class::*pmf)(Args...), std::false_type = {}) const noexcept
|
| 1112 |
+
-> decltype(pmf) {
|
| 1113 |
+
return pmf;
|
| 1114 |
+
}
|
| 1115 |
+
|
| 1116 |
+
template <typename Return, typename Class>
|
| 1117 |
+
constexpr auto operator()(Return (Class::*pmf)(Args...) const, std::true_type) const noexcept
|
| 1118 |
+
-> decltype(pmf) {
|
| 1119 |
+
return pmf;
|
| 1120 |
+
}
|
| 1121 |
+
};
|
| 1122 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 1123 |
+
|
| 1124 |
+
// overload_cast requires variable templates: C++14
|
| 1125 |
+
#if defined(PYBIND11_CPP14)
|
| 1126 |
+
# define PYBIND11_OVERLOAD_CAST 1
|
| 1127 |
+
/// Syntax sugar for resolving overloaded function pointers:
|
| 1128 |
+
/// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
|
| 1129 |
+
/// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
|
| 1130 |
+
template <typename... Args>
|
| 1131 |
+
static constexpr detail::overload_cast_impl<Args...> overload_cast{};
|
| 1132 |
+
#endif
|
| 1133 |
+
|
| 1134 |
+
/// Const member function selector for overload_cast
|
| 1135 |
+
/// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
|
| 1136 |
+
/// - sweet: overload_cast<Arg>(&Class::func, const_)
|
| 1137 |
+
static constexpr auto const_ = std::true_type{};
|
| 1138 |
+
|
| 1139 |
+
#if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
|
| 1140 |
+
template <typename... Args>
|
| 1141 |
+
struct overload_cast {
|
| 1142 |
+
static_assert(detail::deferred_t<std::false_type, Args...>::value,
|
| 1143 |
+
"pybind11::overload_cast<...> requires compiling in C++14 mode");
|
| 1144 |
+
};
|
| 1145 |
+
#endif // overload_cast
|
| 1146 |
+
|
| 1147 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 1148 |
+
|
| 1149 |
+
// Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
|
| 1150 |
+
// any standard container (or C-style array) supporting std::begin/std::end, any singleton
|
| 1151 |
+
// arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
|
| 1152 |
+
template <typename T>
|
| 1153 |
+
class any_container {
|
| 1154 |
+
std::vector<T> v;
|
| 1155 |
+
|
| 1156 |
+
public:
|
| 1157 |
+
any_container() = default;
|
| 1158 |
+
|
| 1159 |
+
// Can construct from a pair of iterators
|
| 1160 |
+
template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
|
| 1161 |
+
any_container(It first, It last) : v(first, last) {}
|
| 1162 |
+
|
| 1163 |
+
// Implicit conversion constructor from any arbitrary container type
|
| 1164 |
+
// with values convertible to T
|
| 1165 |
+
template <typename Container,
|
| 1166 |
+
typename = enable_if_t<
|
| 1167 |
+
std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
|
| 1168 |
+
T>::value>>
|
| 1169 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
| 1170 |
+
any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
|
| 1171 |
+
|
| 1172 |
+
// initializer_list's aren't deducible, so don't get matched by the above template;
|
| 1173 |
+
// we need this to explicitly allow implicit conversion from one:
|
| 1174 |
+
template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
|
| 1175 |
+
any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
|
| 1176 |
+
|
| 1177 |
+
// Avoid copying if given an rvalue vector of the correct type.
|
| 1178 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
| 1179 |
+
any_container(std::vector<T> &&v) : v(std::move(v)) {}
|
| 1180 |
+
|
| 1181 |
+
// Moves the vector out of an rvalue any_container
|
| 1182 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
| 1183 |
+
operator std::vector<T> &&() && { return std::move(v); }
|
| 1184 |
+
|
| 1185 |
+
// Dereferencing obtains a reference to the underlying vector
|
| 1186 |
+
std::vector<T> &operator*() { return v; }
|
| 1187 |
+
const std::vector<T> &operator*() const { return v; }
|
| 1188 |
+
|
| 1189 |
+
// -> lets you call methods on the underlying vector
|
| 1190 |
+
std::vector<T> *operator->() { return &v; }
|
| 1191 |
+
const std::vector<T> *operator->() const { return &v; }
|
| 1192 |
+
};
|
| 1193 |
+
|
| 1194 |
+
// Forward-declaration; see detail/class.h
|
| 1195 |
+
std::string get_fully_qualified_tp_name(PyTypeObject *);
|
| 1196 |
+
|
| 1197 |
+
template <typename T>
|
| 1198 |
+
inline static std::shared_ptr<T>
|
| 1199 |
+
try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
|
| 1200 |
+
// Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
|
| 1201 |
+
// Use at your own risk!
|
| 1202 |
+
// See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
|
| 1203 |
+
// the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
|
| 1204 |
+
#if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
|
| 1205 |
+
return holder_value_ptr->weak_from_this().lock();
|
| 1206 |
+
#else
|
| 1207 |
+
try {
|
| 1208 |
+
return holder_value_ptr->shared_from_this();
|
| 1209 |
+
} catch (const std::bad_weak_ptr &) {
|
| 1210 |
+
return nullptr;
|
| 1211 |
+
}
|
| 1212 |
+
#endif
|
| 1213 |
+
}
|
| 1214 |
+
|
| 1215 |
+
// For silencing "unused" compiler warnings in special situations.
|
| 1216 |
+
template <typename... Args>
|
| 1217 |
+
#if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
|
| 1218 |
+
constexpr
|
| 1219 |
+
#endif
|
| 1220 |
+
inline void
|
| 1221 |
+
silence_unused_warnings(Args &&...) {
|
| 1222 |
+
}
|
| 1223 |
+
|
| 1224 |
+
// MSVC warning C4100: Unreferenced formal parameter
|
| 1225 |
+
#if defined(_MSC_VER) && _MSC_VER <= 1916
|
| 1226 |
+
# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
|
| 1227 |
+
detail::silence_unused_warnings(__VA_ARGS__)
|
| 1228 |
+
#else
|
| 1229 |
+
# define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
|
| 1230 |
+
#endif
|
| 1231 |
+
|
| 1232 |
+
// GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
|
| 1233 |
+
#if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
|
| 1234 |
+
# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
|
| 1235 |
+
detail::silence_unused_warnings(__VA_ARGS__)
|
| 1236 |
+
#else
|
| 1237 |
+
# define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
|
| 1238 |
+
#endif
|
| 1239 |
+
|
| 1240 |
+
#if defined(__clang__) \
|
| 1241 |
+
&& (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point \
|
| 1242 |
+
available. */ \
|
| 1243 |
+
|| (__clang_major__ >= 7 \
|
| 1244 |
+
&& __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */ \
|
| 1245 |
+
)
|
| 1246 |
+
# define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
|
| 1247 |
+
// Example:
|
| 1248 |
+
// tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite
|
| 1249 |
+
// being returned by name [-Werror,-Wreturn-std-move]
|
| 1250 |
+
// m.def("args_function", [](py::args args) -> py::tuple { return args; });
|
| 1251 |
+
// ^~~~
|
| 1252 |
+
// test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying
|
| 1253 |
+
// m.def("args_function", [](py::args args) -> py::tuple { return args; });
|
| 1254 |
+
// ^~~~
|
| 1255 |
+
// std::move(args)
|
| 1256 |
+
#endif
|
| 1257 |
+
|
| 1258 |
+
// Pybind offers detailed error messages by default for all builts that are debug (through the
|
| 1259 |
+
// negation of NDEBUG). This can also be manually enabled by users, for any builds, through
|
| 1260 |
+
// defining PYBIND11_DETAILED_ERROR_MESSAGES. This information is primarily useful for those
|
| 1261 |
+
// who are writing (as opposed to merely using) libraries that use pybind11.
|
| 1262 |
+
#if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
|
| 1263 |
+
# define PYBIND11_DETAILED_ERROR_MESSAGES
|
| 1264 |
+
#endif
|
| 1265 |
+
|
| 1266 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 1267 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
data/home/.local/lib/python3.8/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)
|
data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/init.h
ADDED
|
@@ -0,0 +1,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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 initialization 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)
|
data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/internals.h
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 || defined(_MSC_VER)
|
| 38 |
+
// Version bump for Python 3.12+, before first 3.12 beta release.
|
| 39 |
+
// Version bump for MSVC piggy-backed on PR #4779. See comments there.
|
| 40 |
+
# define PYBIND11_INTERNALS_VERSION 5
|
| 41 |
+
# else
|
| 42 |
+
# define PYBIND11_INTERNALS_VERSION 4
|
| 43 |
+
# endif
|
| 44 |
+
#endif
|
| 45 |
+
|
| 46 |
+
// This requirement is mainly to reduce the support burden (see PR #4570).
|
| 47 |
+
static_assert(PY_VERSION_HEX < 0x030C0000 || PYBIND11_INTERNALS_VERSION >= 5,
|
| 48 |
+
"pybind11 ABI version 5 is the minimum for Python 3.12+");
|
| 49 |
+
|
| 50 |
+
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
| 51 |
+
|
| 52 |
+
using ExceptionTranslator = void (*)(std::exception_ptr);
|
| 53 |
+
|
| 54 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 55 |
+
|
| 56 |
+
constexpr const char *internals_function_record_capsule_name = "pybind11_function_record_capsule";
|
| 57 |
+
|
| 58 |
+
// Forward declarations
|
| 59 |
+
inline PyTypeObject *make_static_property_type();
|
| 60 |
+
inline PyTypeObject *make_default_metaclass();
|
| 61 |
+
inline PyObject *make_object_base_type(PyTypeObject *metaclass);
|
| 62 |
+
|
| 63 |
+
// The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
|
| 64 |
+
// Thread Specific Storage (TSS) API.
|
| 65 |
+
#if PY_VERSION_HEX >= 0x03070000
|
| 66 |
+
// Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
|
| 67 |
+
// `Py_LIMITED_API` anyway.
|
| 68 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
| 69 |
+
# define PYBIND11_TLS_KEY_REF Py_tss_t &
|
| 70 |
+
# if defined(__clang__)
|
| 71 |
+
# define PYBIND11_TLS_KEY_INIT(var) \
|
| 72 |
+
_Pragma("clang diagnostic push") /**/ \
|
| 73 |
+
_Pragma("clang diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
|
| 74 |
+
Py_tss_t var \
|
| 75 |
+
= Py_tss_NEEDS_INIT; \
|
| 76 |
+
_Pragma("clang diagnostic pop")
|
| 77 |
+
# elif defined(__GNUC__) && !defined(__INTEL_COMPILER)
|
| 78 |
+
# define PYBIND11_TLS_KEY_INIT(var) \
|
| 79 |
+
_Pragma("GCC diagnostic push") /**/ \
|
| 80 |
+
_Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
|
| 81 |
+
Py_tss_t var \
|
| 82 |
+
= Py_tss_NEEDS_INIT; \
|
| 83 |
+
_Pragma("GCC diagnostic pop")
|
| 84 |
+
# else
|
| 85 |
+
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
|
| 86 |
+
# endif
|
| 87 |
+
# define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
|
| 88 |
+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
|
| 89 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
|
| 90 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
|
| 91 |
+
# define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
|
| 92 |
+
# else
|
| 93 |
+
# define PYBIND11_TLS_KEY_REF Py_tss_t *
|
| 94 |
+
# define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
|
| 95 |
+
# define PYBIND11_TLS_KEY_CREATE(var) \
|
| 96 |
+
(((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
|
| 97 |
+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
|
| 98 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
|
| 99 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
|
| 100 |
+
# define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
|
| 101 |
+
# endif
|
| 102 |
+
#else
|
| 103 |
+
// Usually an int but a long on Cygwin64 with Python 3.x
|
| 104 |
+
# define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
|
| 105 |
+
# define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0;
|
| 106 |
+
# define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
|
| 107 |
+
# define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
|
| 108 |
+
# if defined(PYPY_VERSION)
|
| 109 |
+
// On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
|
| 110 |
+
// the value if it has already been set. Instead, it must first be deleted and
|
| 111 |
+
// then set again.
|
| 112 |
+
inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) {
|
| 113 |
+
PyThread_delete_key_value(key);
|
| 114 |
+
PyThread_set_key_value(key, value);
|
| 115 |
+
}
|
| 116 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
|
| 117 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) \
|
| 118 |
+
::pybind11::detail::tls_replace_value((key), (value))
|
| 119 |
+
# else
|
| 120 |
+
# define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
|
| 121 |
+
# define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
|
| 122 |
+
# endif
|
| 123 |
+
# define PYBIND11_TLS_FREE(key) (void) key
|
| 124 |
+
#endif
|
| 125 |
+
|
| 126 |
+
// Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
|
| 127 |
+
// other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
|
| 128 |
+
// even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
|
| 129 |
+
// libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
|
| 130 |
+
// which works. If not under a known-good stl, provide our own name-based hash and equality
|
| 131 |
+
// functions that use the type name.
|
| 132 |
+
#if (PYBIND11_INTERNALS_VERSION <= 4 && defined(__GLIBCXX__)) \
|
| 133 |
+
|| (PYBIND11_INTERNALS_VERSION >= 5 && !defined(_LIBCPP_VERSION))
|
| 134 |
+
inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
|
| 135 |
+
using type_hash = std::hash<std::type_index>;
|
| 136 |
+
using type_equal_to = std::equal_to<std::type_index>;
|
| 137 |
+
#else
|
| 138 |
+
inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
|
| 139 |
+
return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
struct type_hash {
|
| 143 |
+
size_t operator()(const std::type_index &t) const {
|
| 144 |
+
size_t hash = 5381;
|
| 145 |
+
const char *ptr = t.name();
|
| 146 |
+
while (auto c = static_cast<unsigned char>(*ptr++)) {
|
| 147 |
+
hash = (hash * 33) ^ c;
|
| 148 |
+
}
|
| 149 |
+
return hash;
|
| 150 |
+
}
|
| 151 |
+
};
|
| 152 |
+
|
| 153 |
+
struct type_equal_to {
|
| 154 |
+
bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
|
| 155 |
+
return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
|
| 156 |
+
}
|
| 157 |
+
};
|
| 158 |
+
#endif
|
| 159 |
+
|
| 160 |
+
template <typename value_type>
|
| 161 |
+
using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
|
| 162 |
+
|
| 163 |
+
struct override_hash {
|
| 164 |
+
inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
|
| 165 |
+
size_t value = std::hash<const void *>()(v.first);
|
| 166 |
+
value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
|
| 167 |
+
return value;
|
| 168 |
+
}
|
| 169 |
+
};
|
| 170 |
+
|
| 171 |
+
/// Internal data structure used to track registered instances and types.
|
| 172 |
+
/// Whenever binary incompatible changes are made to this structure,
|
| 173 |
+
/// `PYBIND11_INTERNALS_VERSION` must be incremented.
|
| 174 |
+
struct internals {
|
| 175 |
+
// std::type_index -> pybind11's type information
|
| 176 |
+
type_map<type_info *> registered_types_cpp;
|
| 177 |
+
// PyTypeObject* -> base type_info(s)
|
| 178 |
+
std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
|
| 179 |
+
std::unordered_multimap<const void *, instance *> registered_instances; // void * -> instance*
|
| 180 |
+
std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
|
| 181 |
+
inactive_override_cache;
|
| 182 |
+
type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
|
| 183 |
+
std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
|
| 184 |
+
std::forward_list<ExceptionTranslator> registered_exception_translators;
|
| 185 |
+
std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
|
| 186 |
+
// extensions
|
| 187 |
+
#if PYBIND11_INTERNALS_VERSION == 4
|
| 188 |
+
std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
|
| 189 |
+
#endif
|
| 190 |
+
std::forward_list<std::string> static_strings; // Stores the std::strings backing
|
| 191 |
+
// detail::c_str()
|
| 192 |
+
PyTypeObject *static_property_type;
|
| 193 |
+
PyTypeObject *default_metaclass;
|
| 194 |
+
PyObject *instance_base;
|
| 195 |
+
#if defined(WITH_THREAD)
|
| 196 |
+
// Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
|
| 197 |
+
PYBIND11_TLS_KEY_INIT(tstate)
|
| 198 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
| 199 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
| 200 |
+
# endif // PYBIND11_INTERNALS_VERSION > 4
|
| 201 |
+
// Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
|
| 202 |
+
PyInterpreterState *istate = nullptr;
|
| 203 |
+
|
| 204 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
| 205 |
+
// Note that we have to use a std::string to allocate memory to ensure a unique address
|
| 206 |
+
// We want unique addresses since we use pointer equality to compare function records
|
| 207 |
+
std::string function_record_capsule_name = internals_function_record_capsule_name;
|
| 208 |
+
# endif
|
| 209 |
+
|
| 210 |
+
internals() = default;
|
| 211 |
+
internals(const internals &other) = delete;
|
| 212 |
+
internals &operator=(const internals &other) = delete;
|
| 213 |
+
~internals() {
|
| 214 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
| 215 |
+
PYBIND11_TLS_FREE(loader_life_support_tls_key);
|
| 216 |
+
# endif // PYBIND11_INTERNALS_VERSION > 4
|
| 217 |
+
|
| 218 |
+
// This destructor is called *after* Py_Finalize() in finalize_interpreter().
|
| 219 |
+
// That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
|
| 220 |
+
// called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
|
| 221 |
+
// nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
|
| 222 |
+
// PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
|
| 223 |
+
// Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
|
| 224 |
+
// that the `tstate` be allocated with the CPython allocator.
|
| 225 |
+
PYBIND11_TLS_FREE(tstate);
|
| 226 |
+
}
|
| 227 |
+
#endif
|
| 228 |
+
};
|
| 229 |
+
|
| 230 |
+
/// Additional type information which does not fit into the PyTypeObject.
|
| 231 |
+
/// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.
|
| 232 |
+
struct type_info {
|
| 233 |
+
PyTypeObject *type;
|
| 234 |
+
const std::type_info *cpptype;
|
| 235 |
+
size_t type_size, type_align, holder_size_in_ptrs;
|
| 236 |
+
void *(*operator_new)(size_t);
|
| 237 |
+
void (*init_instance)(instance *, const void *);
|
| 238 |
+
void (*dealloc)(value_and_holder &v_h);
|
| 239 |
+
std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
|
| 240 |
+
std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
|
| 241 |
+
std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
|
| 242 |
+
buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
|
| 243 |
+
void *get_buffer_data = nullptr;
|
| 244 |
+
void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
|
| 245 |
+
/* A simple type never occurs as a (direct or indirect) parent
|
| 246 |
+
* of a class that makes use of multiple inheritance.
|
| 247 |
+
* A type can be simple even if it has non-simple ancestors as long as it has no descendants.
|
| 248 |
+
*/
|
| 249 |
+
bool simple_type : 1;
|
| 250 |
+
/* True if there is no multiple inheritance in this type's inheritance tree */
|
| 251 |
+
bool simple_ancestors : 1;
|
| 252 |
+
/* for base vs derived holder_type checks */
|
| 253 |
+
bool default_holder : 1;
|
| 254 |
+
/* true if this is a type registered with py::module_local */
|
| 255 |
+
bool module_local : 1;
|
| 256 |
+
};
|
| 257 |
+
|
| 258 |
+
/// On MSVC, debug and release builds are not ABI-compatible!
|
| 259 |
+
#if defined(_MSC_VER) && defined(_DEBUG)
|
| 260 |
+
# define PYBIND11_BUILD_TYPE "_debug"
|
| 261 |
+
#else
|
| 262 |
+
# define PYBIND11_BUILD_TYPE ""
|
| 263 |
+
#endif
|
| 264 |
+
|
| 265 |
+
/// Let's assume that different compilers are ABI-incompatible.
|
| 266 |
+
/// A user can manually set this string if they know their
|
| 267 |
+
/// compiler is compatible.
|
| 268 |
+
#ifndef PYBIND11_COMPILER_TYPE
|
| 269 |
+
# if defined(_MSC_VER)
|
| 270 |
+
# define PYBIND11_COMPILER_TYPE "_msvc"
|
| 271 |
+
# elif defined(__INTEL_COMPILER)
|
| 272 |
+
# define PYBIND11_COMPILER_TYPE "_icc"
|
| 273 |
+
# elif defined(__clang__)
|
| 274 |
+
# define PYBIND11_COMPILER_TYPE "_clang"
|
| 275 |
+
# elif defined(__PGI)
|
| 276 |
+
# define PYBIND11_COMPILER_TYPE "_pgi"
|
| 277 |
+
# elif defined(__MINGW32__)
|
| 278 |
+
# define PYBIND11_COMPILER_TYPE "_mingw"
|
| 279 |
+
# elif defined(__CYGWIN__)
|
| 280 |
+
# define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
|
| 281 |
+
# elif defined(__GNUC__)
|
| 282 |
+
# define PYBIND11_COMPILER_TYPE "_gcc"
|
| 283 |
+
# else
|
| 284 |
+
# define PYBIND11_COMPILER_TYPE "_unknown"
|
| 285 |
+
# endif
|
| 286 |
+
#endif
|
| 287 |
+
|
| 288 |
+
/// Also standard libs
|
| 289 |
+
#ifndef PYBIND11_STDLIB
|
| 290 |
+
# if defined(_LIBCPP_VERSION)
|
| 291 |
+
# define PYBIND11_STDLIB "_libcpp"
|
| 292 |
+
# elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
|
| 293 |
+
# define PYBIND11_STDLIB "_libstdcpp"
|
| 294 |
+
# else
|
| 295 |
+
# define PYBIND11_STDLIB ""
|
| 296 |
+
# endif
|
| 297 |
+
#endif
|
| 298 |
+
|
| 299 |
+
/// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility.
|
| 300 |
+
/// On MSVC, changes in _MSC_VER may indicate ABI incompatibility (#2898).
|
| 301 |
+
#ifndef PYBIND11_BUILD_ABI
|
| 302 |
+
# if defined(__GXX_ABI_VERSION)
|
| 303 |
+
# define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
|
| 304 |
+
# elif defined(_MSC_VER)
|
| 305 |
+
# define PYBIND11_BUILD_ABI "_mscver" PYBIND11_TOSTRING(_MSC_VER)
|
| 306 |
+
# else
|
| 307 |
+
# define PYBIND11_BUILD_ABI ""
|
| 308 |
+
# endif
|
| 309 |
+
#endif
|
| 310 |
+
|
| 311 |
+
#ifndef PYBIND11_INTERNALS_KIND
|
| 312 |
+
# if defined(WITH_THREAD)
|
| 313 |
+
# define PYBIND11_INTERNALS_KIND ""
|
| 314 |
+
# else
|
| 315 |
+
# define PYBIND11_INTERNALS_KIND "_without_thread"
|
| 316 |
+
# endif
|
| 317 |
+
#endif
|
| 318 |
+
|
| 319 |
+
#define PYBIND11_INTERNALS_ID \
|
| 320 |
+
"__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
|
| 321 |
+
PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
|
| 322 |
+
PYBIND11_BUILD_TYPE "__"
|
| 323 |
+
|
| 324 |
+
#define PYBIND11_MODULE_LOCAL_ID \
|
| 325 |
+
"__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
|
| 326 |
+
PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
|
| 327 |
+
PYBIND11_BUILD_TYPE "__"
|
| 328 |
+
|
| 329 |
+
/// Each module locally stores a pointer to the `internals` data. The data
|
| 330 |
+
/// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
|
| 331 |
+
inline internals **&get_internals_pp() {
|
| 332 |
+
static internals **internals_pp = nullptr;
|
| 333 |
+
return internals_pp;
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
// forward decl
|
| 337 |
+
inline void translate_exception(std::exception_ptr);
|
| 338 |
+
|
| 339 |
+
template <class T,
|
| 340 |
+
enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
|
| 341 |
+
bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
|
| 342 |
+
std::exception_ptr nested = exc.nested_ptr();
|
| 343 |
+
if (nested != nullptr && nested != p) {
|
| 344 |
+
translate_exception(nested);
|
| 345 |
+
return true;
|
| 346 |
+
}
|
| 347 |
+
return false;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
template <class T,
|
| 351 |
+
enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
|
| 352 |
+
bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
|
| 353 |
+
if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
|
| 354 |
+
return handle_nested_exception(*nep, p);
|
| 355 |
+
}
|
| 356 |
+
return false;
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
inline bool raise_err(PyObject *exc_type, const char *msg) {
|
| 360 |
+
if (PyErr_Occurred()) {
|
| 361 |
+
raise_from(exc_type, msg);
|
| 362 |
+
return true;
|
| 363 |
+
}
|
| 364 |
+
set_error(exc_type, msg);
|
| 365 |
+
return false;
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
inline void translate_exception(std::exception_ptr p) {
|
| 369 |
+
if (!p) {
|
| 370 |
+
return;
|
| 371 |
+
}
|
| 372 |
+
try {
|
| 373 |
+
std::rethrow_exception(p);
|
| 374 |
+
} catch (error_already_set &e) {
|
| 375 |
+
handle_nested_exception(e, p);
|
| 376 |
+
e.restore();
|
| 377 |
+
return;
|
| 378 |
+
} catch (const builtin_exception &e) {
|
| 379 |
+
// Could not use template since it's an abstract class.
|
| 380 |
+
if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
|
| 381 |
+
handle_nested_exception(*nep, p);
|
| 382 |
+
}
|
| 383 |
+
e.set_error();
|
| 384 |
+
return;
|
| 385 |
+
} catch (const std::bad_alloc &e) {
|
| 386 |
+
handle_nested_exception(e, p);
|
| 387 |
+
raise_err(PyExc_MemoryError, e.what());
|
| 388 |
+
return;
|
| 389 |
+
} catch (const std::domain_error &e) {
|
| 390 |
+
handle_nested_exception(e, p);
|
| 391 |
+
raise_err(PyExc_ValueError, e.what());
|
| 392 |
+
return;
|
| 393 |
+
} catch (const std::invalid_argument &e) {
|
| 394 |
+
handle_nested_exception(e, p);
|
| 395 |
+
raise_err(PyExc_ValueError, e.what());
|
| 396 |
+
return;
|
| 397 |
+
} catch (const std::length_error &e) {
|
| 398 |
+
handle_nested_exception(e, p);
|
| 399 |
+
raise_err(PyExc_ValueError, e.what());
|
| 400 |
+
return;
|
| 401 |
+
} catch (const std::out_of_range &e) {
|
| 402 |
+
handle_nested_exception(e, p);
|
| 403 |
+
raise_err(PyExc_IndexError, e.what());
|
| 404 |
+
return;
|
| 405 |
+
} catch (const std::range_error &e) {
|
| 406 |
+
handle_nested_exception(e, p);
|
| 407 |
+
raise_err(PyExc_ValueError, e.what());
|
| 408 |
+
return;
|
| 409 |
+
} catch (const std::overflow_error &e) {
|
| 410 |
+
handle_nested_exception(e, p);
|
| 411 |
+
raise_err(PyExc_OverflowError, e.what());
|
| 412 |
+
return;
|
| 413 |
+
} catch (const std::exception &e) {
|
| 414 |
+
handle_nested_exception(e, p);
|
| 415 |
+
raise_err(PyExc_RuntimeError, e.what());
|
| 416 |
+
return;
|
| 417 |
+
} catch (const std::nested_exception &e) {
|
| 418 |
+
handle_nested_exception(e, p);
|
| 419 |
+
raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
|
| 420 |
+
return;
|
| 421 |
+
} catch (...) {
|
| 422 |
+
raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
|
| 423 |
+
return;
|
| 424 |
+
}
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
#if !defined(__GLIBCXX__)
|
| 428 |
+
inline void translate_local_exception(std::exception_ptr p) {
|
| 429 |
+
try {
|
| 430 |
+
if (p) {
|
| 431 |
+
std::rethrow_exception(p);
|
| 432 |
+
}
|
| 433 |
+
} catch (error_already_set &e) {
|
| 434 |
+
e.restore();
|
| 435 |
+
return;
|
| 436 |
+
} catch (const builtin_exception &e) {
|
| 437 |
+
e.set_error();
|
| 438 |
+
return;
|
| 439 |
+
}
|
| 440 |
+
}
|
| 441 |
+
#endif
|
| 442 |
+
|
| 443 |
+
inline object get_python_state_dict() {
|
| 444 |
+
object state_dict;
|
| 445 |
+
#if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
|
| 446 |
+
state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
|
| 447 |
+
#else
|
| 448 |
+
# if PY_VERSION_HEX < 0x03090000
|
| 449 |
+
PyInterpreterState *istate = _PyInterpreterState_Get();
|
| 450 |
+
# else
|
| 451 |
+
PyInterpreterState *istate = PyInterpreterState_Get();
|
| 452 |
+
# endif
|
| 453 |
+
if (istate) {
|
| 454 |
+
state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
|
| 455 |
+
}
|
| 456 |
+
#endif
|
| 457 |
+
if (!state_dict) {
|
| 458 |
+
raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
|
| 459 |
+
throw error_already_set();
|
| 460 |
+
}
|
| 461 |
+
return state_dict;
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
inline object get_internals_obj_from_state_dict(handle state_dict) {
|
| 465 |
+
return reinterpret_borrow<object>(dict_getitemstring(state_dict.ptr(), PYBIND11_INTERNALS_ID));
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
inline internals **get_internals_pp_from_capsule(handle obj) {
|
| 469 |
+
void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
|
| 470 |
+
if (raw_ptr == nullptr) {
|
| 471 |
+
raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
|
| 472 |
+
throw error_already_set();
|
| 473 |
+
}
|
| 474 |
+
return static_cast<internals **>(raw_ptr);
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
/// Return a reference to the current `internals` data
|
| 478 |
+
PYBIND11_NOINLINE internals &get_internals() {
|
| 479 |
+
auto **&internals_pp = get_internals_pp();
|
| 480 |
+
if (internals_pp && *internals_pp) {
|
| 481 |
+
return **internals_pp;
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
#if defined(WITH_THREAD)
|
| 485 |
+
# if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
|
| 486 |
+
gil_scoped_acquire gil;
|
| 487 |
+
# else
|
| 488 |
+
// Ensure that the GIL is held since we will need to make Python calls.
|
| 489 |
+
// Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
|
| 490 |
+
struct gil_scoped_acquire_local {
|
| 491 |
+
gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
|
| 492 |
+
gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
|
| 493 |
+
gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
|
| 494 |
+
~gil_scoped_acquire_local() { PyGILState_Release(state); }
|
| 495 |
+
const PyGILState_STATE state;
|
| 496 |
+
} gil;
|
| 497 |
+
# endif
|
| 498 |
+
#endif
|
| 499 |
+
error_scope err_scope;
|
| 500 |
+
|
| 501 |
+
dict state_dict = get_python_state_dict();
|
| 502 |
+
if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
|
| 503 |
+
internals_pp = get_internals_pp_from_capsule(internals_obj);
|
| 504 |
+
}
|
| 505 |
+
if (internals_pp && *internals_pp) {
|
| 506 |
+
// We loaded the internals through `state_dict`, which means that our `error_already_set`
|
| 507 |
+
// and `builtin_exception` may be different local classes than the ones set up in the
|
| 508 |
+
// initial exception translator, below, so add another for our local exception classes.
|
| 509 |
+
//
|
| 510 |
+
// libstdc++ doesn't require this (types there are identified only by name)
|
| 511 |
+
// libc++ with CPython doesn't require this (types are explicitly exported)
|
| 512 |
+
// libc++ with PyPy still need it, awaiting further investigation
|
| 513 |
+
#if !defined(__GLIBCXX__)
|
| 514 |
+
(*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
|
| 515 |
+
#endif
|
| 516 |
+
} else {
|
| 517 |
+
if (!internals_pp) {
|
| 518 |
+
internals_pp = new internals *();
|
| 519 |
+
}
|
| 520 |
+
auto *&internals_ptr = *internals_pp;
|
| 521 |
+
internals_ptr = new internals();
|
| 522 |
+
#if defined(WITH_THREAD)
|
| 523 |
+
|
| 524 |
+
PyThreadState *tstate = PyThreadState_Get();
|
| 525 |
+
// NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
|
| 526 |
+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
|
| 527 |
+
pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
|
| 528 |
+
}
|
| 529 |
+
PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
|
| 530 |
+
|
| 531 |
+
# if PYBIND11_INTERNALS_VERSION > 4
|
| 532 |
+
// NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
|
| 533 |
+
if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
|
| 534 |
+
pybind11_fail("get_internals: could not successfully initialize the "
|
| 535 |
+
"loader_life_support TSS key!");
|
| 536 |
+
}
|
| 537 |
+
# endif
|
| 538 |
+
internals_ptr->istate = tstate->interp;
|
| 539 |
+
#endif
|
| 540 |
+
state_dict[PYBIND11_INTERNALS_ID] = capsule(internals_pp);
|
| 541 |
+
internals_ptr->registered_exception_translators.push_front(&translate_exception);
|
| 542 |
+
internals_ptr->static_property_type = make_static_property_type();
|
| 543 |
+
internals_ptr->default_metaclass = make_default_metaclass();
|
| 544 |
+
internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
|
| 545 |
+
}
|
| 546 |
+
return **internals_pp;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
// the internals struct (above) is shared between all the modules. local_internals are only
|
| 550 |
+
// for a single module. Any changes made to internals may require an update to
|
| 551 |
+
// PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
|
| 552 |
+
// restricted to a single module. Whether a module has local internals or not should not
|
| 553 |
+
// impact any other modules, because the only things accessing the local internals is the
|
| 554 |
+
// module that contains them.
|
| 555 |
+
struct local_internals {
|
| 556 |
+
type_map<type_info *> registered_types_cpp;
|
| 557 |
+
std::forward_list<ExceptionTranslator> registered_exception_translators;
|
| 558 |
+
#if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
|
| 559 |
+
|
| 560 |
+
// For ABI compatibility, we can't store the loader_life_support TLS key in
|
| 561 |
+
// the `internals` struct directly. Instead, we store it in `shared_data` and
|
| 562 |
+
// cache a copy in `local_internals`. If we allocated a separate TLS key for
|
| 563 |
+
// each instance of `local_internals`, we could end up allocating hundreds of
|
| 564 |
+
// TLS keys if hundreds of different pybind11 modules are loaded (which is a
|
| 565 |
+
// plausible number).
|
| 566 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
| 567 |
+
|
| 568 |
+
// Holds the shared TLS key for the loader_life_support stack.
|
| 569 |
+
struct shared_loader_life_support_data {
|
| 570 |
+
PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
|
| 571 |
+
shared_loader_life_support_data() {
|
| 572 |
+
// NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
|
| 573 |
+
if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
|
| 574 |
+
pybind11_fail("local_internals: could not successfully initialize the "
|
| 575 |
+
"loader_life_support TLS key!");
|
| 576 |
+
}
|
| 577 |
+
}
|
| 578 |
+
// We can't help but leak the TLS key, because Python never unloads extension modules.
|
| 579 |
+
};
|
| 580 |
+
|
| 581 |
+
local_internals() {
|
| 582 |
+
auto &internals = get_internals();
|
| 583 |
+
// Get or create the `loader_life_support_stack_key`.
|
| 584 |
+
auto &ptr = internals.shared_data["_life_support"];
|
| 585 |
+
if (!ptr) {
|
| 586 |
+
ptr = new shared_loader_life_support_data;
|
| 587 |
+
}
|
| 588 |
+
loader_life_support_tls_key
|
| 589 |
+
= static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
|
| 590 |
+
}
|
| 591 |
+
#endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
|
| 592 |
+
};
|
| 593 |
+
|
| 594 |
+
/// Works like `get_internals`, but for things which are locally registered.
|
| 595 |
+
inline local_internals &get_local_internals() {
|
| 596 |
+
// Current static can be created in the interpreter finalization routine. If the later will be
|
| 597 |
+
// destroyed in another static variable destructor, creation of this static there will cause
|
| 598 |
+
// static deinitialization fiasco. In order to avoid it we avoid destruction of the
|
| 599 |
+
// local_internals static. One can read more about the problem and current solution here:
|
| 600 |
+
// https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
|
| 601 |
+
static auto *locals = new local_internals();
|
| 602 |
+
return *locals;
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
/// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
|
| 606 |
+
/// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only
|
| 607 |
+
/// cleared when the program exits or after interpreter shutdown (when embedding), and so are
|
| 608 |
+
/// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
|
| 609 |
+
template <typename... Args>
|
| 610 |
+
const char *c_str(Args &&...args) {
|
| 611 |
+
auto &strings = get_internals().static_strings;
|
| 612 |
+
strings.emplace_front(std::forward<Args>(args)...);
|
| 613 |
+
return strings.front().c_str();
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
inline const char *get_function_record_capsule_name() {
|
| 617 |
+
#if PYBIND11_INTERNALS_VERSION > 4
|
| 618 |
+
return get_internals().function_record_capsule_name.c_str();
|
| 619 |
+
#else
|
| 620 |
+
return nullptr;
|
| 621 |
+
#endif
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
// Determine whether or not the following capsule contains a pybind11 function record.
|
| 625 |
+
// Note that we use `internals` to make sure that only ABI compatible records are touched.
|
| 626 |
+
//
|
| 627 |
+
// This check is currently used in two places:
|
| 628 |
+
// - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
|
| 629 |
+
// - The sibling feature of cpp_function to allow overloads
|
| 630 |
+
inline bool is_function_record_capsule(const capsule &cap) {
|
| 631 |
+
// Pointer equality as we rely on internals() to ensure unique pointers
|
| 632 |
+
return cap.name() == get_function_record_capsule_name();
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 636 |
+
|
| 637 |
+
/// Returns a named pointer that is shared among all extension modules (using the same
|
| 638 |
+
/// pybind11 version) running in the current interpreter. Names starting with underscores
|
| 639 |
+
/// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
|
| 640 |
+
PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
|
| 641 |
+
auto &internals = detail::get_internals();
|
| 642 |
+
auto it = internals.shared_data.find(name);
|
| 643 |
+
return it != internals.shared_data.end() ? it->second : nullptr;
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
/// Set the shared data that can be later recovered by `get_shared_data()`.
|
| 647 |
+
PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
|
| 648 |
+
detail::get_internals().shared_data[name] = data;
|
| 649 |
+
return data;
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
/// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
|
| 653 |
+
/// such entry exists. Otherwise, a new object of default-constructible type `T` is
|
| 654 |
+
/// added to the shared data under the given name and a reference to it is returned.
|
| 655 |
+
template <typename T>
|
| 656 |
+
T &get_or_create_shared_data(const std::string &name) {
|
| 657 |
+
auto &internals = detail::get_internals();
|
| 658 |
+
auto it = internals.shared_data.find(name);
|
| 659 |
+
T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
|
| 660 |
+
if (!ptr) {
|
| 661 |
+
ptr = new T();
|
| 662 |
+
internals.shared_data[name] = ptr;
|
| 663 |
+
}
|
| 664 |
+
return *ptr;
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/detail/type_caster_base.h
ADDED
|
@@ -0,0 +1,1218 @@
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
// Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.
|
| 106 |
+
inline void all_type_info_add_base_most_derived_first(std::vector<type_info *> &bases,
|
| 107 |
+
type_info *addl_base) {
|
| 108 |
+
for (auto it = bases.begin(); it != bases.end(); it++) {
|
| 109 |
+
type_info *existing_base = *it;
|
| 110 |
+
if (PyType_IsSubtype(addl_base->type, existing_base->type) != 0) {
|
| 111 |
+
bases.insert(it, addl_base);
|
| 112 |
+
return;
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
bases.push_back(addl_base);
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// Populates a just-created cache entry.
|
| 119 |
+
PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
|
| 120 |
+
assert(bases.empty());
|
| 121 |
+
std::vector<PyTypeObject *> check;
|
| 122 |
+
for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
|
| 123 |
+
check.push_back((PyTypeObject *) parent.ptr());
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
auto const &type_dict = get_internals().registered_types_py;
|
| 127 |
+
for (size_t i = 0; i < check.size(); i++) {
|
| 128 |
+
auto *type = check[i];
|
| 129 |
+
// Ignore Python2 old-style class super type:
|
| 130 |
+
if (!PyType_Check((PyObject *) type)) {
|
| 131 |
+
continue;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// Check `type` in the current set of registered python types:
|
| 135 |
+
auto it = type_dict.find(type);
|
| 136 |
+
if (it != type_dict.end()) {
|
| 137 |
+
// We found a cache entry for it, so it's either pybind-registered or has pre-computed
|
| 138 |
+
// pybind bases, but we have to make sure we haven't already seen the type(s) before:
|
| 139 |
+
// we want to follow Python/virtual C++ rules that there should only be one instance of
|
| 140 |
+
// a common base.
|
| 141 |
+
for (auto *tinfo : it->second) {
|
| 142 |
+
// NB: Could use a second set here, rather than doing a linear search, but since
|
| 143 |
+
// having a large number of immediate pybind11-registered types seems fairly
|
| 144 |
+
// unlikely, that probably isn't worthwhile.
|
| 145 |
+
bool found = false;
|
| 146 |
+
for (auto *known : bases) {
|
| 147 |
+
if (known == tinfo) {
|
| 148 |
+
found = true;
|
| 149 |
+
break;
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
if (!found) {
|
| 153 |
+
all_type_info_add_base_most_derived_first(bases, tinfo);
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
} else if (type->tp_bases) {
|
| 157 |
+
// It's some python type, so keep follow its bases classes to look for one or more
|
| 158 |
+
// registered types
|
| 159 |
+
if (i + 1 == check.size()) {
|
| 160 |
+
// When we're at the end, we can pop off the current element to avoid growing
|
| 161 |
+
// `check` when adding just one base (which is typical--i.e. when there is no
|
| 162 |
+
// multiple inheritance)
|
| 163 |
+
check.pop_back();
|
| 164 |
+
i--;
|
| 165 |
+
}
|
| 166 |
+
for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
|
| 167 |
+
check.push_back((PyTypeObject *) parent.ptr());
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
/**
|
| 174 |
+
* Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
|
| 175 |
+
* be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
|
| 176 |
+
* derived class that uses single inheritance. Will contain as many types as required for a Python
|
| 177 |
+
* class that uses multiple inheritance to inherit (directly or indirectly) from multiple
|
| 178 |
+
* pybind-registered classes. Will be empty if neither the type nor any base classes are
|
| 179 |
+
* pybind-registered.
|
| 180 |
+
*
|
| 181 |
+
* The value is cached for the lifetime of the Python type.
|
| 182 |
+
*/
|
| 183 |
+
inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
|
| 184 |
+
auto ins = all_type_info_get_cache(type);
|
| 185 |
+
if (ins.second) {
|
| 186 |
+
// New cache entry: populate it
|
| 187 |
+
all_type_info_populate(type, ins.first->second);
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
return ins.first->second;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
/**
|
| 194 |
+
* Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
|
| 195 |
+
* ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
|
| 196 |
+
* `all_type_info` instead if you want to support multiple bases.
|
| 197 |
+
*/
|
| 198 |
+
PYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {
|
| 199 |
+
const auto &bases = all_type_info(type);
|
| 200 |
+
if (bases.empty()) {
|
| 201 |
+
return nullptr;
|
| 202 |
+
}
|
| 203 |
+
if (bases.size() > 1) {
|
| 204 |
+
pybind11_fail(
|
| 205 |
+
"pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
|
| 206 |
+
}
|
| 207 |
+
return bases.front();
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
inline detail::type_info *get_local_type_info(const std::type_index &tp) {
|
| 211 |
+
auto &locals = get_local_internals().registered_types_cpp;
|
| 212 |
+
auto it = locals.find(tp);
|
| 213 |
+
if (it != locals.end()) {
|
| 214 |
+
return it->second;
|
| 215 |
+
}
|
| 216 |
+
return nullptr;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
inline detail::type_info *get_global_type_info(const std::type_index &tp) {
|
| 220 |
+
auto &types = get_internals().registered_types_cpp;
|
| 221 |
+
auto it = types.find(tp);
|
| 222 |
+
if (it != types.end()) {
|
| 223 |
+
return it->second;
|
| 224 |
+
}
|
| 225 |
+
return nullptr;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
/// Return the type info for a given C++ type; on lookup failure can either throw or return
|
| 229 |
+
/// nullptr.
|
| 230 |
+
PYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_index &tp,
|
| 231 |
+
bool throw_if_missing = false) {
|
| 232 |
+
if (auto *ltype = get_local_type_info(tp)) {
|
| 233 |
+
return ltype;
|
| 234 |
+
}
|
| 235 |
+
if (auto *gtype = get_global_type_info(tp)) {
|
| 236 |
+
return gtype;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
if (throw_if_missing) {
|
| 240 |
+
std::string tname = tp.name();
|
| 241 |
+
detail::clean_type_id(tname);
|
| 242 |
+
pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \""
|
| 243 |
+
+ std::move(tname) + '"');
|
| 244 |
+
}
|
| 245 |
+
return nullptr;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
|
| 249 |
+
detail::type_info *type_info = get_type_info(tp, throw_if_missing);
|
| 250 |
+
return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// Searches the inheritance graph for a registered Python instance, using all_type_info().
|
| 254 |
+
PYBIND11_NOINLINE handle find_registered_python_instance(void *src,
|
| 255 |
+
const detail::type_info *tinfo) {
|
| 256 |
+
auto it_instances = get_internals().registered_instances.equal_range(src);
|
| 257 |
+
for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
|
| 258 |
+
for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
|
| 259 |
+
if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {
|
| 260 |
+
return handle((PyObject *) it_i->second).inc_ref();
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
return handle();
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
struct value_and_holder {
|
| 268 |
+
instance *inst = nullptr;
|
| 269 |
+
size_t index = 0u;
|
| 270 |
+
const detail::type_info *type = nullptr;
|
| 271 |
+
void **vh = nullptr;
|
| 272 |
+
|
| 273 |
+
// Main constructor for a found value/holder:
|
| 274 |
+
value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
|
| 275 |
+
: inst{i}, index{index}, type{type},
|
| 276 |
+
vh{inst->simple_layout ? inst->simple_value_holder
|
| 277 |
+
: &inst->nonsimple.values_and_holders[vpos]} {}
|
| 278 |
+
|
| 279 |
+
// Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
|
| 280 |
+
value_and_holder() = default;
|
| 281 |
+
|
| 282 |
+
// Used for past-the-end iterator
|
| 283 |
+
explicit value_and_holder(size_t index) : index{index} {}
|
| 284 |
+
|
| 285 |
+
template <typename V = void>
|
| 286 |
+
V *&value_ptr() const {
|
| 287 |
+
return reinterpret_cast<V *&>(vh[0]);
|
| 288 |
+
}
|
| 289 |
+
// True if this `value_and_holder` has a non-null value pointer
|
| 290 |
+
explicit operator bool() const { return value_ptr() != nullptr; }
|
| 291 |
+
|
| 292 |
+
template <typename H>
|
| 293 |
+
H &holder() const {
|
| 294 |
+
return reinterpret_cast<H &>(vh[1]);
|
| 295 |
+
}
|
| 296 |
+
bool holder_constructed() const {
|
| 297 |
+
return inst->simple_layout
|
| 298 |
+
? inst->simple_holder_constructed
|
| 299 |
+
: (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;
|
| 300 |
+
}
|
| 301 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
| 302 |
+
void set_holder_constructed(bool v = true) {
|
| 303 |
+
if (inst->simple_layout) {
|
| 304 |
+
inst->simple_holder_constructed = v;
|
| 305 |
+
} else if (v) {
|
| 306 |
+
inst->nonsimple.status[index] |= instance::status_holder_constructed;
|
| 307 |
+
} else {
|
| 308 |
+
inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
bool instance_registered() const {
|
| 312 |
+
return inst->simple_layout
|
| 313 |
+
? inst->simple_instance_registered
|
| 314 |
+
: ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);
|
| 315 |
+
}
|
| 316 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
| 317 |
+
void set_instance_registered(bool v = true) {
|
| 318 |
+
if (inst->simple_layout) {
|
| 319 |
+
inst->simple_instance_registered = v;
|
| 320 |
+
} else if (v) {
|
| 321 |
+
inst->nonsimple.status[index] |= instance::status_instance_registered;
|
| 322 |
+
} else {
|
| 323 |
+
inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
};
|
| 327 |
+
|
| 328 |
+
// Container for accessing and iterating over an instance's values/holders
|
| 329 |
+
struct values_and_holders {
|
| 330 |
+
private:
|
| 331 |
+
instance *inst;
|
| 332 |
+
using type_vec = std::vector<detail::type_info *>;
|
| 333 |
+
const type_vec &tinfo;
|
| 334 |
+
|
| 335 |
+
public:
|
| 336 |
+
explicit values_and_holders(instance *inst)
|
| 337 |
+
: inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
|
| 338 |
+
|
| 339 |
+
explicit values_and_holders(PyObject *obj)
|
| 340 |
+
: inst{nullptr}, tinfo(all_type_info(Py_TYPE(obj))) {
|
| 341 |
+
if (!tinfo.empty()) {
|
| 342 |
+
inst = reinterpret_cast<instance *>(obj);
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
struct iterator {
|
| 347 |
+
private:
|
| 348 |
+
instance *inst = nullptr;
|
| 349 |
+
const type_vec *types = nullptr;
|
| 350 |
+
value_and_holder curr;
|
| 351 |
+
friend struct values_and_holders;
|
| 352 |
+
iterator(instance *inst, const type_vec *tinfo) : inst{inst}, types{tinfo} {
|
| 353 |
+
if (inst != nullptr) {
|
| 354 |
+
assert(!types->empty());
|
| 355 |
+
curr = value_and_holder(
|
| 356 |
+
inst /* instance */,
|
| 357 |
+
(*types)[0] /* type info */,
|
| 358 |
+
0, /* vpos: (non-simple types only): the first vptr comes first */
|
| 359 |
+
0 /* index */);
|
| 360 |
+
}
|
| 361 |
+
}
|
| 362 |
+
// Past-the-end iterator:
|
| 363 |
+
explicit iterator(size_t end) : curr(end) {}
|
| 364 |
+
|
| 365 |
+
public:
|
| 366 |
+
bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
|
| 367 |
+
bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
|
| 368 |
+
iterator &operator++() {
|
| 369 |
+
if (!inst->simple_layout) {
|
| 370 |
+
curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
|
| 371 |
+
}
|
| 372 |
+
++curr.index;
|
| 373 |
+
curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
|
| 374 |
+
return *this;
|
| 375 |
+
}
|
| 376 |
+
value_and_holder &operator*() { return curr; }
|
| 377 |
+
value_and_holder *operator->() { return &curr; }
|
| 378 |
+
};
|
| 379 |
+
|
| 380 |
+
iterator begin() { return iterator(inst, &tinfo); }
|
| 381 |
+
iterator end() { return iterator(tinfo.size()); }
|
| 382 |
+
|
| 383 |
+
iterator find(const type_info *find_type) {
|
| 384 |
+
auto it = begin(), endit = end();
|
| 385 |
+
while (it != endit && it->type != find_type) {
|
| 386 |
+
++it;
|
| 387 |
+
}
|
| 388 |
+
return it;
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
size_t size() { return tinfo.size(); }
|
| 392 |
+
|
| 393 |
+
// Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.
|
| 394 |
+
bool is_redundant_value_and_holder(const value_and_holder &vh) {
|
| 395 |
+
for (size_t i = 0; i < vh.index; i++) {
|
| 396 |
+
if (PyType_IsSubtype(tinfo[i]->type, tinfo[vh.index]->type) != 0) {
|
| 397 |
+
return true;
|
| 398 |
+
}
|
| 399 |
+
}
|
| 400 |
+
return false;
|
| 401 |
+
}
|
| 402 |
+
};
|
| 403 |
+
|
| 404 |
+
/**
|
| 405 |
+
* Extracts C++ value and holder pointer references from an instance (which may contain multiple
|
| 406 |
+
* values/holders for python-side multiple inheritance) that match the given type. Throws an error
|
| 407 |
+
* if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
|
| 408 |
+
* `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
|
| 409 |
+
* regardless of type (and the resulting .type will be nullptr).
|
| 410 |
+
*
|
| 411 |
+
* The returned object should be short-lived: in particular, it must not outlive the called-upon
|
| 412 |
+
* instance.
|
| 413 |
+
*/
|
| 414 |
+
PYBIND11_NOINLINE value_and_holder
|
| 415 |
+
instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,
|
| 416 |
+
bool throw_if_missing /*= true in common.h*/) {
|
| 417 |
+
// Optimize common case:
|
| 418 |
+
if (!find_type || Py_TYPE(this) == find_type->type) {
|
| 419 |
+
return value_and_holder(this, find_type, 0, 0);
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
detail::values_and_holders vhs(this);
|
| 423 |
+
auto it = vhs.find(find_type);
|
| 424 |
+
if (it != vhs.end()) {
|
| 425 |
+
return *it;
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
if (!throw_if_missing) {
|
| 429 |
+
return value_and_holder();
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
| 433 |
+
pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
|
| 434 |
+
+ get_fully_qualified_tp_name(find_type->type)
|
| 435 |
+
+ "' is not a pybind11 base of the given `"
|
| 436 |
+
+ get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
|
| 437 |
+
#else
|
| 438 |
+
pybind11_fail(
|
| 439 |
+
"pybind11::detail::instance::get_value_and_holder: "
|
| 440 |
+
"type is not a pybind11 base of the given instance "
|
| 441 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for type details)");
|
| 442 |
+
#endif
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
PYBIND11_NOINLINE void instance::allocate_layout() {
|
| 446 |
+
const auto &tinfo = all_type_info(Py_TYPE(this));
|
| 447 |
+
|
| 448 |
+
const size_t n_types = tinfo.size();
|
| 449 |
+
|
| 450 |
+
if (n_types == 0) {
|
| 451 |
+
pybind11_fail(
|
| 452 |
+
"instance allocation failed: new instance has no pybind11-registered base types");
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
simple_layout
|
| 456 |
+
= n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
|
| 457 |
+
|
| 458 |
+
// Simple path: no python-side multiple inheritance, and a small-enough holder
|
| 459 |
+
if (simple_layout) {
|
| 460 |
+
simple_value_holder[0] = nullptr;
|
| 461 |
+
simple_holder_constructed = false;
|
| 462 |
+
simple_instance_registered = false;
|
| 463 |
+
} else { // multiple base types or a too-large holder
|
| 464 |
+
// Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
|
| 465 |
+
// [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
|
| 466 |
+
// values that tracks whether each associated holder has been initialized. Each [block] is
|
| 467 |
+
// padded, if necessary, to an integer multiple of sizeof(void *).
|
| 468 |
+
size_t space = 0;
|
| 469 |
+
for (auto *t : tinfo) {
|
| 470 |
+
space += 1; // value pointer
|
| 471 |
+
space += t->holder_size_in_ptrs; // holder instance
|
| 472 |
+
}
|
| 473 |
+
size_t flags_at = space;
|
| 474 |
+
space += size_in_ptrs(n_types); // status bytes (holder_constructed and
|
| 475 |
+
// instance_registered)
|
| 476 |
+
|
| 477 |
+
// Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
|
| 478 |
+
// in particular, need to be 0). Use Python's memory allocation
|
| 479 |
+
// functions: Python is using pymalloc, which is designed to be
|
| 480 |
+
// efficient for small allocations like the one we're doing here;
|
| 481 |
+
// for larger allocations they are just wrappers around malloc.
|
| 482 |
+
// TODO: is this still true for pure Python 3.6?
|
| 483 |
+
nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
|
| 484 |
+
if (!nonsimple.values_and_holders) {
|
| 485 |
+
throw std::bad_alloc();
|
| 486 |
+
}
|
| 487 |
+
nonsimple.status
|
| 488 |
+
= reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
|
| 489 |
+
}
|
| 490 |
+
owned = true;
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
// NOLINTNEXTLINE(readability-make-member-function-const)
|
| 494 |
+
PYBIND11_NOINLINE void instance::deallocate_layout() {
|
| 495 |
+
if (!simple_layout) {
|
| 496 |
+
PyMem_Free(nonsimple.values_and_holders);
|
| 497 |
+
}
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
|
| 501 |
+
handle type = detail::get_type_handle(tp, false);
|
| 502 |
+
if (!type) {
|
| 503 |
+
return false;
|
| 504 |
+
}
|
| 505 |
+
return isinstance(obj, type);
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
|
| 509 |
+
auto &instances = get_internals().registered_instances;
|
| 510 |
+
auto range = instances.equal_range(ptr);
|
| 511 |
+
for (auto it = range.first; it != range.second; ++it) {
|
| 512 |
+
for (const auto &vh : values_and_holders(it->second)) {
|
| 513 |
+
if (vh.type == type) {
|
| 514 |
+
return handle((PyObject *) it->second);
|
| 515 |
+
}
|
| 516 |
+
}
|
| 517 |
+
}
|
| 518 |
+
return handle();
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
inline PyThreadState *get_thread_state_unchecked() {
|
| 522 |
+
#if defined(PYPY_VERSION)
|
| 523 |
+
return PyThreadState_GET();
|
| 524 |
+
#elif PY_VERSION_HEX < 0x030D0000
|
| 525 |
+
return _PyThreadState_UncheckedGet();
|
| 526 |
+
#else
|
| 527 |
+
return PyThreadState_GetUnchecked();
|
| 528 |
+
#endif
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
// Forward declarations
|
| 532 |
+
void keep_alive_impl(handle nurse, handle patient);
|
| 533 |
+
inline PyObject *make_new_instance(PyTypeObject *type);
|
| 534 |
+
|
| 535 |
+
class type_caster_generic {
|
| 536 |
+
public:
|
| 537 |
+
PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
|
| 538 |
+
: typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
|
| 539 |
+
|
| 540 |
+
explicit type_caster_generic(const type_info *typeinfo)
|
| 541 |
+
: typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
|
| 542 |
+
|
| 543 |
+
bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
|
| 544 |
+
|
| 545 |
+
PYBIND11_NOINLINE static handle cast(const void *_src,
|
| 546 |
+
return_value_policy policy,
|
| 547 |
+
handle parent,
|
| 548 |
+
const detail::type_info *tinfo,
|
| 549 |
+
void *(*copy_constructor)(const void *),
|
| 550 |
+
void *(*move_constructor)(const void *),
|
| 551 |
+
const void *existing_holder = nullptr) {
|
| 552 |
+
if (!tinfo) { // no type info: error will be set already
|
| 553 |
+
return handle();
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
void *src = const_cast<void *>(_src);
|
| 557 |
+
if (src == nullptr) {
|
| 558 |
+
return none().release();
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
|
| 562 |
+
return registered_inst;
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
|
| 566 |
+
auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
|
| 567 |
+
wrapper->owned = false;
|
| 568 |
+
void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
|
| 569 |
+
|
| 570 |
+
switch (policy) {
|
| 571 |
+
case return_value_policy::automatic:
|
| 572 |
+
case return_value_policy::take_ownership:
|
| 573 |
+
valueptr = src;
|
| 574 |
+
wrapper->owned = true;
|
| 575 |
+
break;
|
| 576 |
+
|
| 577 |
+
case return_value_policy::automatic_reference:
|
| 578 |
+
case return_value_policy::reference:
|
| 579 |
+
valueptr = src;
|
| 580 |
+
wrapper->owned = false;
|
| 581 |
+
break;
|
| 582 |
+
|
| 583 |
+
case return_value_policy::copy:
|
| 584 |
+
if (copy_constructor) {
|
| 585 |
+
valueptr = copy_constructor(src);
|
| 586 |
+
} else {
|
| 587 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
| 588 |
+
std::string type_name(tinfo->cpptype->name());
|
| 589 |
+
detail::clean_type_id(type_name);
|
| 590 |
+
throw cast_error("return_value_policy = copy, but type " + type_name
|
| 591 |
+
+ " is non-copyable!");
|
| 592 |
+
#else
|
| 593 |
+
throw cast_error("return_value_policy = copy, but type is "
|
| 594 |
+
"non-copyable! (#define PYBIND11_DETAILED_ERROR_MESSAGES or "
|
| 595 |
+
"compile in debug mode for details)");
|
| 596 |
+
#endif
|
| 597 |
+
}
|
| 598 |
+
wrapper->owned = true;
|
| 599 |
+
break;
|
| 600 |
+
|
| 601 |
+
case return_value_policy::move:
|
| 602 |
+
if (move_constructor) {
|
| 603 |
+
valueptr = move_constructor(src);
|
| 604 |
+
} else if (copy_constructor) {
|
| 605 |
+
valueptr = copy_constructor(src);
|
| 606 |
+
} else {
|
| 607 |
+
#if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
|
| 608 |
+
std::string type_name(tinfo->cpptype->name());
|
| 609 |
+
detail::clean_type_id(type_name);
|
| 610 |
+
throw cast_error("return_value_policy = move, but type " + type_name
|
| 611 |
+
+ " is neither movable nor copyable!");
|
| 612 |
+
#else
|
| 613 |
+
throw cast_error("return_value_policy = move, but type is neither "
|
| 614 |
+
"movable nor copyable! "
|
| 615 |
+
"(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in "
|
| 616 |
+
"debug mode for details)");
|
| 617 |
+
#endif
|
| 618 |
+
}
|
| 619 |
+
wrapper->owned = true;
|
| 620 |
+
break;
|
| 621 |
+
|
| 622 |
+
case return_value_policy::reference_internal:
|
| 623 |
+
valueptr = src;
|
| 624 |
+
wrapper->owned = false;
|
| 625 |
+
keep_alive_impl(inst, parent);
|
| 626 |
+
break;
|
| 627 |
+
|
| 628 |
+
default:
|
| 629 |
+
throw cast_error("unhandled return_value_policy: should not happen!");
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
tinfo->init_instance(wrapper, existing_holder);
|
| 633 |
+
|
| 634 |
+
return inst.release();
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
// Base methods for generic caster; there are overridden in copyable_holder_caster
|
| 638 |
+
void load_value(value_and_holder &&v_h) {
|
| 639 |
+
auto *&vptr = v_h.value_ptr();
|
| 640 |
+
// Lazy allocation for unallocated values:
|
| 641 |
+
if (vptr == nullptr) {
|
| 642 |
+
const auto *type = v_h.type ? v_h.type : typeinfo;
|
| 643 |
+
if (type->operator_new) {
|
| 644 |
+
vptr = type->operator_new(type->type_size);
|
| 645 |
+
} else {
|
| 646 |
+
#if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
|
| 647 |
+
if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
|
| 648 |
+
vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
|
| 649 |
+
} else {
|
| 650 |
+
vptr = ::operator new(type->type_size);
|
| 651 |
+
}
|
| 652 |
+
#else
|
| 653 |
+
vptr = ::operator new(type->type_size);
|
| 654 |
+
#endif
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
value = vptr;
|
| 658 |
+
}
|
| 659 |
+
bool try_implicit_casts(handle src, bool convert) {
|
| 660 |
+
for (const auto &cast : typeinfo->implicit_casts) {
|
| 661 |
+
type_caster_generic sub_caster(*cast.first);
|
| 662 |
+
if (sub_caster.load(src, convert)) {
|
| 663 |
+
value = cast.second(sub_caster.value);
|
| 664 |
+
return true;
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
return false;
|
| 668 |
+
}
|
| 669 |
+
bool try_direct_conversions(handle src) {
|
| 670 |
+
for (auto &converter : *typeinfo->direct_conversions) {
|
| 671 |
+
if (converter(src.ptr(), value)) {
|
| 672 |
+
return true;
|
| 673 |
+
}
|
| 674 |
+
}
|
| 675 |
+
return false;
|
| 676 |
+
}
|
| 677 |
+
void check_holder_compat() {}
|
| 678 |
+
|
| 679 |
+
PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
|
| 680 |
+
auto caster = type_caster_generic(ti);
|
| 681 |
+
if (caster.load(src, false)) {
|
| 682 |
+
return caster.value;
|
| 683 |
+
}
|
| 684 |
+
return nullptr;
|
| 685 |
+
}
|
| 686 |
+
|
| 687 |
+
/// Try to load with foreign typeinfo, if available. Used when there is no
|
| 688 |
+
/// native typeinfo, or when the native one wasn't able to produce a value.
|
| 689 |
+
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
|
| 690 |
+
constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
|
| 691 |
+
const auto pytype = type::handle_of(src);
|
| 692 |
+
if (!hasattr(pytype, local_key)) {
|
| 693 |
+
return false;
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
|
| 697 |
+
// Only consider this foreign loader if actually foreign and is a loader of the correct cpp
|
| 698 |
+
// type
|
| 699 |
+
if (foreign_typeinfo->module_local_load == &local_load
|
| 700 |
+
|| (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
|
| 701 |
+
return false;
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
|
| 705 |
+
value = result;
|
| 706 |
+
return true;
|
| 707 |
+
}
|
| 708 |
+
return false;
|
| 709 |
+
}
|
| 710 |
+
|
| 711 |
+
// Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
|
| 712 |
+
// bits of code between here and copyable_holder_caster where the two classes need different
|
| 713 |
+
// logic (without having to resort to virtual inheritance).
|
| 714 |
+
template <typename ThisT>
|
| 715 |
+
PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
|
| 716 |
+
if (!src) {
|
| 717 |
+
return false;
|
| 718 |
+
}
|
| 719 |
+
if (!typeinfo) {
|
| 720 |
+
return try_load_foreign_module_local(src);
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
auto &this_ = static_cast<ThisT &>(*this);
|
| 724 |
+
this_.check_holder_compat();
|
| 725 |
+
|
| 726 |
+
PyTypeObject *srctype = Py_TYPE(src.ptr());
|
| 727 |
+
|
| 728 |
+
// Case 1: If src is an exact type match for the target type then we can reinterpret_cast
|
| 729 |
+
// the instance's value pointer to the target type:
|
| 730 |
+
if (srctype == typeinfo->type) {
|
| 731 |
+
this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
|
| 732 |
+
return true;
|
| 733 |
+
}
|
| 734 |
+
// Case 2: We have a derived class
|
| 735 |
+
if (PyType_IsSubtype(srctype, typeinfo->type)) {
|
| 736 |
+
const auto &bases = all_type_info(srctype);
|
| 737 |
+
bool no_cpp_mi = typeinfo->simple_type;
|
| 738 |
+
|
| 739 |
+
// Case 2a: the python type is a Python-inherited derived class that inherits from just
|
| 740 |
+
// one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
|
| 741 |
+
// the right type and we can use reinterpret_cast.
|
| 742 |
+
// (This is essentially the same as case 2b, but because not using multiple inheritance
|
| 743 |
+
// is extremely common, we handle it specially to avoid the loop iterator and type
|
| 744 |
+
// pointer lookup overhead)
|
| 745 |
+
if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
|
| 746 |
+
this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
|
| 747 |
+
return true;
|
| 748 |
+
}
|
| 749 |
+
// Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
|
| 750 |
+
// if we can find an exact match (or, for a simple C++ type, an inherited match); if
|
| 751 |
+
// so, we can safely reinterpret_cast to the relevant pointer.
|
| 752 |
+
if (bases.size() > 1) {
|
| 753 |
+
for (auto *base : bases) {
|
| 754 |
+
if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
|
| 755 |
+
: base->type == typeinfo->type) {
|
| 756 |
+
this_.load_value(
|
| 757 |
+
reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
|
| 758 |
+
return true;
|
| 759 |
+
}
|
| 760 |
+
}
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
// Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
|
| 764 |
+
// match in the registered bases, above, so try implicit casting (needed for proper C++
|
| 765 |
+
// casting when MI is involved).
|
| 766 |
+
if (this_.try_implicit_casts(src, convert)) {
|
| 767 |
+
return true;
|
| 768 |
+
}
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
// Perform an implicit conversion
|
| 772 |
+
if (convert) {
|
| 773 |
+
for (const auto &converter : typeinfo->implicit_conversions) {
|
| 774 |
+
auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
|
| 775 |
+
if (load_impl<ThisT>(temp, false)) {
|
| 776 |
+
loader_life_support::add_patient(temp);
|
| 777 |
+
return true;
|
| 778 |
+
}
|
| 779 |
+
}
|
| 780 |
+
if (this_.try_direct_conversions(src)) {
|
| 781 |
+
return true;
|
| 782 |
+
}
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
// Failed to match local typeinfo. Try again with global.
|
| 786 |
+
if (typeinfo->module_local) {
|
| 787 |
+
if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
|
| 788 |
+
typeinfo = gtype;
|
| 789 |
+
return load(src, false);
|
| 790 |
+
}
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
// Global typeinfo has precedence over foreign module_local
|
| 794 |
+
if (try_load_foreign_module_local(src)) {
|
| 795 |
+
return true;
|
| 796 |
+
}
|
| 797 |
+
|
| 798 |
+
// Custom converters didn't take None, now we convert None to nullptr.
|
| 799 |
+
if (src.is_none()) {
|
| 800 |
+
// Defer accepting None to other overloads (if we aren't in convert mode):
|
| 801 |
+
if (!convert) {
|
| 802 |
+
return false;
|
| 803 |
+
}
|
| 804 |
+
value = nullptr;
|
| 805 |
+
return true;
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
return false;
|
| 809 |
+
}
|
| 810 |
+
|
| 811 |
+
// Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
|
| 812 |
+
// isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
|
| 813 |
+
// with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
|
| 814 |
+
PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
|
| 815 |
+
src_and_type(const void *src,
|
| 816 |
+
const std::type_info &cast_type,
|
| 817 |
+
const std::type_info *rtti_type = nullptr) {
|
| 818 |
+
if (auto *tpi = get_type_info(cast_type)) {
|
| 819 |
+
return {src, const_cast<const type_info *>(tpi)};
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
// Not found, set error:
|
| 823 |
+
std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
|
| 824 |
+
detail::clean_type_id(tname);
|
| 825 |
+
std::string msg = "Unregistered type : " + tname;
|
| 826 |
+
set_error(PyExc_TypeError, msg.c_str());
|
| 827 |
+
return {nullptr, nullptr};
|
| 828 |
+
}
|
| 829 |
+
|
| 830 |
+
const type_info *typeinfo = nullptr;
|
| 831 |
+
const std::type_info *cpptype = nullptr;
|
| 832 |
+
void *value = nullptr;
|
| 833 |
+
};
|
| 834 |
+
|
| 835 |
+
/**
|
| 836 |
+
* Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
|
| 837 |
+
* needs to provide `operator T*()` and `operator T&()` operators.
|
| 838 |
+
*
|
| 839 |
+
* If the type supports moving the value away via an `operator T&&() &&` method, it should use
|
| 840 |
+
* `movable_cast_op_type` instead.
|
| 841 |
+
*/
|
| 842 |
+
template <typename T>
|
| 843 |
+
using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
|
| 844 |
+
typename std::add_pointer<intrinsic_t<T>>::type,
|
| 845 |
+
typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
|
| 846 |
+
|
| 847 |
+
/**
|
| 848 |
+
* Determine suitable casting operator for a type caster with a movable value. Such a type caster
|
| 849 |
+
* needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
|
| 850 |
+
* called in appropriate contexts where the value can be moved rather than copied.
|
| 851 |
+
*
|
| 852 |
+
* These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
|
| 853 |
+
*/
|
| 854 |
+
template <typename T>
|
| 855 |
+
using movable_cast_op_type
|
| 856 |
+
= conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
|
| 857 |
+
typename std::add_pointer<intrinsic_t<T>>::type,
|
| 858 |
+
conditional_t<std::is_rvalue_reference<T>::value,
|
| 859 |
+
typename std::add_rvalue_reference<intrinsic_t<T>>::type,
|
| 860 |
+
typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
|
| 861 |
+
|
| 862 |
+
// Does the container have a mapped type and is it recursive?
|
| 863 |
+
// Implemented by specializations below.
|
| 864 |
+
template <typename Container, typename SFINAE = void>
|
| 865 |
+
struct container_mapped_type_traits {
|
| 866 |
+
static constexpr bool has_mapped_type = false;
|
| 867 |
+
static constexpr bool has_recursive_mapped_type = false;
|
| 868 |
+
};
|
| 869 |
+
|
| 870 |
+
template <typename Container>
|
| 871 |
+
struct container_mapped_type_traits<
|
| 872 |
+
Container,
|
| 873 |
+
typename std::enable_if<
|
| 874 |
+
std::is_same<typename Container::mapped_type, Container>::value>::type> {
|
| 875 |
+
static constexpr bool has_mapped_type = true;
|
| 876 |
+
static constexpr bool has_recursive_mapped_type = true;
|
| 877 |
+
};
|
| 878 |
+
|
| 879 |
+
template <typename Container>
|
| 880 |
+
struct container_mapped_type_traits<
|
| 881 |
+
Container,
|
| 882 |
+
typename std::enable_if<
|
| 883 |
+
negation<std::is_same<typename Container::mapped_type, Container>>::value>::type> {
|
| 884 |
+
static constexpr bool has_mapped_type = true;
|
| 885 |
+
static constexpr bool has_recursive_mapped_type = false;
|
| 886 |
+
};
|
| 887 |
+
|
| 888 |
+
// Does the container have a value type and is it recursive?
|
| 889 |
+
// Implemented by specializations below.
|
| 890 |
+
template <typename Container, typename SFINAE = void>
|
| 891 |
+
struct container_value_type_traits : std::false_type {
|
| 892 |
+
static constexpr bool has_value_type = false;
|
| 893 |
+
static constexpr bool has_recursive_value_type = false;
|
| 894 |
+
};
|
| 895 |
+
|
| 896 |
+
template <typename Container>
|
| 897 |
+
struct container_value_type_traits<
|
| 898 |
+
Container,
|
| 899 |
+
typename std::enable_if<
|
| 900 |
+
std::is_same<typename Container::value_type, Container>::value>::type> {
|
| 901 |
+
static constexpr bool has_value_type = true;
|
| 902 |
+
static constexpr bool has_recursive_value_type = true;
|
| 903 |
+
};
|
| 904 |
+
|
| 905 |
+
template <typename Container>
|
| 906 |
+
struct container_value_type_traits<
|
| 907 |
+
Container,
|
| 908 |
+
typename std::enable_if<
|
| 909 |
+
negation<std::is_same<typename Container::value_type, Container>>::value>::type> {
|
| 910 |
+
static constexpr bool has_value_type = true;
|
| 911 |
+
static constexpr bool has_recursive_value_type = false;
|
| 912 |
+
};
|
| 913 |
+
|
| 914 |
+
/*
|
| 915 |
+
* Tag to be used for representing the bottom of recursively defined types.
|
| 916 |
+
* Define this tag so we don't have to use void.
|
| 917 |
+
*/
|
| 918 |
+
struct recursive_bottom {};
|
| 919 |
+
|
| 920 |
+
/*
|
| 921 |
+
* Implementation detail of `recursive_container_traits` below.
|
| 922 |
+
* `T` is the `value_type` of the container, which might need to be modified to
|
| 923 |
+
* avoid recursive types and const types.
|
| 924 |
+
*/
|
| 925 |
+
template <typename T, bool is_this_a_map>
|
| 926 |
+
struct impl_type_to_check_recursively {
|
| 927 |
+
/*
|
| 928 |
+
* If the container is recursive, then no further recursion should be done.
|
| 929 |
+
*/
|
| 930 |
+
using if_recursive = recursive_bottom;
|
| 931 |
+
/*
|
| 932 |
+
* Otherwise yield `T` unchanged.
|
| 933 |
+
*/
|
| 934 |
+
using if_not_recursive = T;
|
| 935 |
+
};
|
| 936 |
+
|
| 937 |
+
/*
|
| 938 |
+
* For pairs - only as value type of a map -, the first type should remove the `const`.
|
| 939 |
+
* Also, if the map is recursive, then the recursive checking should consider
|
| 940 |
+
* the first type only.
|
| 941 |
+
*/
|
| 942 |
+
template <typename A, typename B>
|
| 943 |
+
struct impl_type_to_check_recursively<std::pair<A, B>, /* is_this_a_map = */ true> {
|
| 944 |
+
using if_recursive = typename std::remove_const<A>::type;
|
| 945 |
+
using if_not_recursive = std::pair<typename std::remove_const<A>::type, B>;
|
| 946 |
+
};
|
| 947 |
+
|
| 948 |
+
/*
|
| 949 |
+
* Implementation of `recursive_container_traits` below.
|
| 950 |
+
*/
|
| 951 |
+
template <typename Container, typename SFINAE = void>
|
| 952 |
+
struct impl_recursive_container_traits {
|
| 953 |
+
using type_to_check_recursively = recursive_bottom;
|
| 954 |
+
};
|
| 955 |
+
|
| 956 |
+
template <typename Container>
|
| 957 |
+
struct impl_recursive_container_traits<
|
| 958 |
+
Container,
|
| 959 |
+
typename std::enable_if<container_value_type_traits<Container>::has_value_type>::type> {
|
| 960 |
+
static constexpr bool is_recursive
|
| 961 |
+
= container_mapped_type_traits<Container>::has_recursive_mapped_type
|
| 962 |
+
|| container_value_type_traits<Container>::has_recursive_value_type;
|
| 963 |
+
/*
|
| 964 |
+
* This member dictates which type Pybind11 should check recursively in traits
|
| 965 |
+
* such as `is_move_constructible`, `is_copy_constructible`, `is_move_assignable`, ...
|
| 966 |
+
* Direct access to `value_type` should be avoided:
|
| 967 |
+
* 1. `value_type` might recursively contain the type again
|
| 968 |
+
* 2. `value_type` of STL map types is `std::pair<A const, B>`, the `const`
|
| 969 |
+
* should be removed.
|
| 970 |
+
*
|
| 971 |
+
*/
|
| 972 |
+
using type_to_check_recursively = typename std::conditional<
|
| 973 |
+
is_recursive,
|
| 974 |
+
typename impl_type_to_check_recursively<
|
| 975 |
+
typename Container::value_type,
|
| 976 |
+
container_mapped_type_traits<Container>::has_mapped_type>::if_recursive,
|
| 977 |
+
typename impl_type_to_check_recursively<
|
| 978 |
+
typename Container::value_type,
|
| 979 |
+
container_mapped_type_traits<Container>::has_mapped_type>::if_not_recursive>::type;
|
| 980 |
+
};
|
| 981 |
+
|
| 982 |
+
/*
|
| 983 |
+
* This trait defines the `type_to_check_recursively` which is needed to properly
|
| 984 |
+
* handle recursively defined traits such as `is_move_constructible` without going
|
| 985 |
+
* into an infinite recursion.
|
| 986 |
+
* Should be used instead of directly accessing the `value_type`.
|
| 987 |
+
* It cancels the recursion by returning the `recursive_bottom` tag.
|
| 988 |
+
*
|
| 989 |
+
* The default definition of `type_to_check_recursively` is as follows:
|
| 990 |
+
*
|
| 991 |
+
* 1. By default, it is `recursive_bottom`, so that the recursion is canceled.
|
| 992 |
+
* 2. If the type is non-recursive and defines a `value_type`, then the `value_type` is used.
|
| 993 |
+
* If the `value_type` is a pair and a `mapped_type` is defined,
|
| 994 |
+
* then the `const` is removed from the first type.
|
| 995 |
+
* 3. If the type is recursive and `value_type` is not a pair, then `recursive_bottom` is returned.
|
| 996 |
+
* 4. If the type is recursive and `value_type` is a pair and a `mapped_type` is defined,
|
| 997 |
+
* then `const` is removed from the first type and the first type is returned.
|
| 998 |
+
*
|
| 999 |
+
* This behavior can be extended by the user as seen in test_stl_binders.cpp.
|
| 1000 |
+
*
|
| 1001 |
+
* This struct is exactly the same as impl_recursive_container_traits.
|
| 1002 |
+
* The duplication achieves that user-defined specializations don't compete
|
| 1003 |
+
* with internal specializations, but take precedence.
|
| 1004 |
+
*/
|
| 1005 |
+
template <typename Container, typename SFINAE = void>
|
| 1006 |
+
struct recursive_container_traits : impl_recursive_container_traits<Container> {};
|
| 1007 |
+
|
| 1008 |
+
template <typename T>
|
| 1009 |
+
struct is_move_constructible
|
| 1010 |
+
: all_of<std::is_move_constructible<T>,
|
| 1011 |
+
is_move_constructible<
|
| 1012 |
+
typename recursive_container_traits<T>::type_to_check_recursively>> {};
|
| 1013 |
+
|
| 1014 |
+
template <>
|
| 1015 |
+
struct is_move_constructible<recursive_bottom> : std::true_type {};
|
| 1016 |
+
|
| 1017 |
+
// Likewise for std::pair
|
| 1018 |
+
// (after C++17 it is mandatory that the move constructor not exist when the two types aren't
|
| 1019 |
+
// themselves move constructible, but this can not be relied upon when T1 or T2 are themselves
|
| 1020 |
+
// containers).
|
| 1021 |
+
template <typename T1, typename T2>
|
| 1022 |
+
struct is_move_constructible<std::pair<T1, T2>>
|
| 1023 |
+
: all_of<is_move_constructible<T1>, is_move_constructible<T2>> {};
|
| 1024 |
+
|
| 1025 |
+
// std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
|
| 1026 |
+
// T is non-copyable, but code containing such a copy constructor fails to actually compile.
|
| 1027 |
+
template <typename T>
|
| 1028 |
+
struct is_copy_constructible
|
| 1029 |
+
: all_of<std::is_copy_constructible<T>,
|
| 1030 |
+
is_copy_constructible<
|
| 1031 |
+
typename recursive_container_traits<T>::type_to_check_recursively>> {};
|
| 1032 |
+
|
| 1033 |
+
template <>
|
| 1034 |
+
struct is_copy_constructible<recursive_bottom> : std::true_type {};
|
| 1035 |
+
|
| 1036 |
+
// Likewise for std::pair
|
| 1037 |
+
// (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
|
| 1038 |
+
// themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
|
| 1039 |
+
// containers).
|
| 1040 |
+
template <typename T1, typename T2>
|
| 1041 |
+
struct is_copy_constructible<std::pair<T1, T2>>
|
| 1042 |
+
: all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
|
| 1043 |
+
|
| 1044 |
+
// The same problems arise with std::is_copy_assignable, so we use the same workaround.
|
| 1045 |
+
template <typename T>
|
| 1046 |
+
struct is_copy_assignable
|
| 1047 |
+
: all_of<
|
| 1048 |
+
std::is_copy_assignable<T>,
|
| 1049 |
+
is_copy_assignable<typename recursive_container_traits<T>::type_to_check_recursively>> {
|
| 1050 |
+
};
|
| 1051 |
+
|
| 1052 |
+
template <>
|
| 1053 |
+
struct is_copy_assignable<recursive_bottom> : std::true_type {};
|
| 1054 |
+
|
| 1055 |
+
template <typename T1, typename T2>
|
| 1056 |
+
struct is_copy_assignable<std::pair<T1, T2>>
|
| 1057 |
+
: all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
|
| 1058 |
+
|
| 1059 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 1060 |
+
|
| 1061 |
+
// polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
|
| 1062 |
+
// to by `src` actually is an instance of some class derived from `itype`.
|
| 1063 |
+
// If so, it sets `tinfo` to point to the std::type_info representing that derived
|
| 1064 |
+
// type, and returns a pointer to the start of the most-derived object of that type
|
| 1065 |
+
// (in which `src` is a subobject; this will be the same address as `src` in most
|
| 1066 |
+
// single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
|
| 1067 |
+
// and leaves `tinfo` at its default value of nullptr.
|
| 1068 |
+
//
|
| 1069 |
+
// The default polymorphic_type_hook just returns src. A specialization for polymorphic
|
| 1070 |
+
// types determines the runtime type of the passed object and adjusts the this-pointer
|
| 1071 |
+
// appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
|
| 1072 |
+
// to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
|
| 1073 |
+
// registered with pybind11, and this Animal is in fact a Dog).
|
| 1074 |
+
//
|
| 1075 |
+
// You may specialize polymorphic_type_hook yourself for types that want to appear
|
| 1076 |
+
// polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
|
| 1077 |
+
// in performance-sensitive applications, used most notably in LLVM.)
|
| 1078 |
+
//
|
| 1079 |
+
// polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
|
| 1080 |
+
// std::enable_if. User provided specializations will always have higher priority than
|
| 1081 |
+
// the default implementation and specialization provided in polymorphic_type_hook_base.
|
| 1082 |
+
template <typename itype, typename SFINAE = void>
|
| 1083 |
+
struct polymorphic_type_hook_base {
|
| 1084 |
+
static const void *get(const itype *src, const std::type_info *&) { return src; }
|
| 1085 |
+
};
|
| 1086 |
+
template <typename itype>
|
| 1087 |
+
struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
|
| 1088 |
+
static const void *get(const itype *src, const std::type_info *&type) {
|
| 1089 |
+
type = src ? &typeid(*src) : nullptr;
|
| 1090 |
+
return dynamic_cast<const void *>(src);
|
| 1091 |
+
}
|
| 1092 |
+
};
|
| 1093 |
+
template <typename itype, typename SFINAE = void>
|
| 1094 |
+
struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
|
| 1095 |
+
|
| 1096 |
+
PYBIND11_NAMESPACE_BEGIN(detail)
|
| 1097 |
+
|
| 1098 |
+
/// Generic type caster for objects stored on the heap
|
| 1099 |
+
template <typename type>
|
| 1100 |
+
class type_caster_base : public type_caster_generic {
|
| 1101 |
+
using itype = intrinsic_t<type>;
|
| 1102 |
+
|
| 1103 |
+
public:
|
| 1104 |
+
static constexpr auto name = const_name<type>();
|
| 1105 |
+
|
| 1106 |
+
type_caster_base() : type_caster_base(typeid(type)) {}
|
| 1107 |
+
explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
|
| 1108 |
+
|
| 1109 |
+
static handle cast(const itype &src, return_value_policy policy, handle parent) {
|
| 1110 |
+
if (policy == return_value_policy::automatic
|
| 1111 |
+
|| policy == return_value_policy::automatic_reference) {
|
| 1112 |
+
policy = return_value_policy::copy;
|
| 1113 |
+
}
|
| 1114 |
+
return cast(&src, policy, parent);
|
| 1115 |
+
}
|
| 1116 |
+
|
| 1117 |
+
static handle cast(itype &&src, return_value_policy, handle parent) {
|
| 1118 |
+
return cast(&src, return_value_policy::move, parent);
|
| 1119 |
+
}
|
| 1120 |
+
|
| 1121 |
+
// Returns a (pointer, type_info) pair taking care of necessary type lookup for a
|
| 1122 |
+
// polymorphic type (using RTTI by default, but can be overridden by specializing
|
| 1123 |
+
// polymorphic_type_hook). If the instance isn't derived, returns the base version.
|
| 1124 |
+
static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
|
| 1125 |
+
const auto &cast_type = typeid(itype);
|
| 1126 |
+
const std::type_info *instance_type = nullptr;
|
| 1127 |
+
const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
|
| 1128 |
+
if (instance_type && !same_type(cast_type, *instance_type)) {
|
| 1129 |
+
// This is a base pointer to a derived type. If the derived type is registered
|
| 1130 |
+
// with pybind11, we want to make the full derived object available.
|
| 1131 |
+
// In the typical case where itype is polymorphic, we get the correct
|
| 1132 |
+
// derived pointer (which may be != base pointer) by a dynamic_cast to
|
| 1133 |
+
// most derived type. If itype is not polymorphic, we won't get here
|
| 1134 |
+
// except via a user-provided specialization of polymorphic_type_hook,
|
| 1135 |
+
// and the user has promised that no this-pointer adjustment is
|
| 1136 |
+
// required in that case, so it's OK to use static_cast.
|
| 1137 |
+
if (const auto *tpi = get_type_info(*instance_type)) {
|
| 1138 |
+
return {vsrc, tpi};
|
| 1139 |
+
}
|
| 1140 |
+
}
|
| 1141 |
+
// Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
|
| 1142 |
+
// so don't do a cast
|
| 1143 |
+
return type_caster_generic::src_and_type(src, cast_type, instance_type);
|
| 1144 |
+
}
|
| 1145 |
+
|
| 1146 |
+
static handle cast(const itype *src, return_value_policy policy, handle parent) {
|
| 1147 |
+
auto st = src_and_type(src);
|
| 1148 |
+
return type_caster_generic::cast(st.first,
|
| 1149 |
+
policy,
|
| 1150 |
+
parent,
|
| 1151 |
+
st.second,
|
| 1152 |
+
make_copy_constructor(src),
|
| 1153 |
+
make_move_constructor(src));
|
| 1154 |
+
}
|
| 1155 |
+
|
| 1156 |
+
static handle cast_holder(const itype *src, const void *holder) {
|
| 1157 |
+
auto st = src_and_type(src);
|
| 1158 |
+
return type_caster_generic::cast(st.first,
|
| 1159 |
+
return_value_policy::take_ownership,
|
| 1160 |
+
{},
|
| 1161 |
+
st.second,
|
| 1162 |
+
nullptr,
|
| 1163 |
+
nullptr,
|
| 1164 |
+
holder);
|
| 1165 |
+
}
|
| 1166 |
+
|
| 1167 |
+
template <typename T>
|
| 1168 |
+
using cast_op_type = detail::cast_op_type<T>;
|
| 1169 |
+
|
| 1170 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
| 1171 |
+
operator itype *() { return (type *) value; }
|
| 1172 |
+
// NOLINTNEXTLINE(google-explicit-constructor)
|
| 1173 |
+
operator itype &() {
|
| 1174 |
+
if (!value) {
|
| 1175 |
+
throw reference_cast_error();
|
| 1176 |
+
}
|
| 1177 |
+
return *((itype *) value);
|
| 1178 |
+
}
|
| 1179 |
+
|
| 1180 |
+
protected:
|
| 1181 |
+
using Constructor = void *(*) (const void *);
|
| 1182 |
+
|
| 1183 |
+
/* Only enabled when the types are {copy,move}-constructible *and* when the type
|
| 1184 |
+
does not have a private operator new implementation. A comma operator is used in the
|
| 1185 |
+
decltype argument to apply SFINAE to the public copy/move constructors.*/
|
| 1186 |
+
template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
|
| 1187 |
+
static auto make_copy_constructor(const T *)
|
| 1188 |
+
-> decltype(new T(std::declval<const T>()), Constructor{}) {
|
| 1189 |
+
return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
|
| 1190 |
+
}
|
| 1191 |
+
|
| 1192 |
+
template <typename T, typename = enable_if_t<is_move_constructible<T>::value>>
|
| 1193 |
+
static auto make_move_constructor(const T *)
|
| 1194 |
+
-> decltype(new T(std::declval<T &&>()), Constructor{}) {
|
| 1195 |
+
return [](const void *arg) -> void * {
|
| 1196 |
+
return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
|
| 1197 |
+
};
|
| 1198 |
+
}
|
| 1199 |
+
|
| 1200 |
+
static Constructor make_copy_constructor(...) { return nullptr; }
|
| 1201 |
+
static Constructor make_move_constructor(...) { return nullptr; }
|
| 1202 |
+
};
|
| 1203 |
+
|
| 1204 |
+
inline std::string quote_cpp_type_name(const std::string &cpp_type_name) {
|
| 1205 |
+
return cpp_type_name; // No-op for now. See PR #4888
|
| 1206 |
+
}
|
| 1207 |
+
|
| 1208 |
+
PYBIND11_NOINLINE std::string type_info_description(const std::type_info &ti) {
|
| 1209 |
+
if (auto *type_data = get_type_info(ti)) {
|
| 1210 |
+
handle th((PyObject *) type_data->type);
|
| 1211 |
+
return th.attr("__module__").cast<std::string>() + '.'
|
| 1212 |
+
+ th.attr("__qualname__").cast<std::string>();
|
| 1213 |
+
}
|
| 1214 |
+
return quote_cpp_type_name(clean_type_id(ti.name()));
|
| 1215 |
+
}
|
| 1216 |
+
|
| 1217 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 1218 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
data/home/.local/lib/python3.8/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)
|
data/home/.local/lib/python3.8/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 |
+
"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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
data/home/.local/lib/python3.8/site-packages/torch/include/pybind11/eigen/tensor.h
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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served. 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 = ::pybind11::detail::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
|
| 108 |
+
= ::pybind11::detail::concat(const_name<Indices>()...);
|
| 109 |
+
|
| 110 |
+
template <typename... Args>
|
| 111 |
+
static Type *alloc(Args &&...args) {
|
| 112 |
+
Eigen::aligned_allocator<Type> allocator;
|
| 113 |
+
return ::new (allocator.allocate(1)) Type(std::forward<Args>(args)...);
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
static void free(Type *tensor) {
|
| 117 |
+
Eigen::aligned_allocator<Type> allocator;
|
| 118 |
+
tensor->~Type();
|
| 119 |
+
allocator.deallocate(tensor, 1);
|
| 120 |
+
}
|
| 121 |
+
};
|
| 122 |
+
|
| 123 |
+
template <typename Type, bool ShowDetails, bool NeedsWriteable = false>
|
| 124 |
+
struct get_tensor_descriptor {
|
| 125 |
+
static constexpr auto details
|
| 126 |
+
= const_name<NeedsWriteable>(", flags.writeable", "")
|
| 127 |
+
+ const_name<static_cast<int>(Type::Layout) == static_cast<int>(Eigen::RowMajor)>(
|
| 128 |
+
", flags.c_contiguous", ", flags.f_contiguous");
|
| 129 |
+
static constexpr auto value
|
| 130 |
+
= const_name("numpy.ndarray[") + npy_format_descriptor<typename Type::Scalar>::name
|
| 131 |
+
+ const_name("[") + eigen_tensor_helper<remove_cv_t<Type>>::dimensions_descriptor
|
| 132 |
+
+ const_name("]") + const_name<ShowDetails>(details, const_name("")) + const_name("]");
|
| 133 |
+
};
|
| 134 |
+
|
| 135 |
+
// When EIGEN_AVOID_STL_ARRAY is defined, Eigen::DSizes<T, 0> does not have the begin() member
|
| 136 |
+
// function. Falling back to a simple loop works around this issue.
|
| 137 |
+
//
|
| 138 |
+
// We need to disable the type-limits warning for the inner loop when size = 0.
|
| 139 |
+
|
| 140 |
+
PYBIND11_WARNING_PUSH
|
| 141 |
+
PYBIND11_WARNING_DISABLE_GCC("-Wtype-limits")
|
| 142 |
+
|
| 143 |
+
template <typename T, int size>
|
| 144 |
+
std::vector<T> convert_dsizes_to_vector(const Eigen::DSizes<T, size> &arr) {
|
| 145 |
+
std::vector<T> result(size);
|
| 146 |
+
|
| 147 |
+
for (size_t i = 0; i < size; i++) {
|
| 148 |
+
result[i] = arr[i];
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
return result;
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
template <typename T, int size>
|
| 155 |
+
Eigen::DSizes<T, size> get_shape_for_array(const array &arr) {
|
| 156 |
+
Eigen::DSizes<T, size> result;
|
| 157 |
+
const T *shape = arr.shape();
|
| 158 |
+
for (size_t i = 0; i < size; i++) {
|
| 159 |
+
result[i] = shape[i];
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
return result;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
PYBIND11_WARNING_POP
|
| 166 |
+
|
| 167 |
+
template <typename Type>
|
| 168 |
+
struct type_caster<Type, typename eigen_tensor_helper<Type>::ValidType> {
|
| 169 |
+
static_assert(!std::is_pointer<typename Type::Scalar>::value,
|
| 170 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
| 171 |
+
using Helper = eigen_tensor_helper<Type>;
|
| 172 |
+
static constexpr auto temp_name = get_tensor_descriptor<Type, false>::value;
|
| 173 |
+
PYBIND11_TYPE_CASTER(Type, temp_name);
|
| 174 |
+
|
| 175 |
+
bool load(handle src, bool convert) {
|
| 176 |
+
if (!convert) {
|
| 177 |
+
if (!isinstance<array>(src)) {
|
| 178 |
+
return false;
|
| 179 |
+
}
|
| 180 |
+
array temp = array::ensure(src);
|
| 181 |
+
if (!temp) {
|
| 182 |
+
return false;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
if (!temp.dtype().is(dtype::of<typename Type::Scalar>())) {
|
| 186 |
+
return false;
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()> arr(
|
| 191 |
+
reinterpret_borrow<object>(src));
|
| 192 |
+
|
| 193 |
+
if (arr.ndim() != Type::NumIndices) {
|
| 194 |
+
return false;
|
| 195 |
+
}
|
| 196 |
+
auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
|
| 197 |
+
|
| 198 |
+
if (!Helper::is_correct_shape(shape)) {
|
| 199 |
+
return false;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
#if EIGEN_VERSION_AT_LEAST(3, 4, 0)
|
| 203 |
+
auto data_pointer = arr.data();
|
| 204 |
+
#else
|
| 205 |
+
// Handle Eigen bug
|
| 206 |
+
auto data_pointer = const_cast<typename Type::Scalar *>(arr.data());
|
| 207 |
+
#endif
|
| 208 |
+
|
| 209 |
+
if (is_tensor_aligned(arr.data())) {
|
| 210 |
+
value = Eigen::TensorMap<const Type, Eigen::Aligned>(data_pointer, shape);
|
| 211 |
+
} else {
|
| 212 |
+
value = Eigen::TensorMap<const Type>(data_pointer, shape);
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
return true;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
static handle cast(Type &&src, return_value_policy policy, handle parent) {
|
| 219 |
+
if (policy == return_value_policy::reference
|
| 220 |
+
|| policy == return_value_policy::reference_internal) {
|
| 221 |
+
pybind11_fail("Cannot use a reference return value policy for an rvalue");
|
| 222 |
+
}
|
| 223 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
static handle cast(const Type &&src, return_value_policy policy, handle parent) {
|
| 227 |
+
if (policy == return_value_policy::reference
|
| 228 |
+
|| policy == return_value_policy::reference_internal) {
|
| 229 |
+
pybind11_fail("Cannot use a reference return value policy for an rvalue");
|
| 230 |
+
}
|
| 231 |
+
return cast_impl(&src, return_value_policy::move, parent);
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
static handle cast(Type &src, return_value_policy policy, handle parent) {
|
| 235 |
+
if (policy == return_value_policy::automatic
|
| 236 |
+
|| policy == return_value_policy::automatic_reference) {
|
| 237 |
+
policy = return_value_policy::copy;
|
| 238 |
+
}
|
| 239 |
+
return cast_impl(&src, policy, parent);
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
static handle cast(const Type &src, return_value_policy policy, handle parent) {
|
| 243 |
+
if (policy == return_value_policy::automatic
|
| 244 |
+
|| policy == return_value_policy::automatic_reference) {
|
| 245 |
+
policy = return_value_policy::copy;
|
| 246 |
+
}
|
| 247 |
+
return cast(&src, policy, parent);
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
static handle cast(Type *src, return_value_policy policy, handle parent) {
|
| 251 |
+
if (policy == return_value_policy::automatic) {
|
| 252 |
+
policy = return_value_policy::take_ownership;
|
| 253 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
| 254 |
+
policy = return_value_policy::reference;
|
| 255 |
+
}
|
| 256 |
+
return cast_impl(src, policy, parent);
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
static handle cast(const Type *src, return_value_policy policy, handle parent) {
|
| 260 |
+
if (policy == return_value_policy::automatic) {
|
| 261 |
+
policy = return_value_policy::take_ownership;
|
| 262 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
| 263 |
+
policy = return_value_policy::reference;
|
| 264 |
+
}
|
| 265 |
+
return cast_impl(src, policy, parent);
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
template <typename C>
|
| 269 |
+
static handle cast_impl(C *src, return_value_policy policy, handle parent) {
|
| 270 |
+
object parent_object;
|
| 271 |
+
bool writeable = false;
|
| 272 |
+
switch (policy) {
|
| 273 |
+
case return_value_policy::move:
|
| 274 |
+
if (std::is_const<C>::value) {
|
| 275 |
+
pybind11_fail("Cannot move from a constant reference");
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
src = Helper::alloc(std::move(*src));
|
| 279 |
+
|
| 280 |
+
parent_object
|
| 281 |
+
= capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
|
| 282 |
+
writeable = true;
|
| 283 |
+
break;
|
| 284 |
+
|
| 285 |
+
case return_value_policy::take_ownership:
|
| 286 |
+
if (std::is_const<C>::value) {
|
| 287 |
+
// This cast is ugly, and might be UB in some cases, but we don't have an
|
| 288 |
+
// alternative here as we must free that memory
|
| 289 |
+
Helper::free(const_cast<Type *>(src));
|
| 290 |
+
pybind11_fail("Cannot take ownership of a const reference");
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
parent_object
|
| 294 |
+
= capsule(src, [](void *ptr) { Helper::free(reinterpret_cast<Type *>(ptr)); });
|
| 295 |
+
writeable = true;
|
| 296 |
+
break;
|
| 297 |
+
|
| 298 |
+
case return_value_policy::copy:
|
| 299 |
+
writeable = true;
|
| 300 |
+
break;
|
| 301 |
+
|
| 302 |
+
case return_value_policy::reference:
|
| 303 |
+
parent_object = none();
|
| 304 |
+
writeable = !std::is_const<C>::value;
|
| 305 |
+
break;
|
| 306 |
+
|
| 307 |
+
case return_value_policy::reference_internal:
|
| 308 |
+
// Default should do the right thing
|
| 309 |
+
if (!parent) {
|
| 310 |
+
pybind11_fail("Cannot use reference internal when there is no parent");
|
| 311 |
+
}
|
| 312 |
+
parent_object = reinterpret_borrow<object>(parent);
|
| 313 |
+
writeable = !std::is_const<C>::value;
|
| 314 |
+
break;
|
| 315 |
+
|
| 316 |
+
default:
|
| 317 |
+
pybind11_fail("pybind11 bug in eigen.h, please file a bug report");
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
|
| 321 |
+
convert_dsizes_to_vector(Helper::get_shape(*src)), src->data(), parent_object);
|
| 322 |
+
|
| 323 |
+
if (!writeable) {
|
| 324 |
+
array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
return result.release();
|
| 328 |
+
}
|
| 329 |
+
};
|
| 330 |
+
|
| 331 |
+
template <typename StoragePointerType,
|
| 332 |
+
bool needs_writeable,
|
| 333 |
+
enable_if_t<!needs_writeable, bool> = true>
|
| 334 |
+
StoragePointerType get_array_data_for_type(array &arr) {
|
| 335 |
+
#if EIGEN_VERSION_AT_LEAST(3, 4, 0)
|
| 336 |
+
return reinterpret_cast<StoragePointerType>(arr.data());
|
| 337 |
+
#else
|
| 338 |
+
// Handle Eigen bug
|
| 339 |
+
return reinterpret_cast<StoragePointerType>(const_cast<void *>(arr.data()));
|
| 340 |
+
#endif
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
template <typename StoragePointerType,
|
| 344 |
+
bool needs_writeable,
|
| 345 |
+
enable_if_t<needs_writeable, bool> = true>
|
| 346 |
+
StoragePointerType get_array_data_for_type(array &arr) {
|
| 347 |
+
return reinterpret_cast<StoragePointerType>(arr.mutable_data());
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
template <typename T, typename = void>
|
| 351 |
+
struct get_storage_pointer_type;
|
| 352 |
+
|
| 353 |
+
template <typename MapType>
|
| 354 |
+
struct get_storage_pointer_type<MapType, void_t<typename MapType::StoragePointerType>> {
|
| 355 |
+
using SPT = typename MapType::StoragePointerType;
|
| 356 |
+
};
|
| 357 |
+
|
| 358 |
+
template <typename MapType>
|
| 359 |
+
struct get_storage_pointer_type<MapType, void_t<typename MapType::PointerArgType>> {
|
| 360 |
+
using SPT = typename MapType::PointerArgType;
|
| 361 |
+
};
|
| 362 |
+
|
| 363 |
+
template <typename Type, int Options>
|
| 364 |
+
struct type_caster<Eigen::TensorMap<Type, Options>,
|
| 365 |
+
typename eigen_tensor_helper<remove_cv_t<Type>>::ValidType> {
|
| 366 |
+
static_assert(!std::is_pointer<typename Type::Scalar>::value,
|
| 367 |
+
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
|
| 368 |
+
using MapType = Eigen::TensorMap<Type, Options>;
|
| 369 |
+
using Helper = eigen_tensor_helper<remove_cv_t<Type>>;
|
| 370 |
+
|
| 371 |
+
bool load(handle src, bool /*convert*/) {
|
| 372 |
+
// Note that we have a lot more checks here as we want to make sure to avoid copies
|
| 373 |
+
if (!isinstance<array>(src)) {
|
| 374 |
+
return false;
|
| 375 |
+
}
|
| 376 |
+
auto arr = reinterpret_borrow<array>(src);
|
| 377 |
+
if ((arr.flags() & compute_array_flag_from_tensor<Type>()) == 0) {
|
| 378 |
+
return false;
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
if (!arr.dtype().is(dtype::of<typename Type::Scalar>())) {
|
| 382 |
+
return false;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
if (arr.ndim() != Type::NumIndices) {
|
| 386 |
+
return false;
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
constexpr bool is_aligned = (Options & Eigen::Aligned) != 0;
|
| 390 |
+
|
| 391 |
+
if (is_aligned && !is_tensor_aligned(arr.data())) {
|
| 392 |
+
return false;
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
auto shape = get_shape_for_array<typename Type::Index, Type::NumIndices>(arr);
|
| 396 |
+
|
| 397 |
+
if (!Helper::is_correct_shape(shape)) {
|
| 398 |
+
return false;
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
if (needs_writeable && !arr.writeable()) {
|
| 402 |
+
return false;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
auto result = get_array_data_for_type<typename get_storage_pointer_type<MapType>::SPT,
|
| 406 |
+
needs_writeable>(arr);
|
| 407 |
+
|
| 408 |
+
value.reset(new MapType(std::move(result), std::move(shape)));
|
| 409 |
+
|
| 410 |
+
return true;
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
static handle cast(MapType &&src, return_value_policy policy, handle parent) {
|
| 414 |
+
return cast_impl(&src, policy, parent);
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
static handle cast(const MapType &&src, return_value_policy policy, handle parent) {
|
| 418 |
+
return cast_impl(&src, policy, parent);
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
static handle cast(MapType &src, return_value_policy policy, handle parent) {
|
| 422 |
+
if (policy == return_value_policy::automatic
|
| 423 |
+
|| policy == return_value_policy::automatic_reference) {
|
| 424 |
+
policy = return_value_policy::copy;
|
| 425 |
+
}
|
| 426 |
+
return cast_impl(&src, policy, parent);
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
static handle cast(const MapType &src, return_value_policy policy, handle parent) {
|
| 430 |
+
if (policy == return_value_policy::automatic
|
| 431 |
+
|| policy == return_value_policy::automatic_reference) {
|
| 432 |
+
policy = return_value_policy::copy;
|
| 433 |
+
}
|
| 434 |
+
return cast(&src, policy, parent);
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
static handle cast(MapType *src, return_value_policy policy, handle parent) {
|
| 438 |
+
if (policy == return_value_policy::automatic) {
|
| 439 |
+
policy = return_value_policy::take_ownership;
|
| 440 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
| 441 |
+
policy = return_value_policy::reference;
|
| 442 |
+
}
|
| 443 |
+
return cast_impl(src, policy, parent);
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
static handle cast(const MapType *src, return_value_policy policy, handle parent) {
|
| 447 |
+
if (policy == return_value_policy::automatic) {
|
| 448 |
+
policy = return_value_policy::take_ownership;
|
| 449 |
+
} else if (policy == return_value_policy::automatic_reference) {
|
| 450 |
+
policy = return_value_policy::reference;
|
| 451 |
+
}
|
| 452 |
+
return cast_impl(src, policy, parent);
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
template <typename C>
|
| 456 |
+
static handle cast_impl(C *src, return_value_policy policy, handle parent) {
|
| 457 |
+
object parent_object;
|
| 458 |
+
constexpr bool writeable = !std::is_const<C>::value;
|
| 459 |
+
switch (policy) {
|
| 460 |
+
case return_value_policy::reference:
|
| 461 |
+
parent_object = none();
|
| 462 |
+
break;
|
| 463 |
+
|
| 464 |
+
case return_value_policy::reference_internal:
|
| 465 |
+
// Default should do the right thing
|
| 466 |
+
if (!parent) {
|
| 467 |
+
pybind11_fail("Cannot use reference internal when there is no parent");
|
| 468 |
+
}
|
| 469 |
+
parent_object = reinterpret_borrow<object>(parent);
|
| 470 |
+
break;
|
| 471 |
+
|
| 472 |
+
case return_value_policy::take_ownership:
|
| 473 |
+
delete src;
|
| 474 |
+
// fallthrough
|
| 475 |
+
default:
|
| 476 |
+
// move, take_ownership don't make any sense for a ref/map:
|
| 477 |
+
pybind11_fail("Invalid return_value_policy for Eigen Map type, must be either "
|
| 478 |
+
"reference or reference_internal");
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
auto result = array_t<typename Type::Scalar, compute_array_flag_from_tensor<Type>()>(
|
| 482 |
+
convert_dsizes_to_vector(Helper::get_shape(*src)),
|
| 483 |
+
src->data(),
|
| 484 |
+
std::move(parent_object));
|
| 485 |
+
|
| 486 |
+
if (!writeable) {
|
| 487 |
+
array_proxy(result.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
return result.release();
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
#if EIGEN_VERSION_AT_LEAST(3, 4, 0)
|
| 494 |
+
|
| 495 |
+
static constexpr bool needs_writeable = !std::is_const<typename std::remove_pointer<
|
| 496 |
+
typename get_storage_pointer_type<MapType>::SPT>::type>::value;
|
| 497 |
+
#else
|
| 498 |
+
// Handle Eigen bug
|
| 499 |
+
static constexpr bool needs_writeable = !std::is_const<Type>::value;
|
| 500 |
+
#endif
|
| 501 |
+
|
| 502 |
+
protected:
|
| 503 |
+
// TODO: Move to std::optional once std::optional has more support
|
| 504 |
+
std::unique_ptr<MapType> value;
|
| 505 |
+
|
| 506 |
+
public:
|
| 507 |
+
static constexpr auto name = get_tensor_descriptor<Type, true, needs_writeable>::value;
|
| 508 |
+
explicit operator MapType *() { return value.get(); }
|
| 509 |
+
explicit operator MapType &() { return *value; }
|
| 510 |
+
explicit operator MapType &&() && { return std::move(*value); }
|
| 511 |
+
|
| 512 |
+
template <typename T_>
|
| 513 |
+
using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>;
|
| 514 |
+
};
|
| 515 |
+
|
| 516 |
+
PYBIND11_NAMESPACE_END(detail)
|
| 517 |
+
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/dataloader/stateful.h>
|
| 4 |
+
#include <torch/data/dataloader/stateless.h>
|
| 5 |
+
|
| 6 |
+
#include <torch/csrc/utils/variadic.h>
|
| 7 |
+
|
| 8 |
+
#include <c10/util/Exception.h>
|
| 9 |
+
|
| 10 |
+
#include <cstddef>
|
| 11 |
+
#include <memory>
|
| 12 |
+
#include <type_traits>
|
| 13 |
+
#include <utility>
|
| 14 |
+
|
| 15 |
+
namespace torch {
|
| 16 |
+
namespace data {
|
| 17 |
+
|
| 18 |
+
/// Creates a `DataLoader` instance for a stateless `dataset`, a `sampler` and
|
| 19 |
+
/// some `options`.
|
| 20 |
+
template <typename Dataset, typename Sampler>
|
| 21 |
+
std::enable_if_t<
|
| 22 |
+
!Dataset::is_stateful,
|
| 23 |
+
std::unique_ptr<StatelessDataLoader<Dataset, Sampler>>>
|
| 24 |
+
make_data_loader(Dataset dataset, Sampler sampler, DataLoaderOptions options) {
|
| 25 |
+
return std::make_unique<StatelessDataLoader<Dataset, Sampler>>(
|
| 26 |
+
std::move(dataset), std::move(sampler), std::move(options));
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
/// Creates a `DataLoader` instance for a stateless `dataset` and some
|
| 30 |
+
/// `options`. A sampler (by default a `RandomSampler`) will be constructed from
|
| 31 |
+
/// the size of the dataset.
|
| 32 |
+
template <typename Sampler = samplers::RandomSampler, typename Dataset>
|
| 33 |
+
std::enable_if_t<
|
| 34 |
+
!Dataset::is_stateful && std::is_constructible_v<Sampler, size_t>,
|
| 35 |
+
std::unique_ptr<StatelessDataLoader<Dataset, Sampler>>>
|
| 36 |
+
make_data_loader(
|
| 37 |
+
Dataset dataset,
|
| 38 |
+
DataLoaderOptions options = DataLoaderOptions()) {
|
| 39 |
+
const optional<size_t> size = dataset.size();
|
| 40 |
+
TORCH_CHECK(
|
| 41 |
+
size.has_value(),
|
| 42 |
+
"Expected the dataset to be sized in "
|
| 43 |
+
"order to construct the Sampler");
|
| 44 |
+
return make_data_loader(
|
| 45 |
+
std::move(dataset), Sampler(*size), std::move(options));
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
/// Creates a `DataLoader` for a stateful `dataset` and some `options`.
|
| 49 |
+
template <typename Dataset, typename = std::enable_if_t<Dataset::is_stateful>>
|
| 50 |
+
std::unique_ptr<StatefulDataLoader<Dataset>> make_data_loader(
|
| 51 |
+
Dataset dataset,
|
| 52 |
+
DataLoaderOptions options = DataLoaderOptions()) {
|
| 53 |
+
return std::make_unique<StatefulDataLoader<Dataset>>(
|
| 54 |
+
std::move(dataset), std::move(options));
|
| 55 |
+
}
|
| 56 |
+
} // namespace data
|
| 57 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/dataloader_options.h>
|
| 4 |
+
#include <torch/data/detail/data_shuttle.h>
|
| 5 |
+
#include <torch/data/detail/sequencers.h>
|
| 6 |
+
#include <torch/data/iterator.h>
|
| 7 |
+
#include <torch/data/samplers/random.h>
|
| 8 |
+
#include <torch/data/worker_exception.h>
|
| 9 |
+
#include <torch/types.h>
|
| 10 |
+
|
| 11 |
+
#include <torch/csrc/utils/variadic.h>
|
| 12 |
+
|
| 13 |
+
#include <c10/util/Exception.h>
|
| 14 |
+
#include <c10/util/irange.h>
|
| 15 |
+
|
| 16 |
+
#include <cstddef>
|
| 17 |
+
#include <exception>
|
| 18 |
+
#include <memory>
|
| 19 |
+
#include <thread>
|
| 20 |
+
#include <type_traits>
|
| 21 |
+
#include <utility>
|
| 22 |
+
#include <vector>
|
| 23 |
+
|
| 24 |
+
namespace torch {
|
| 25 |
+
namespace data {
|
| 26 |
+
template <typename Dataset, typename Batch, typename BatchRequest>
|
| 27 |
+
class DataLoaderBase {
|
| 28 |
+
public:
|
| 29 |
+
using BatchType = Batch;
|
| 30 |
+
using BatchRequestType = BatchRequest;
|
| 31 |
+
|
| 32 |
+
/// Constructs a new DataLoader from a `dataset` to sample from, `options`
|
| 33 |
+
/// to configure the DataLoader with, and a `sampler` that specifies the
|
| 34 |
+
/// sampling strategy.
|
| 35 |
+
DataLoaderBase(
|
| 36 |
+
DataLoaderOptions options,
|
| 37 |
+
std::unique_ptr<Dataset> main_thread_dataset = nullptr)
|
| 38 |
+
: options_(std::move(options)),
|
| 39 |
+
main_thread_dataset_(std::move(main_thread_dataset)),
|
| 40 |
+
sequencer_(new_sequencer()) {}
|
| 41 |
+
|
| 42 |
+
// NOLINTNEXTLINE(bugprone-exception-escape)
|
| 43 |
+
virtual ~DataLoaderBase() {
|
| 44 |
+
join();
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
/// Returns an iterator into the DataLoader. The lifetime of the iterator is
|
| 48 |
+
/// bound to the DataLoader. In C++ standards language, the category of the
|
| 49 |
+
/// iterator is `OutputIterator`. See
|
| 50 |
+
/// https://en.cppreference.com/w/cpp/named_req/OutputIterator for what this
|
| 51 |
+
/// means. In short: you may increment the iterator and dereference it, but
|
| 52 |
+
/// cannot go back, or step forward more than one position at a time. When the
|
| 53 |
+
/// DataLoader is exhausted, it will compare equal with the special
|
| 54 |
+
/// "sentinel" iterator returned by `DataLoader::end()`. Most of the time, you
|
| 55 |
+
/// should only use range-for loops to loop over the DataLoader, but
|
| 56 |
+
/// standard algorithms like `std::copy(dataloader.begin(), dataloader.end(),
|
| 57 |
+
/// output_iterator)` are supported too.
|
| 58 |
+
Iterator<Batch> begin() {
|
| 59 |
+
TORCH_CHECK(
|
| 60 |
+
shuttle_.in_flight_jobs() == 0,
|
| 61 |
+
"Attempted to get a new DataLoader iterator "
|
| 62 |
+
"while another iterator is not yet exhausted");
|
| 63 |
+
reset();
|
| 64 |
+
return Iterator<Batch>(std::make_unique<detail::ValidIterator<Batch>>(
|
| 65 |
+
[this] { return this->next(); }));
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
/// Returns a special "sentinel" iterator that compares equal with a
|
| 69 |
+
/// non-sentinel iterator once the DataLoader is exhausted.
|
| 70 |
+
Iterator<Batch> end() {
|
| 71 |
+
return Iterator<Batch>(std::make_unique<detail::SentinelIterator<Batch>>());
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/// Joins the DataLoader's worker threads and drains internal queues.
|
| 75 |
+
/// This function may only be invoked from the main thread (in which the
|
| 76 |
+
/// DataLoader lives).
|
| 77 |
+
void join() {
|
| 78 |
+
if (joined_) {
|
| 79 |
+
return;
|
| 80 |
+
}
|
| 81 |
+
shuttle_.drain();
|
| 82 |
+
// Send one 'quit' message per worker. Since a worker dies (exits its
|
| 83 |
+
// thread) after receiving this message, each `QuitWorker()` message will be
|
| 84 |
+
// read by exactly one worker.
|
| 85 |
+
for (const auto w : c10::irange(options_.workers)) {
|
| 86 |
+
(void)w; // Suppress unused variable warning
|
| 87 |
+
push_job(QuitWorker());
|
| 88 |
+
}
|
| 89 |
+
for (auto& worker : workers_) {
|
| 90 |
+
worker.join();
|
| 91 |
+
}
|
| 92 |
+
joined_ = true;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/// Returns the options with which the DataLoader was configured.
|
| 96 |
+
const FullDataLoaderOptions& options() const noexcept {
|
| 97 |
+
return options_;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
protected:
|
| 101 |
+
/// Simple mix-in to give something a sequence number.
|
| 102 |
+
struct Sequenced {
|
| 103 |
+
Sequenced() = default;
|
| 104 |
+
Sequenced(size_t sqn) : sequence_number(sqn) {}
|
| 105 |
+
size_t sequence_number;
|
| 106 |
+
};
|
| 107 |
+
|
| 108 |
+
struct QuitWorker {};
|
| 109 |
+
|
| 110 |
+
/// A `Job` is either a `BatchRequest` (new indices to fetch data at) or a
|
| 111 |
+
/// `QuitWorker` object, to indicate the worker should shut down.
|
| 112 |
+
struct Job : Sequenced {
|
| 113 |
+
Job() = default;
|
| 114 |
+
Job(QuitWorker q, size_t sqn) : Sequenced(sqn), quit(q) {}
|
| 115 |
+
Job(BatchRequest&& i, size_t sqn)
|
| 116 |
+
: Sequenced(sqn), batch_request(std::move(i)) {}
|
| 117 |
+
optional<QuitWorker> quit;
|
| 118 |
+
optional<BatchRequest> batch_request;
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
/// The finished result of a job.
|
| 122 |
+
struct Result : Sequenced {
|
| 123 |
+
Result() = default;
|
| 124 |
+
Result(optional<Batch>&& b, size_t sqn)
|
| 125 |
+
: Sequenced(sqn), batch(std::move(b)) {}
|
| 126 |
+
Result(std::exception_ptr exception, size_t sqn)
|
| 127 |
+
: Sequenced(sqn), exception(std::move(exception)) {}
|
| 128 |
+
optional<Batch> batch;
|
| 129 |
+
std::exception_ptr exception;
|
| 130 |
+
};
|
| 131 |
+
|
| 132 |
+
/// Subclass hook for getting the next batch request. The stateless case will
|
| 133 |
+
/// ask the sampler for a new batch request (e.g. a vector of indices), while
|
| 134 |
+
/// the stateful one will simply return the batch size.
|
| 135 |
+
virtual optional<BatchRequestType> get_batch_request() = 0;
|
| 136 |
+
|
| 137 |
+
/// Resets the internal state of the DataLoader, optionally pre-fetching
|
| 138 |
+
/// new jobs.
|
| 139 |
+
virtual void reset() {
|
| 140 |
+
shuttle_.drain();
|
| 141 |
+
sequence_number_ = 0;
|
| 142 |
+
sequencer_ = new_sequencer();
|
| 143 |
+
prefetch();
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
/// Schedules `requested_jobs` many new batches to be fetched. The actual
|
| 147 |
+
/// number of jobs scheduled may be less if the DataLoader exhausts.
|
| 148 |
+
void prefetch(size_t requested_jobs) {
|
| 149 |
+
for (const auto r : c10::irange(requested_jobs)) {
|
| 150 |
+
(void)r; // Suppress unused variable
|
| 151 |
+
if (auto batch_request = get_batch_request()) {
|
| 152 |
+
this->push_job(std::move(*batch_request));
|
| 153 |
+
} else {
|
| 154 |
+
break;
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
/// Schedules the maximum number of jobs (based on the `max_jobs` option).
|
| 160 |
+
void prefetch() {
|
| 161 |
+
prefetch(options_.max_jobs);
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
/// Returns the next batch of data, or an empty `optional` if the DataLoader
|
| 165 |
+
/// is exhausted. This operation will block until a batch is available if one
|
| 166 |
+
/// is still expected.
|
| 167 |
+
optional<BatchType> next() {
|
| 168 |
+
if (options_.workers > 0) {
|
| 169 |
+
while (optional<Result> result = this->pop_result()) {
|
| 170 |
+
if (result->exception) {
|
| 171 |
+
throw WorkerException(result->exception);
|
| 172 |
+
} else if (result->batch) {
|
| 173 |
+
prefetch(1);
|
| 174 |
+
return std::move(result->batch);
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
} else if (auto batch_request = get_batch_request()) {
|
| 178 |
+
return this->main_thread_dataset_->get_batch(std::move(*batch_request));
|
| 179 |
+
}
|
| 180 |
+
return nullopt;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
/// The function that worker threads run.
|
| 184 |
+
void worker_thread(Dataset& dataset) {
|
| 185 |
+
while (true) {
|
| 186 |
+
auto job = shuttle_.pop_job();
|
| 187 |
+
if (job.quit) {
|
| 188 |
+
break;
|
| 189 |
+
}
|
| 190 |
+
try {
|
| 191 |
+
auto batch = dataset.get_batch(std::move(*job.batch_request));
|
| 192 |
+
shuttle_.push_result({std::move(batch), job.sequence_number});
|
| 193 |
+
} catch (...) {
|
| 194 |
+
shuttle_.push_result({std::current_exception(), job.sequence_number});
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
/// Convenience method that calls `shuttle_.push_job()` with the next sequence
|
| 200 |
+
/// number.
|
| 201 |
+
template <typename T>
|
| 202 |
+
void push_job(T value) {
|
| 203 |
+
shuttle_.push_job({std::move(value), sequence_number_++});
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
/// Convenience method that gets the next result from the sequencer.
|
| 207 |
+
optional<Result> pop_result() {
|
| 208 |
+
return sequencer_->next(
|
| 209 |
+
[this] { return this->shuttle_.pop_result(this->options_.timeout); });
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
/// Convenience method that creates a new sequencer based on the
|
| 213 |
+
/// `enforce_ordering` option.
|
| 214 |
+
std::unique_ptr<detail::sequencers::Sequencer<Result>> new_sequencer() {
|
| 215 |
+
if (options_.enforce_ordering) {
|
| 216 |
+
return std::make_unique<detail::sequencers::OrderedSequencer<Result>>(
|
| 217 |
+
options_.max_jobs);
|
| 218 |
+
}
|
| 219 |
+
return std::make_unique<detail::sequencers::NoSequencer<Result>>();
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// The options the DataLoader was configured with.
|
| 223 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 224 |
+
const FullDataLoaderOptions options_;
|
| 225 |
+
|
| 226 |
+
/// The dataset for the main thread, only has a value if the number of
|
| 227 |
+
/// worker threads was configured as zero, meaning the main thread has to do
|
| 228 |
+
/// all the work (synchronously). NOTE: Really want this to be on the heap
|
| 229 |
+
/// when empty, therefore `unique_ptr` and not `optional`.
|
| 230 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 231 |
+
std::unique_ptr<Dataset> main_thread_dataset_;
|
| 232 |
+
|
| 233 |
+
/// The sequence number for the *next* batch to be retrieved from the
|
| 234 |
+
/// dataset.
|
| 235 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 236 |
+
size_t sequence_number_ = 0;
|
| 237 |
+
|
| 238 |
+
/// The worker threads, running the `worker_thread()` method.
|
| 239 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 240 |
+
std::vector<std::thread> workers_;
|
| 241 |
+
|
| 242 |
+
/// The `DataShuttle` which takes care of the life cycle of a job.
|
| 243 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 244 |
+
detail::DataShuttle<Job, Result> shuttle_;
|
| 245 |
+
|
| 246 |
+
/// The `Sequencer`, which handles optional ordering of batches.
|
| 247 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 248 |
+
std::unique_ptr<detail::sequencers::Sequencer<Result>> sequencer_;
|
| 249 |
+
|
| 250 |
+
/// True if the DataLoader has joined its worker threads.
|
| 251 |
+
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
| 252 |
+
bool joined_ = false;
|
| 253 |
+
};
|
| 254 |
+
} // namespace data
|
| 255 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/util/irange.h>
|
| 4 |
+
#include <torch/data/dataloader/base.h>
|
| 5 |
+
|
| 6 |
+
#include <cstddef>
|
| 7 |
+
#include <thread>
|
| 8 |
+
#include <utility>
|
| 9 |
+
|
| 10 |
+
namespace torch {
|
| 11 |
+
namespace data {
|
| 12 |
+
|
| 13 |
+
/// A dataloader for stateful datasets.
|
| 14 |
+
///
|
| 15 |
+
/// A dataloader for stateful datatasets differs from one for stateless
|
| 16 |
+
/// datasets one in that the dataset is shared among worker threads, and that
|
| 17 |
+
/// this dataset is itself responsible for producing batches rather than
|
| 18 |
+
/// depending on a sampler. The statefulness here actually refers to the
|
| 19 |
+
/// dataset. The StatefulDataLoader simply alters the data loading algorithm to
|
| 20 |
+
/// accommodate the stateful, shared nature of the dataset. Note that the
|
| 21 |
+
/// dataset must be thread safe if more than one worker thread is used.
|
| 22 |
+
///
|
| 23 |
+
/// A stateful dataloader is created by calling `make_data_loader` with a
|
| 24 |
+
/// stateful dataset.
|
| 25 |
+
template <typename Dataset>
|
| 26 |
+
class StatefulDataLoader : public DataLoaderBase<
|
| 27 |
+
Dataset,
|
| 28 |
+
typename Dataset::BatchType::value_type,
|
| 29 |
+
typename Dataset::BatchRequestType> {
|
| 30 |
+
public:
|
| 31 |
+
using super = DataLoaderBase<
|
| 32 |
+
Dataset,
|
| 33 |
+
typename Dataset::BatchType::value_type,
|
| 34 |
+
typename Dataset::BatchRequestType>;
|
| 35 |
+
using typename super::BatchRequestType;
|
| 36 |
+
|
| 37 |
+
/// Constructs the `StatefulDataLoader` from a `dataset` and some `options`.
|
| 38 |
+
StatefulDataLoader(Dataset dataset, DataLoaderOptions options)
|
| 39 |
+
: super(options, std::make_unique<Dataset>(std::move(dataset))) {
|
| 40 |
+
for ([[maybe_unused]] const auto _ : c10::irange(this->options_.workers)) {
|
| 41 |
+
// As opposed to the stateless case, here all worker threads access the
|
| 42 |
+
// same underlying dataset.
|
| 43 |
+
this->workers_.emplace_back(
|
| 44 |
+
[this] { this->worker_thread(*this->main_thread_dataset_); });
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
private:
|
| 49 |
+
/// Resets the internal state of the dataloader and the dataset.
|
| 50 |
+
void reset() override {
|
| 51 |
+
this->main_thread_dataset_->reset();
|
| 52 |
+
// Call the base class method last because it calls `prefetch()`
|
| 53 |
+
super::reset();
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/// For stateful datasets, the batch request is always the batch size. The
|
| 57 |
+
/// dataset is responsible for determining what goes into the batch next.
|
| 58 |
+
optional<BatchRequestType> get_batch_request() override {
|
| 59 |
+
return this->options_.batch_size;
|
| 60 |
+
}
|
| 61 |
+
};
|
| 62 |
+
} // namespace data
|
| 63 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateless.h
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/dataloader/base.h>
|
| 4 |
+
#include <torch/data/worker_exception.h>
|
| 5 |
+
|
| 6 |
+
#include <c10/util/Exception.h>
|
| 7 |
+
#include <c10/util/irange.h>
|
| 8 |
+
|
| 9 |
+
#include <cstddef>
|
| 10 |
+
#include <thread>
|
| 11 |
+
#include <utility>
|
| 12 |
+
|
| 13 |
+
namespace torch {
|
| 14 |
+
namespace data {
|
| 15 |
+
|
| 16 |
+
/// A dataloader for stateless datasets.
|
| 17 |
+
///
|
| 18 |
+
/// This dataloader follows the traditional PyTorch dataloader design, whereby a
|
| 19 |
+
/// (posssibly) stateful sampler produces *batch requests* for a stateless
|
| 20 |
+
/// dataset, which acts as a simple batch request to batch mapping. The batch
|
| 21 |
+
/// request will often be an array of indices, and if the dataset is a simple
|
| 22 |
+
/// image dataset, the dataset would produce the images at those indices.
|
| 23 |
+
template <typename Dataset, typename Sampler>
|
| 24 |
+
class StatelessDataLoader : public DataLoaderBase<
|
| 25 |
+
Dataset,
|
| 26 |
+
typename Dataset::BatchType,
|
| 27 |
+
typename Sampler::BatchRequestType> {
|
| 28 |
+
public:
|
| 29 |
+
using super = DataLoaderBase<
|
| 30 |
+
Dataset,
|
| 31 |
+
typename Dataset::BatchType,
|
| 32 |
+
typename Sampler::BatchRequestType>;
|
| 33 |
+
using typename super::BatchRequestType;
|
| 34 |
+
|
| 35 |
+
/// Constructs the `StatelessDataLoader` from a `dataset`, a `sampler` and
|
| 36 |
+
/// some `options`.
|
| 37 |
+
StatelessDataLoader(
|
| 38 |
+
Dataset dataset,
|
| 39 |
+
Sampler sampler,
|
| 40 |
+
DataLoaderOptions options)
|
| 41 |
+
: super(std::move(options)), sampler_(std::move(sampler)) {
|
| 42 |
+
for (const auto w : c10::irange(this->options_.workers)) {
|
| 43 |
+
// Here we copy the dataset into the worker thread closure. Each worker
|
| 44 |
+
// has its own copy of the dataset. This means the dataset must be
|
| 45 |
+
// trivially copiable, or else we don't expect more than one worker to
|
| 46 |
+
// be in use.
|
| 47 |
+
(void)w; // Suppress unused variable warning
|
| 48 |
+
this->workers_.emplace_back(
|
| 49 |
+
[this, dataset]() mutable { this->worker_thread(dataset); });
|
| 50 |
+
}
|
| 51 |
+
if (this->options_.workers == 0) {
|
| 52 |
+
this->main_thread_dataset_ =
|
| 53 |
+
std::make_unique<Dataset>(std::move(dataset));
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
private:
|
| 58 |
+
/// Resets the internal state of the dataloader and the sampler.
|
| 59 |
+
void reset() override {
|
| 60 |
+
sampler_.reset();
|
| 61 |
+
// Call the base class method last because it calls `prefetch()`
|
| 62 |
+
super::reset();
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/// Queries the sampler for the next batch request (possibly progressing its
|
| 66 |
+
/// internal state).
|
| 67 |
+
optional<BatchRequestType> get_batch_request() override {
|
| 68 |
+
auto indices = sampler_.next(this->options_.batch_size);
|
| 69 |
+
if (!indices ||
|
| 70 |
+
(indices->size() < this->options_.batch_size &&
|
| 71 |
+
this->options_.drop_last)) {
|
| 72 |
+
return nullopt;
|
| 73 |
+
}
|
| 74 |
+
AT_ASSERT(indices->size() > 0);
|
| 75 |
+
return indices;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
/// The `Sampler` used to produce batch requests.
|
| 79 |
+
Sampler sampler_;
|
| 80 |
+
};
|
| 81 |
+
} // namespace data
|
| 82 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/base.h
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/example.h>
|
| 4 |
+
#include <torch/types.h>
|
| 5 |
+
|
| 6 |
+
#include <c10/util/ArrayRef.h>
|
| 7 |
+
|
| 8 |
+
#include <cstddef>
|
| 9 |
+
#include <cstdint>
|
| 10 |
+
#include <type_traits>
|
| 11 |
+
#include <utility>
|
| 12 |
+
#include <vector>
|
| 13 |
+
|
| 14 |
+
namespace torch {
|
| 15 |
+
namespace data {
|
| 16 |
+
namespace datasets {
|
| 17 |
+
template <typename S, typename T>
|
| 18 |
+
class MapDataset;
|
| 19 |
+
template <typename D, typename T>
|
| 20 |
+
MapDataset<D, T> map(D, T); // NOLINT
|
| 21 |
+
} // namespace datasets
|
| 22 |
+
} // namespace data
|
| 23 |
+
} // namespace torch
|
| 24 |
+
|
| 25 |
+
namespace torch {
|
| 26 |
+
namespace data {
|
| 27 |
+
namespace datasets {
|
| 28 |
+
namespace detail {
|
| 29 |
+
template <typename T>
|
| 30 |
+
struct is_optional : std::false_type {};
|
| 31 |
+
template <typename T>
|
| 32 |
+
struct is_optional<optional<T>> : std::true_type {};
|
| 33 |
+
} // namespace detail
|
| 34 |
+
|
| 35 |
+
/// A dataset that can yield data only in batches.
|
| 36 |
+
template <
|
| 37 |
+
typename Self,
|
| 38 |
+
typename Batch = std::vector<Example<>>,
|
| 39 |
+
typename BatchRequest = ArrayRef<size_t>>
|
| 40 |
+
class BatchDataset {
|
| 41 |
+
public:
|
| 42 |
+
using SelfType = Self;
|
| 43 |
+
using BatchType = Batch;
|
| 44 |
+
using BatchRequestType = BatchRequest;
|
| 45 |
+
constexpr static bool is_stateful = detail::is_optional<BatchType>::value;
|
| 46 |
+
|
| 47 |
+
virtual ~BatchDataset() = default;
|
| 48 |
+
|
| 49 |
+
/// Returns a batch of data given an index.
|
| 50 |
+
virtual Batch get_batch(BatchRequest request) = 0;
|
| 51 |
+
|
| 52 |
+
/// Returns the size of the dataset, or an empty optional if it is unsized.
|
| 53 |
+
virtual optional<size_t> size() const = 0;
|
| 54 |
+
|
| 55 |
+
/// Creates a `MapDataset` that applies the given `transform` to this dataset.
|
| 56 |
+
template <typename TransformType>
|
| 57 |
+
MapDataset<Self, TransformType> map(TransformType transform) & {
|
| 58 |
+
return datasets::map(static_cast<Self&>(*this), std::move(transform));
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
/// Creates a `MapDataset` that applies the given `transform` to this dataset.
|
| 62 |
+
template <typename TransformType>
|
| 63 |
+
MapDataset<Self, TransformType> map(TransformType transform) && {
|
| 64 |
+
return datasets::map(
|
| 65 |
+
std::move(static_cast<Self&>(*this)), std::move(transform));
|
| 66 |
+
}
|
| 67 |
+
};
|
| 68 |
+
|
| 69 |
+
/// A dataset that can yield data in batches, or as individual examples.
|
| 70 |
+
///
|
| 71 |
+
/// A `Dataset` is a `BatchDataset`, because it supports random access and
|
| 72 |
+
/// therefore batched access is implemented (by default) by calling the random
|
| 73 |
+
/// access indexing function for each index in the requested batch of indices.
|
| 74 |
+
/// This can be customized.
|
| 75 |
+
template <typename Self, typename SingleExample = Example<>>
|
| 76 |
+
class Dataset : public BatchDataset<Self, std::vector<SingleExample>> {
|
| 77 |
+
public:
|
| 78 |
+
using ExampleType = SingleExample;
|
| 79 |
+
|
| 80 |
+
/// Returns the example at the given index.
|
| 81 |
+
virtual ExampleType get(size_t index) = 0;
|
| 82 |
+
|
| 83 |
+
/// Returns a batch of data.
|
| 84 |
+
/// The default implementation calls `get()` for every requested index
|
| 85 |
+
/// in the batch.
|
| 86 |
+
std::vector<ExampleType> get_batch(ArrayRef<size_t> indices) override {
|
| 87 |
+
std::vector<ExampleType> batch;
|
| 88 |
+
batch.reserve(indices.size());
|
| 89 |
+
for (const auto i : indices) {
|
| 90 |
+
batch.push_back(get(i));
|
| 91 |
+
}
|
| 92 |
+
return batch;
|
| 93 |
+
}
|
| 94 |
+
};
|
| 95 |
+
|
| 96 |
+
/// A `StreamDataset` represents a dataset that is a potentially infinite
|
| 97 |
+
/// stream. It takes as batch index only a number, which is the batch size, and
|
| 98 |
+
/// yields that many elements from the stream.
|
| 99 |
+
template <typename Self, typename Batch = std::vector<Example<>>>
|
| 100 |
+
using StreamDataset = BatchDataset<Self, Batch, /*BatchRequest=*/size_t>;
|
| 101 |
+
} // namespace datasets
|
| 102 |
+
} // namespace data
|
| 103 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/util/irange.h>
|
| 4 |
+
#include <torch/arg.h>
|
| 5 |
+
#include <torch/data/datasets/stateful.h>
|
| 6 |
+
#include <torch/data/samplers.h>
|
| 7 |
+
#include <queue>
|
| 8 |
+
#include <thread>
|
| 9 |
+
|
| 10 |
+
#include <torch/serialize.h>
|
| 11 |
+
|
| 12 |
+
namespace torch {
|
| 13 |
+
namespace data {
|
| 14 |
+
namespace datasets {
|
| 15 |
+
|
| 16 |
+
/// Interface for chunk reader, which performs data chunking and reading of
|
| 17 |
+
/// entire chunks.
|
| 18 |
+
///
|
| 19 |
+
/// A chunk could be an entire file, such as an audio data file or an image,
|
| 20 |
+
/// or part of a file in the case of a large text-file split based on seek
|
| 21 |
+
/// positions.
|
| 22 |
+
template <
|
| 23 |
+
typename ExampleType_,
|
| 24 |
+
typename ChunkType_ = std::vector<ExampleType_>>
|
| 25 |
+
class ChunkDataReader {
|
| 26 |
+
public:
|
| 27 |
+
virtual ~ChunkDataReader() = default;
|
| 28 |
+
|
| 29 |
+
using ChunkType = ChunkType_;
|
| 30 |
+
using ExampleType = ExampleType_;
|
| 31 |
+
|
| 32 |
+
/// Read an entire chunk.
|
| 33 |
+
virtual ChunkType read_chunk(size_t chunk_index) = 0;
|
| 34 |
+
|
| 35 |
+
/// Returns the number of chunks available in this reader.
|
| 36 |
+
virtual size_t chunk_count() = 0;
|
| 37 |
+
|
| 38 |
+
/// This will clear any internal state associate with this reader.
|
| 39 |
+
virtual void reset() = 0;
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
namespace detail {
|
| 43 |
+
/// BatchDataBuffer manages a queue of UnwrappedBatchData. After a new chunk is
|
| 44 |
+
/// loaded, BatchDataBuffer splits it into small batches and push them into the
|
| 45 |
+
/// queue. When get_batch is called from data loader, it pops cached batches and
|
| 46 |
+
/// return. If the cache is empty, it either waits to load more chunks or return
|
| 47 |
+
/// null if all chunks are loaded.
|
| 48 |
+
template <
|
| 49 |
+
typename UnwrappedBatch,
|
| 50 |
+
typename ExampleSampler = samplers::RandomSampler>
|
| 51 |
+
class BatchDataBuffer {
|
| 52 |
+
public:
|
| 53 |
+
using UnwrappedBatchType = UnwrappedBatch;
|
| 54 |
+
using BatchType = torch::optional<UnwrappedBatchType>;
|
| 55 |
+
using BatchRequestType = typename ExampleSampler::BatchRequestType;
|
| 56 |
+
|
| 57 |
+
BatchDataBuffer(
|
| 58 |
+
size_t batch_size,
|
| 59 |
+
ExampleSampler& example_sampler,
|
| 60 |
+
size_t queue_capacity)
|
| 61 |
+
: batch_size_(batch_size),
|
| 62 |
+
example_sampler_(example_sampler),
|
| 63 |
+
queue_capacity_(queue_capacity) {}
|
| 64 |
+
|
| 65 |
+
/// Return batch data from the queue. Called from the ChunkDataset main
|
| 66 |
+
/// thread.
|
| 67 |
+
BatchType get_batch() {
|
| 68 |
+
std::unique_lock<std::mutex> lock(queue_mutex_);
|
| 69 |
+
cv_read_.wait(lock, [this] {
|
| 70 |
+
// wait till there is available data in the queue or if all chunks are
|
| 71 |
+
// loaded (i.e. the dataset is exhausted for this epoch)
|
| 72 |
+
return (
|
| 73 |
+
this->total_example_count_in_queue_ >= batch_size_ || this->stop_);
|
| 74 |
+
});
|
| 75 |
+
if (batch_queue_.empty()) {
|
| 76 |
+
AT_ASSERT(stop_);
|
| 77 |
+
// All batches have been retrieved. Return an empty batch.
|
| 78 |
+
return nullopt;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
UnwrappedBatchData batch = std::move(batch_queue_.front());
|
| 82 |
+
batch_queue_.pop();
|
| 83 |
+
if (batch.exception) {
|
| 84 |
+
throw WorkerException(batch.exception);
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
total_example_count_in_queue_ -= batch.batch_data.size();
|
| 88 |
+
lock.unlock();
|
| 89 |
+
cv_write_.notify_all();
|
| 90 |
+
|
| 91 |
+
return batch.batch_data;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
/// Push preloaded chunks to batch queue. Called from the ChunkDataset worker
|
| 95 |
+
/// threads.
|
| 96 |
+
void add_chunk_data(UnwrappedBatchType data) {
|
| 97 |
+
std::unique_lock<std::mutex> lock(queue_mutex_);
|
| 98 |
+
cv_write_.wait(lock, [this] {
|
| 99 |
+
// stop loading if we have preloaded enough data.
|
| 100 |
+
return this->total_example_count_in_queue_ < this->queue_capacity_ ||
|
| 101 |
+
this->stop_;
|
| 102 |
+
});
|
| 103 |
+
if (stop_) {
|
| 104 |
+
// When stop_ is true, it means no further chunk loading is necessary.
|
| 105 |
+
// Return without any further processing.
|
| 106 |
+
return;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
auto data_size = data.size();
|
| 110 |
+
auto remaining_size = data_size;
|
| 111 |
+
example_sampler_.reset(data_size);
|
| 112 |
+
|
| 113 |
+
auto fill_batch = [&](size_t example_count, UnwrappedBatchType& batch) {
|
| 114 |
+
auto batch_example_indices = this->example_sampler_.next(example_count);
|
| 115 |
+
AT_ASSERT(
|
| 116 |
+
batch_example_indices &&
|
| 117 |
+
batch_example_indices.value().size() == example_count);
|
| 118 |
+
BatchRequestType& indices = batch_example_indices.value();
|
| 119 |
+
for (size_t i : indices) {
|
| 120 |
+
TORCH_CHECK(i < data_size, "Index out of range");
|
| 121 |
+
batch.emplace_back(std::move(data[i]));
|
| 122 |
+
}
|
| 123 |
+
remaining_size -= example_count;
|
| 124 |
+
};
|
| 125 |
+
|
| 126 |
+
if (!batch_queue_.empty()) {
|
| 127 |
+
// if the queue has existing data, and the last batch doesn't have enough
|
| 128 |
+
// examples to fill a batch_size batch, add more example to this batch
|
| 129 |
+
// first.
|
| 130 |
+
auto& batch = batch_queue_.back();
|
| 131 |
+
size_t current_count = batch.batch_data.size();
|
| 132 |
+
if (current_count < batch_size_) {
|
| 133 |
+
auto example_count =
|
| 134 |
+
std::min(remaining_size, batch_size_ - current_count);
|
| 135 |
+
fill_batch(example_count, batch.batch_data);
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// If we still have data remaining after filling the last pushed batch, add
|
| 140 |
+
// them to the queue too.
|
| 141 |
+
// NOLINTNEXTLINE(bugprone-infinite-loop)
|
| 142 |
+
while (remaining_size > 0) {
|
| 143 |
+
UnwrappedBatchType current_batch;
|
| 144 |
+
|
| 145 |
+
// Allocate the batch memory ahead of time.
|
| 146 |
+
current_batch.reserve(batch_size_);
|
| 147 |
+
|
| 148 |
+
auto example_count = std::min(remaining_size, batch_size_);
|
| 149 |
+
fill_batch(example_count, current_batch);
|
| 150 |
+
batch_queue_.emplace(std::move(current_batch));
|
| 151 |
+
}
|
| 152 |
+
total_example_count_in_queue_ += data_size;
|
| 153 |
+
lock.unlock();
|
| 154 |
+
cv_read_.notify_all();
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
/// Push exceptions thrown during preloading into batch queue. Called from
|
| 158 |
+
/// the ChunkDataset worker threads.
|
| 159 |
+
void add_chunk_data(std::exception_ptr e_ptr) {
|
| 160 |
+
std::unique_lock<std::mutex> lock(queue_mutex_);
|
| 161 |
+
cv_write_.wait(lock, [this] {
|
| 162 |
+
// stop loading if we have preloaded enough data.
|
| 163 |
+
return (
|
| 164 |
+
this->total_example_count_in_queue_ < this->queue_capacity_ ||
|
| 165 |
+
this->stop_);
|
| 166 |
+
});
|
| 167 |
+
if (stop_) {
|
| 168 |
+
// When stop_ is true, it means this current thread needs to be tore down,
|
| 169 |
+
// the batch buffer will be discarded, so no need to enqueue any new
|
| 170 |
+
// exceptions.
|
| 171 |
+
return;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
batch_queue_.emplace(e_ptr);
|
| 175 |
+
lock.unlock();
|
| 176 |
+
cv_read_.notify_all();
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
void stop() {
|
| 180 |
+
{
|
| 181 |
+
// Hold the lock before changing stop_ to prevent a race condition which
|
| 182 |
+
// can cause a deadlock. To be more specific, conditional variable
|
| 183 |
+
// cv_write_ waits on predicate stop_ in add_chunk_data(). The wait
|
| 184 |
+
// happens in two steps: 1) while still holding the lock, check if
|
| 185 |
+
// predicate is true; 2) if it is true, proceeds, otherwise, release the
|
| 186 |
+
// lock and wait until notified. Without holding a lock, cv_write_'s
|
| 187 |
+
// notification can happen in between step 1) and 2). In that case, as
|
| 188 |
+
// cv_write_ is not in waiting status yet, so the notification is lost and
|
| 189 |
+
// cv_write_ will sleep forever. By taking a lock before changing
|
| 190 |
+
// predicate stop_, it is ensured updating and evaluating stop_ always
|
| 191 |
+
// happen in a synchronized way
|
| 192 |
+
std::lock_guard<std::mutex> lock(queue_mutex_);
|
| 193 |
+
stop_ = true;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
// notify all writers, wake them from wait to exit current method.
|
| 197 |
+
cv_write_.notify_all();
|
| 198 |
+
// notify all readers too.
|
| 199 |
+
cv_read_.notify_all();
|
| 200 |
+
}
|
| 201 |
+
/// The batch size is needed to create batches from the chunk data. Similar to
|
| 202 |
+
/// regular dataloader where the batches are created with prefetches,
|
| 203 |
+
/// BatchDataBuffer perform the batch creation using the provided batch size.
|
| 204 |
+
size_t batch_size_ = 0;
|
| 205 |
+
|
| 206 |
+
/// count of total example stored in the queue
|
| 207 |
+
size_t total_example_count_in_queue_ = 0;
|
| 208 |
+
|
| 209 |
+
/// struct that contains a raw unwrapped batch unit. An unwrapped batch unit
|
| 210 |
+
/// is the raw data without 'optional' wrapper. It can be a collection of
|
| 211 |
+
/// images, utterances, e.t.c.
|
| 212 |
+
struct UnwrappedBatchData {
|
| 213 |
+
explicit UnwrappedBatchData(UnwrappedBatchType data)
|
| 214 |
+
: batch_data(std::move(data)) {}
|
| 215 |
+
|
| 216 |
+
// NOLINTNEXTLINE(modernize-pass-by-value)
|
| 217 |
+
explicit UnwrappedBatchData(std::exception_ptr e) : exception(e) {}
|
| 218 |
+
|
| 219 |
+
/// batch data to return
|
| 220 |
+
UnwrappedBatchType batch_data;
|
| 221 |
+
|
| 222 |
+
/// exception pointer which captures any abnormal exceptions while creating
|
| 223 |
+
/// the batch.
|
| 224 |
+
std::exception_ptr exception;
|
| 225 |
+
};
|
| 226 |
+
|
| 227 |
+
/// local cache to store example batches from loaded chunk
|
| 228 |
+
std::queue<UnwrappedBatchData> batch_queue_;
|
| 229 |
+
|
| 230 |
+
// sync batch_queue_ update.
|
| 231 |
+
std::mutex queue_mutex_;
|
| 232 |
+
|
| 233 |
+
std::condition_variable cv_read_;
|
| 234 |
+
std::condition_variable cv_write_;
|
| 235 |
+
|
| 236 |
+
ExampleSampler& example_sampler_;
|
| 237 |
+
|
| 238 |
+
// configurable maximun number of elements the queue can hold at one time.
|
| 239 |
+
size_t queue_capacity_;
|
| 240 |
+
|
| 241 |
+
// When set to true, it wakes the writer threads from the wait and exit
|
| 242 |
+
// current function call. This is needed when ChunkDataSet.Reset is called
|
| 243 |
+
// while the previous epoch is not exhausted yet. When ChunkDataset is waiting
|
| 244 |
+
// its preloader to finish previous work before tearing down the thread, the
|
| 245 |
+
// preloader could be still waiting for the conditional variable, thus cause
|
| 246 |
+
// the program to hang. This boolean is used to break this waiting condition.
|
| 247 |
+
bool stop_ = false;
|
| 248 |
+
};
|
| 249 |
+
} // namespace detail
|
| 250 |
+
|
| 251 |
+
/// Options to configure a `ChunkDataset`.
|
| 252 |
+
struct ChunkDatasetOptions {
|
| 253 |
+
ChunkDatasetOptions() = delete;
|
| 254 |
+
ChunkDatasetOptions(
|
| 255 |
+
size_t preloader_count,
|
| 256 |
+
size_t batch_size,
|
| 257 |
+
size_t cache_size = 2048,
|
| 258 |
+
size_t cross_chunk_shuffle_count = 1)
|
| 259 |
+
: preloader_count_(preloader_count),
|
| 260 |
+
batch_size_(batch_size),
|
| 261 |
+
cache_size_(cache_size),
|
| 262 |
+
cross_chunk_shuffle_count_(cross_chunk_shuffle_count) {
|
| 263 |
+
TORCH_CHECK(
|
| 264 |
+
preloader_count_ > 0,
|
| 265 |
+
"Preloader count is 0. At least one preloader needs to be specified.");
|
| 266 |
+
TORCH_CHECK(
|
| 267 |
+
batch_size_ > 0,
|
| 268 |
+
"Batch size is 0. A positive batch size needs to be specified.");
|
| 269 |
+
TORCH_CHECK(
|
| 270 |
+
cache_size_ > 0,
|
| 271 |
+
"Cache size is 0. A positive cache size needs to be specified.");
|
| 272 |
+
TORCH_CHECK(
|
| 273 |
+
cache_size_ >= batch_size_,
|
| 274 |
+
"Cache size is less than batch size. Cache needs to be large enough to "
|
| 275 |
+
"hold at least one batch.");
|
| 276 |
+
TORCH_CHECK(
|
| 277 |
+
cross_chunk_shuffle_count_ > 0,
|
| 278 |
+
"cross_chunk_shuffle_count needs to be greater than 0.");
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
/// The number of worker thread to preload chunk data.
|
| 282 |
+
TORCH_ARG(size_t, preloader_count);
|
| 283 |
+
|
| 284 |
+
/// The size of each batch.
|
| 285 |
+
TORCH_ARG(size_t, batch_size);
|
| 286 |
+
|
| 287 |
+
/// The capacity of the queue for batch caching.
|
| 288 |
+
TORCH_ARG(size_t, cache_size) = 2048;
|
| 289 |
+
|
| 290 |
+
// The number of chunks to perfrom cross-chunk shuffling. Default to 1 meaning
|
| 291 |
+
// no cross-chunk shuffling. When it is equal to n (n > 1), n random
|
| 292 |
+
// chunks will be loaded at once and example shuffling will be performed
|
| 293 |
+
// across all those n chunks.
|
| 294 |
+
// Note: Usually the default config (1 chunk shuffle + example shuffle) is
|
| 295 |
+
// good enough to generate random distributed data. Use this parameter only if
|
| 296 |
+
// you know cross-shuffle is needed in your case. Also there is a performance
|
| 297 |
+
// penalty when this value is greater than 1, as we need to do extra merge
|
| 298 |
+
// between multiple chunks before performing example sampling.
|
| 299 |
+
TORCH_ARG(size_t, cross_chunk_shuffle_count) = 1;
|
| 300 |
+
};
|
| 301 |
+
|
| 302 |
+
/// A stateful dataset that support hierarchical sampling and prefetching of
|
| 303 |
+
/// entre chunks.
|
| 304 |
+
///
|
| 305 |
+
/// Unlike regular dataset, chunk dataset require two samplers to operate and
|
| 306 |
+
/// keeps an internal state. `ChunkSampler` selects, which chunk to load next,
|
| 307 |
+
/// while the `ExampleSampler` determins the order of Examples that are returned
|
| 308 |
+
/// in each `get_batch` call. The hierarchical sampling approach used here is
|
| 309 |
+
/// inspired by this paper http://martin.zinkevich.org/publications/nips2010.pdf
|
| 310 |
+
template <
|
| 311 |
+
typename ChunkReader,
|
| 312 |
+
typename ChunkSampler = samplers::RandomSampler,
|
| 313 |
+
typename ExampleSampler = samplers::RandomSampler>
|
| 314 |
+
class ChunkDataset final
|
| 315 |
+
: public StatefulDataset<
|
| 316 |
+
ChunkDataset<ChunkReader, ChunkSampler, ExampleSampler>,
|
| 317 |
+
typename ChunkReader::BatchType,
|
| 318 |
+
size_t> {
|
| 319 |
+
public:
|
| 320 |
+
using BatchType = torch::optional<typename ChunkReader::BatchType>;
|
| 321 |
+
using UnwrappedBatchType = typename ChunkReader::BatchType;
|
| 322 |
+
using BatchRequestType = size_t;
|
| 323 |
+
using ChunkSamplerType = ChunkSampler;
|
| 324 |
+
using ExampleSamplerType = ExampleSampler;
|
| 325 |
+
|
| 326 |
+
ChunkDataset(
|
| 327 |
+
ChunkReader chunk_reader,
|
| 328 |
+
ChunkSampler chunk_sampler,
|
| 329 |
+
ExampleSampler example_sampler,
|
| 330 |
+
ChunkDatasetOptions options,
|
| 331 |
+
std::function<void(UnwrappedBatchType&)> preprocessing_policy =
|
| 332 |
+
std::function<void(UnwrappedBatchType&)>())
|
| 333 |
+
: chunk_reader_(std::move(chunk_reader)),
|
| 334 |
+
chunk_sampler_(std::move(chunk_sampler)),
|
| 335 |
+
example_sampler_(std::move(example_sampler)),
|
| 336 |
+
options_(std::move(options)),
|
| 337 |
+
preprocessing_policy_(std::move(preprocessing_policy)),
|
| 338 |
+
quit_worker_(false),
|
| 339 |
+
running_preloaders_(0),
|
| 340 |
+
load_checkpoint_(false) {}
|
| 341 |
+
|
| 342 |
+
~ChunkDataset() override {
|
| 343 |
+
// stop batch buffer first.
|
| 344 |
+
if (batch_buffer_) {
|
| 345 |
+
batch_buffer_->stop();
|
| 346 |
+
}
|
| 347 |
+
free_workers();
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
/// Default get_batch method of BatchDataset. This method returns
|
| 351 |
+
/// Example batches created from the preloaded chunks. The implemenation
|
| 352 |
+
/// is dataset agnostic and does not need overriding in different chunk
|
| 353 |
+
/// datasets.
|
| 354 |
+
BatchType get_batch(size_t batch_size) override {
|
| 355 |
+
TORCH_CHECK(
|
| 356 |
+
batch_buffer_ != nullptr,
|
| 357 |
+
"Dataset needs to call reset() before calling get_batch().");
|
| 358 |
+
|
| 359 |
+
TORCH_CHECK(
|
| 360 |
+
batch_size == options_.batch_size(),
|
| 361 |
+
"The requested batch size does not match with the initialized batch size.\n"
|
| 362 |
+
" The requested batch size is ",
|
| 363 |
+
batch_size,
|
| 364 |
+
", while the dataset is created with batch size equal to ",
|
| 365 |
+
options_.batch_size());
|
| 366 |
+
return batch_buffer_->get_batch();
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
/// Helper method around get_batch as `batch_size` is not strictly necessary
|
| 370 |
+
BatchType get_batch() {
|
| 371 |
+
return get_batch(options_.batch_size());
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
/// This will clear any internal state and starts the internal prefetching
|
| 375 |
+
/// mechanism for the chunk dataset.
|
| 376 |
+
void reset() override {
|
| 377 |
+
// We need this to support partial data reads via dataloader iterator.
|
| 378 |
+
if (batch_buffer_) {
|
| 379 |
+
batch_buffer_->stop();
|
| 380 |
+
}
|
| 381 |
+
// free workers from previous reset if there is any.
|
| 382 |
+
free_workers();
|
| 383 |
+
preload_threads_.clear();
|
| 384 |
+
|
| 385 |
+
if (!load_checkpoint_) {
|
| 386 |
+
chunk_reader_.reset();
|
| 387 |
+
chunk_sampler_.reset(chunk_reader_.chunk_count());
|
| 388 |
+
load_checkpoint_ = false;
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
// Throw out any existing cached batch in the buffer and re-creates a new
|
| 392 |
+
// chunk buffer.
|
| 393 |
+
batch_buffer_ = std::make_unique<
|
| 394 |
+
detail::BatchDataBuffer<UnwrappedBatchType, ExampleSamplerType>>(
|
| 395 |
+
options_.batch_size(), example_sampler_, options_.cache_size());
|
| 396 |
+
|
| 397 |
+
// create new workers for this new epoch.
|
| 398 |
+
quit_worker_ = false;
|
| 399 |
+
|
| 400 |
+
AT_ASSERT(running_preloaders_ == 0);
|
| 401 |
+
running_preloaders_ = options_.preloader_count();
|
| 402 |
+
for (const auto i : c10::irange(options_.preloader_count())) {
|
| 403 |
+
preload_threads_.emplace_back([this, i]() { this->preloader(i); });
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
/// size is not used for chunk dataset.
|
| 408 |
+
optional<size_t> size() const override {
|
| 409 |
+
return torch::nullopt;
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
// provide a references to chunk sampler. Used mainly in distributed data
|
| 413 |
+
// loading to set the epoch number for the sampler.
|
| 414 |
+
ChunkSamplerType& chunk_sampler() {
|
| 415 |
+
return chunk_sampler_;
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
void save(serialize::OutputArchive& archive) const override {
|
| 419 |
+
std::lock_guard<std::mutex> lock(chunk_index_guard_);
|
| 420 |
+
chunk_sampler_.save(archive);
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
void load(serialize::InputArchive& archive) override {
|
| 424 |
+
std::lock_guard<std::mutex> lock(chunk_index_guard_);
|
| 425 |
+
chunk_sampler_.load(archive);
|
| 426 |
+
load_checkpoint_ = true;
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
private:
|
| 430 |
+
/// running on worker thread to preload chunk data.
|
| 431 |
+
void preloader(size_t id) {
|
| 432 |
+
while (!quit_worker_.load()) {
|
| 433 |
+
try {
|
| 434 |
+
std::vector<size_t> chunk_idx;
|
| 435 |
+
{
|
| 436 |
+
std::lock_guard<std::mutex> lock(chunk_index_guard_);
|
| 437 |
+
if (auto chunk_sampler_result = chunk_sampler_.next(
|
| 438 |
+
this->options_.cross_chunk_shuffle_count())) {
|
| 439 |
+
chunk_idx = chunk_sampler_result.value();
|
| 440 |
+
} else {
|
| 441 |
+
break;
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
UnwrappedBatchType data = chunk_reader_.read_chunk(chunk_idx[0]);
|
| 445 |
+
for (const auto i : c10::irange(1, chunk_idx.size())) {
|
| 446 |
+
auto chunk_data = chunk_reader_.read_chunk(chunk_idx[i]);
|
| 447 |
+
std::move(
|
| 448 |
+
chunk_data.begin(), chunk_data.end(), std::back_inserter(data));
|
| 449 |
+
}
|
| 450 |
+
if (preprocessing_policy_) {
|
| 451 |
+
preprocessing_policy_(data);
|
| 452 |
+
}
|
| 453 |
+
if (!data.empty()) { // skip empty chunks.
|
| 454 |
+
batch_buffer_->add_chunk_data(std::move(data));
|
| 455 |
+
}
|
| 456 |
+
} catch (...) {
|
| 457 |
+
batch_buffer_->add_chunk_data(std::current_exception());
|
| 458 |
+
}
|
| 459 |
+
}
|
| 460 |
+
AT_ASSERT(running_preloaders_.load() > 0);
|
| 461 |
+
--running_preloaders_;
|
| 462 |
+
if (running_preloaders_.load() == 0) {
|
| 463 |
+
// all preloaders are completed, so we can notify the batch_buffer.
|
| 464 |
+
batch_buffer_->stop();
|
| 465 |
+
}
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
/// Block the current thread until the workers finish execution and exit.
|
| 469 |
+
void free_workers() {
|
| 470 |
+
if (!quit_worker_.load()) {
|
| 471 |
+
quit_worker_ = true;
|
| 472 |
+
for (auto& worker_thread : preload_threads_) {
|
| 473 |
+
worker_thread.join();
|
| 474 |
+
}
|
| 475 |
+
}
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
private:
|
| 479 |
+
// Templated class that defines what is a chunk and how to read chunk data.
|
| 480 |
+
// When a chunk is returned by chunk_reader_, ChunkDataset split it into
|
| 481 |
+
// batches and caches them in batch_buffer_.
|
| 482 |
+
ChunkReader chunk_reader_;
|
| 483 |
+
|
| 484 |
+
// chunk sampler to shuffle different chunks
|
| 485 |
+
ChunkSamplerType chunk_sampler_;
|
| 486 |
+
|
| 487 |
+
// example sampler to shuffle examples in a specific chunk
|
| 488 |
+
ExampleSamplerType example_sampler_;
|
| 489 |
+
|
| 490 |
+
// batch data buffer which holds chunk data from preloading thread.
|
| 491 |
+
std::shared_ptr<
|
| 492 |
+
detail::BatchDataBuffer<UnwrappedBatchType, ExampleSamplerType>>
|
| 493 |
+
batch_buffer_;
|
| 494 |
+
|
| 495 |
+
// worker thread pool
|
| 496 |
+
std::vector<std::thread> preload_threads_;
|
| 497 |
+
|
| 498 |
+
/// The options the Dataset was configured with.
|
| 499 |
+
const ChunkDatasetOptions options_;
|
| 500 |
+
|
| 501 |
+
// function pointer wrapper to apply custom processing over chunk data. This
|
| 502 |
+
// is considered an advanced parameter for developers who want to apply a
|
| 503 |
+
// pre-process to the chunk data before sampling into minibatch.
|
| 504 |
+
// Different than the collate function, this policy is applied on the chunk
|
| 505 |
+
// level, instead of minibatch level. When a chunk of data is loaded (multiple
|
| 506 |
+
// chunks if cross_chunk_shuffle_count_ is greater than 1), this policy is
|
| 507 |
+
// applied to the full loaded data. It is useful if developers want to
|
| 508 |
+
// perform pre-processing (like bucketing) to the chunk data before
|
| 509 |
+
// example sampler samples the data. By default it's an empty pointer and no
|
| 510 |
+
// action will be taken.
|
| 511 |
+
std::function<void(UnwrappedBatchType&)> preprocessing_policy_;
|
| 512 |
+
|
| 513 |
+
// indicate whether the worker thread can be teared down
|
| 514 |
+
std::atomic<bool> quit_worker_;
|
| 515 |
+
|
| 516 |
+
// keep track of running preloaders to notify batch buffer. A value 0
|
| 517 |
+
// indicates that the chunk loading is completed.
|
| 518 |
+
std::atomic<size_t> running_preloaders_;
|
| 519 |
+
|
| 520 |
+
// mutex to synchronize chunk sampler next() call.
|
| 521 |
+
mutable std::mutex chunk_index_guard_;
|
| 522 |
+
|
| 523 |
+
// boolean value to indicate whether we need to load the checkpoint for
|
| 524 |
+
// chunk_sampler_.
|
| 525 |
+
bool load_checkpoint_;
|
| 526 |
+
};
|
| 527 |
+
} // namespace datasets
|
| 528 |
+
} // namespace data
|
| 529 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/map.h
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/datasets/base.h>
|
| 4 |
+
#include <torch/types.h>
|
| 5 |
+
|
| 6 |
+
#include <c10/util/ArrayRef.h>
|
| 7 |
+
|
| 8 |
+
#include <cstddef>
|
| 9 |
+
#include <type_traits>
|
| 10 |
+
#include <utility>
|
| 11 |
+
|
| 12 |
+
namespace torch {
|
| 13 |
+
namespace data {
|
| 14 |
+
namespace datasets {
|
| 15 |
+
namespace detail {
|
| 16 |
+
template <bool C, typename T>
|
| 17 |
+
using optional_if_t = typename std::conditional<C, torch::optional<T>, T>::type;
|
| 18 |
+
} // namespace detail
|
| 19 |
+
|
| 20 |
+
/// A `MapDataset` is a dataset that applies a transform to a source dataset.
|
| 21 |
+
template <typename SourceDataset, typename AppliedTransform>
|
| 22 |
+
class MapDataset : public BatchDataset<
|
| 23 |
+
MapDataset<SourceDataset, AppliedTransform>,
|
| 24 |
+
detail::optional_if_t<
|
| 25 |
+
SourceDataset::is_stateful,
|
| 26 |
+
typename AppliedTransform::OutputBatchType>,
|
| 27 |
+
typename SourceDataset::BatchRequestType> {
|
| 28 |
+
public:
|
| 29 |
+
using DatasetType = SourceDataset;
|
| 30 |
+
using TransformType = AppliedTransform;
|
| 31 |
+
using BatchRequestType = typename SourceDataset::BatchRequestType;
|
| 32 |
+
using OutputBatchType = detail::optional_if_t<
|
| 33 |
+
SourceDataset::is_stateful,
|
| 34 |
+
typename AppliedTransform::OutputBatchType>;
|
| 35 |
+
|
| 36 |
+
MapDataset(DatasetType dataset, TransformType transform)
|
| 37 |
+
: dataset_(std::move(dataset)), transform_(std::move(transform)) {}
|
| 38 |
+
|
| 39 |
+
/// Gets a batch from the source dataset and applies the transform to it,
|
| 40 |
+
/// returning the result.
|
| 41 |
+
OutputBatchType get_batch(BatchRequestType indices) override {
|
| 42 |
+
return get_batch_impl(std::move(indices));
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/// Returns the size of the source dataset.
|
| 46 |
+
// NOLINTNEXTLINE(bugprone-exception-escape)
|
| 47 |
+
optional<size_t> size() const noexcept override {
|
| 48 |
+
return dataset_.size();
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/// Calls `reset()` on the underlying dataset.
|
| 52 |
+
/// NOTE: Stateless datasets do not have a reset() method, so a call to this
|
| 53 |
+
/// method will only compile for stateful datasets (which have a reset()
|
| 54 |
+
/// method).
|
| 55 |
+
void reset() {
|
| 56 |
+
dataset_.reset();
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
/// Returns the underlying dataset.
|
| 60 |
+
const SourceDataset& dataset() noexcept {
|
| 61 |
+
return dataset_;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/// Returns the transform being applied.
|
| 65 |
+
const AppliedTransform& transform() noexcept {
|
| 66 |
+
return transform_;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
private:
|
| 70 |
+
/// The implementation of `get_batch()` for the stateless case, which simply
|
| 71 |
+
/// applies the transform to the output of `get_batch()` from the dataset.
|
| 72 |
+
template <
|
| 73 |
+
typename D = SourceDataset,
|
| 74 |
+
typename = std::enable_if_t<!D::is_stateful>>
|
| 75 |
+
OutputBatchType get_batch_impl(BatchRequestType indices) {
|
| 76 |
+
return transform_.apply_batch(dataset_.get_batch(std::move(indices)));
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/// The implementation of `get_batch()` for the stateful case. Here, we follow
|
| 80 |
+
/// the semantics of `Optional.map()` in many functional languages, which
|
| 81 |
+
/// applies a transformation to the optional's content when the optional
|
| 82 |
+
/// contains a value, and returns a new optional (of a different type) if the
|
| 83 |
+
/// original optional returned by `get_batch()` was empty.
|
| 84 |
+
template <typename D = SourceDataset>
|
| 85 |
+
std::enable_if_t<D::is_stateful, OutputBatchType> get_batch_impl(
|
| 86 |
+
BatchRequestType indices) {
|
| 87 |
+
if (auto batch = dataset_.get_batch(std::move(indices))) {
|
| 88 |
+
return transform_.apply_batch(std::move(*batch));
|
| 89 |
+
}
|
| 90 |
+
return nullopt;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
/// The underlying dataset being transformed.
|
| 94 |
+
SourceDataset dataset_;
|
| 95 |
+
|
| 96 |
+
// The transformation that is applied to batches received from the dataset.
|
| 97 |
+
AppliedTransform transform_;
|
| 98 |
+
};
|
| 99 |
+
|
| 100 |
+
/// Creates a `MapDataset` with the given dataset and transform.
|
| 101 |
+
template <typename DatasetType, typename TransformType>
|
| 102 |
+
MapDataset<DatasetType, TransformType> map(
|
| 103 |
+
DatasetType dataset,
|
| 104 |
+
TransformType transform) {
|
| 105 |
+
static_assert(
|
| 106 |
+
std::is_same<
|
| 107 |
+
typename std::conditional<
|
| 108 |
+
DatasetType::is_stateful,
|
| 109 |
+
typename DatasetType::BatchType::value_type,
|
| 110 |
+
typename DatasetType::BatchType>::type,
|
| 111 |
+
typename TransformType::InputBatchType>::value,
|
| 112 |
+
"BatchType type of dataset does not match input type of transform");
|
| 113 |
+
return {std::move(dataset), std::move(transform)};
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
} // namespace datasets
|
| 117 |
+
} // namespace data
|
| 118 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/mnist.h
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/datasets/base.h>
|
| 4 |
+
#include <torch/data/example.h>
|
| 5 |
+
#include <torch/types.h>
|
| 6 |
+
|
| 7 |
+
#include <torch/csrc/Export.h>
|
| 8 |
+
|
| 9 |
+
#include <cstddef>
|
| 10 |
+
#include <string>
|
| 11 |
+
|
| 12 |
+
namespace torch {
|
| 13 |
+
namespace data {
|
| 14 |
+
namespace datasets {
|
| 15 |
+
/// The MNIST dataset.
|
| 16 |
+
class TORCH_API MNIST : public Dataset<MNIST> {
|
| 17 |
+
public:
|
| 18 |
+
/// The mode in which the dataset is loaded.
|
| 19 |
+
enum class Mode { kTrain, kTest };
|
| 20 |
+
|
| 21 |
+
/// Loads the MNIST dataset from the `root` path.
|
| 22 |
+
///
|
| 23 |
+
/// The supplied `root` path should contain the *content* of the unzipped
|
| 24 |
+
/// MNIST dataset, available from http://yann.lecun.com/exdb/mnist.
|
| 25 |
+
explicit MNIST(const std::string& root, Mode mode = Mode::kTrain);
|
| 26 |
+
|
| 27 |
+
/// Returns the `Example` at the given `index`.
|
| 28 |
+
Example<> get(size_t index) override;
|
| 29 |
+
|
| 30 |
+
/// Returns the size of the dataset.
|
| 31 |
+
optional<size_t> size() const override;
|
| 32 |
+
|
| 33 |
+
/// Returns true if this is the training subset of MNIST.
|
| 34 |
+
// NOLINTNEXTLINE(bugprone-exception-escape)
|
| 35 |
+
bool is_train() const noexcept;
|
| 36 |
+
|
| 37 |
+
/// Returns all images stacked into a single tensor.
|
| 38 |
+
const Tensor& images() const;
|
| 39 |
+
|
| 40 |
+
/// Returns all targets stacked into a single tensor.
|
| 41 |
+
const Tensor& targets() const;
|
| 42 |
+
|
| 43 |
+
private:
|
| 44 |
+
Tensor images_, targets_;
|
| 45 |
+
};
|
| 46 |
+
} // namespace datasets
|
| 47 |
+
} // namespace data
|
| 48 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/shared.h
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/datasets/base.h>
|
| 4 |
+
|
| 5 |
+
#include <memory>
|
| 6 |
+
#include <utility>
|
| 7 |
+
|
| 8 |
+
namespace torch {
|
| 9 |
+
namespace data {
|
| 10 |
+
namespace datasets {
|
| 11 |
+
|
| 12 |
+
/// A dataset that wraps another dataset in a shared pointer and implements the
|
| 13 |
+
/// `BatchDataset` API, delegating all calls to the shared instance. This is
|
| 14 |
+
/// useful when you want all worker threads in the dataloader to access the same
|
| 15 |
+
/// dataset instance. The dataset must take care of synchronization and
|
| 16 |
+
/// thread-safe access itself.
|
| 17 |
+
///
|
| 18 |
+
/// Use `torch::data::datasets::make_shared_dataset()` to create a new
|
| 19 |
+
/// `SharedBatchDataset` like you would a `std::shared_ptr`.
|
| 20 |
+
template <typename UnderlyingDataset>
|
| 21 |
+
class SharedBatchDataset : public BatchDataset<
|
| 22 |
+
SharedBatchDataset<UnderlyingDataset>,
|
| 23 |
+
typename UnderlyingDataset::BatchType,
|
| 24 |
+
typename UnderlyingDataset::BatchRequestType> {
|
| 25 |
+
public:
|
| 26 |
+
using BatchType = typename UnderlyingDataset::BatchType;
|
| 27 |
+
using BatchRequestType = typename UnderlyingDataset::BatchRequestType;
|
| 28 |
+
|
| 29 |
+
/// Constructs a new `SharedBatchDataset` from a `shared_ptr` to the
|
| 30 |
+
/// `UnderlyingDataset`.
|
| 31 |
+
/* implicit */ SharedBatchDataset(
|
| 32 |
+
std::shared_ptr<UnderlyingDataset> shared_dataset)
|
| 33 |
+
: dataset_(std::move(shared_dataset)) {}
|
| 34 |
+
|
| 35 |
+
/// Calls `get_batch` on the underlying dataset.
|
| 36 |
+
BatchType get_batch(BatchRequestType request) override {
|
| 37 |
+
return dataset_->get_batch(std::move(request));
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/// Returns the `size` from the underlying dataset.
|
| 41 |
+
optional<size_t> size() const override {
|
| 42 |
+
return dataset_->size();
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/// Accesses the underlying dataset.
|
| 46 |
+
UnderlyingDataset& operator*() {
|
| 47 |
+
return *dataset_;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/// Accesses the underlying dataset.
|
| 51 |
+
const UnderlyingDataset& operator*() const {
|
| 52 |
+
return *dataset_;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/// Accesses the underlying dataset.
|
| 56 |
+
UnderlyingDataset* operator->() {
|
| 57 |
+
return dataset_.get();
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/// Accesses the underlying dataset.
|
| 61 |
+
const UnderlyingDataset* operator->() const {
|
| 62 |
+
return dataset_.get();
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/// Calls `reset()` on the underlying dataset.
|
| 66 |
+
void reset() {
|
| 67 |
+
dataset_->reset();
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
private:
|
| 71 |
+
std::shared_ptr<UnderlyingDataset> dataset_;
|
| 72 |
+
};
|
| 73 |
+
|
| 74 |
+
/// Constructs a new `SharedBatchDataset` by creating a
|
| 75 |
+
/// `shared_ptr<UnderlyingDatase>`. All arguments are forwarded to
|
| 76 |
+
/// `make_shared<UnderlyingDataset>`.
|
| 77 |
+
template <typename UnderlyingDataset, typename... Args>
|
| 78 |
+
SharedBatchDataset<UnderlyingDataset> make_shared_dataset(Args&&... args) {
|
| 79 |
+
return std::make_shared<UnderlyingDataset>(std::forward<Args>(args)...);
|
| 80 |
+
}
|
| 81 |
+
} // namespace datasets
|
| 82 |
+
} // namespace data
|
| 83 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/stateful.h
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/datasets/base.h>
|
| 4 |
+
#include <torch/data/example.h>
|
| 5 |
+
|
| 6 |
+
#include <cstddef>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
namespace torch {
|
| 10 |
+
namespace serialize {
|
| 11 |
+
class OutputArchive;
|
| 12 |
+
class InputArchive;
|
| 13 |
+
} // namespace serialize
|
| 14 |
+
} // namespace torch
|
| 15 |
+
|
| 16 |
+
namespace torch {
|
| 17 |
+
namespace data {
|
| 18 |
+
namespace datasets {
|
| 19 |
+
|
| 20 |
+
/// A stateful dataset is a dataset that maintains some internal state, which
|
| 21 |
+
/// will be `reset()` at the beginning of each epoch. Subclasses can override
|
| 22 |
+
/// the `reset()` method to configure this behavior. Further, the return type of
|
| 23 |
+
/// a stateful dataset's `get_batch()` method is always an `optional`. When the
|
| 24 |
+
/// stateful dataset wants to indicate to the dataloader that its epoch has
|
| 25 |
+
/// ended, it should return an empty optional. The dataloader knows to modify
|
| 26 |
+
/// its implementation based on whether the dataset is stateless or stateful.
|
| 27 |
+
///
|
| 28 |
+
/// Note that when subclassing a from `StatefulDataset<Self, T>`, the return
|
| 29 |
+
/// type of `get_batch()`, which the subclass must override, will be
|
| 30 |
+
/// `optional<T>` (i.e. the type specified in the `StatefulDataset`
|
| 31 |
+
/// specialization is automatically boxed into an `optional` for the dataset's
|
| 32 |
+
/// `BatchType`).
|
| 33 |
+
template <
|
| 34 |
+
typename Self,
|
| 35 |
+
typename Batch = std::vector<Example<>>,
|
| 36 |
+
typename BatchRequest = size_t>
|
| 37 |
+
class StatefulDataset
|
| 38 |
+
: public BatchDataset<Self, optional<Batch>, BatchRequest> {
|
| 39 |
+
public:
|
| 40 |
+
/// Resets internal state of the dataset.
|
| 41 |
+
virtual void reset() = 0;
|
| 42 |
+
|
| 43 |
+
/// Saves the statefulDataset's state to OutputArchive.
|
| 44 |
+
virtual void save(serialize::OutputArchive& archive) const = 0;
|
| 45 |
+
|
| 46 |
+
/// Deserializes the statefulDataset's state from the `archive`.
|
| 47 |
+
virtual void load(serialize::InputArchive& archive) = 0;
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
/// Serializes a statefulDataset to `OutputArchive`.
|
| 51 |
+
template <typename... Args>
|
| 52 |
+
serialize::OutputArchive& operator<<(
|
| 53 |
+
serialize::OutputArchive& archive,
|
| 54 |
+
const StatefulDataset<Args...>& statefulDataset) {
|
| 55 |
+
statefulDataset.save(archive);
|
| 56 |
+
return archive;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
/// Deserializes a statefulDataset from an `InputArchive`.
|
| 60 |
+
template <typename... Args>
|
| 61 |
+
serialize::InputArchive& operator>>(
|
| 62 |
+
serialize::InputArchive& archive,
|
| 63 |
+
StatefulDataset<Args...>& statefulDataset) {
|
| 64 |
+
statefulDataset.load(archive);
|
| 65 |
+
return archive;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
} // namespace datasets
|
| 69 |
+
} // namespace data
|
| 70 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/datasets/tensor.h
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/datasets/base.h>
|
| 4 |
+
#include <torch/data/example.h>
|
| 5 |
+
#include <torch/types.h>
|
| 6 |
+
|
| 7 |
+
#include <cstddef>
|
| 8 |
+
#include <vector>
|
| 9 |
+
|
| 10 |
+
namespace torch {
|
| 11 |
+
namespace data {
|
| 12 |
+
namespace datasets {
|
| 13 |
+
|
| 14 |
+
/// A dataset of tensors.
|
| 15 |
+
/// Stores a single tensor internally, which is then indexed inside `get()`.
|
| 16 |
+
struct TensorDataset : public Dataset<TensorDataset, TensorExample> {
|
| 17 |
+
/// Creates a `TensorDataset` from a vector of tensors.
|
| 18 |
+
explicit TensorDataset(const std::vector<Tensor>& tensors)
|
| 19 |
+
: TensorDataset(torch::stack(tensors)) {}
|
| 20 |
+
|
| 21 |
+
explicit TensorDataset(torch::Tensor tensor) : tensor(std::move(tensor)) {}
|
| 22 |
+
|
| 23 |
+
/// Returns a single `TensorExample`.
|
| 24 |
+
TensorExample get(size_t index) override {
|
| 25 |
+
return tensor[index];
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/// Returns the number of tensors in the dataset.
|
| 29 |
+
optional<size_t> size() const override {
|
| 30 |
+
return tensor.size(0);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
Tensor tensor;
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
} // namespace datasets
|
| 37 |
+
} // namespace data
|
| 38 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/data_shuttle.h
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/data/detail/queue.h>
|
| 4 |
+
#include <torch/types.h>
|
| 5 |
+
|
| 6 |
+
#include <c10/util/Exception.h>
|
| 7 |
+
#include <c10/util/Optional.h>
|
| 8 |
+
|
| 9 |
+
#include <chrono>
|
| 10 |
+
#include <utility>
|
| 11 |
+
|
| 12 |
+
namespace torch {
|
| 13 |
+
namespace data {
|
| 14 |
+
namespace detail {
|
| 15 |
+
|
| 16 |
+
/// Encapsulates the full life cycle of DataLoader jobs.
|
| 17 |
+
///
|
| 18 |
+
/// When a new job is enqueued to the `DataShuttle`, a counter for in-flight
|
| 19 |
+
/// jobs is bumped. This job is said to be "in-flight" until its result is
|
| 20 |
+
/// popped. Worker threads dequeue jobs as soon as they are available. When a
|
| 21 |
+
/// worker finishes a job, it enqueues the result. Only when the main thread
|
| 22 |
+
/// dequeues a result is the count of in-flight jobs decremented. When the main
|
| 23 |
+
/// thread attempts to dequeue a job but no jobs are in-flight, that means the
|
| 24 |
+
/// epoch is complete and `pop_result` returns an empty optional.
|
| 25 |
+
template <typename Job, typename Result>
|
| 26 |
+
class DataShuttle {
|
| 27 |
+
public:
|
| 28 |
+
/// Pushes a new job. Called by the main thread.
|
| 29 |
+
void push_job(Job job) {
|
| 30 |
+
new_jobs_.push(std::move(job));
|
| 31 |
+
++in_flight_jobs_;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
/// Pushes the result of a job. Called by worker threads.
|
| 35 |
+
void push_result(Result result) {
|
| 36 |
+
results_.push(std::move(result));
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/// Returns the next job, blocking until there is one available. Called by
|
| 40 |
+
/// worker threads.
|
| 41 |
+
Job pop_job() {
|
| 42 |
+
return new_jobs_.pop();
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/// Returns the result of a job, or nullopt if all jobs were exhausted. Called
|
| 46 |
+
/// by the main thread.
|
| 47 |
+
optional<Result> pop_result(
|
| 48 |
+
optional<std::chrono::milliseconds> timeout = nullopt) {
|
| 49 |
+
if (in_flight_jobs_ > 0) {
|
| 50 |
+
auto result = results_.pop(timeout);
|
| 51 |
+
--in_flight_jobs_;
|
| 52 |
+
return result;
|
| 53 |
+
}
|
| 54 |
+
return nullopt;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/// Discards any jobs that are not yet in flight, and waits for all in-flight
|
| 58 |
+
/// jobs to finish, discarding their result.
|
| 59 |
+
void drain() {
|
| 60 |
+
// Clear all inputs so that no further jobs are scheduled.
|
| 61 |
+
auto number_cleared = new_jobs_.clear();
|
| 62 |
+
in_flight_jobs_ -= number_cleared;
|
| 63 |
+
// Remove any outstanding results.
|
| 64 |
+
while (in_flight_jobs_ > 0) {
|
| 65 |
+
pop_result();
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
/// Returns the number of jobs that are still in progress.
|
| 70 |
+
/// When this number is zero, an epoch is finished.
|
| 71 |
+
size_t in_flight_jobs() const noexcept {
|
| 72 |
+
return in_flight_jobs_;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
private:
|
| 76 |
+
/// The queue for jobs that are not yet in flight.
|
| 77 |
+
Queue<Job> new_jobs_;
|
| 78 |
+
/// The number of in-flight jobs.
|
| 79 |
+
/// NOTE: Not atomic because only manipulated by the main thread.
|
| 80 |
+
size_t in_flight_jobs_ = 0;
|
| 81 |
+
/// The queue for results of finished jobs.
|
| 82 |
+
Queue<Result> results_;
|
| 83 |
+
};
|
| 84 |
+
|
| 85 |
+
} // namespace detail
|
| 86 |
+
} // namespace data
|
| 87 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/queue.h
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/types.h>
|
| 4 |
+
|
| 5 |
+
#include <c10/util/Exception.h>
|
| 6 |
+
|
| 7 |
+
#include <chrono>
|
| 8 |
+
#include <condition_variable>
|
| 9 |
+
#include <cstddef>
|
| 10 |
+
#include <mutex>
|
| 11 |
+
#include <queue>
|
| 12 |
+
|
| 13 |
+
namespace torch {
|
| 14 |
+
namespace data {
|
| 15 |
+
namespace detail {
|
| 16 |
+
|
| 17 |
+
/// A basic locked, blocking MPMC queue.
|
| 18 |
+
///
|
| 19 |
+
/// Every `push` and `pop` is guarded by a mutex. A condition variable is used
|
| 20 |
+
/// to communicate insertion of new elements, such that waiting threads will be
|
| 21 |
+
/// woken up if they are currently waiting inside a call to `pop()`.
|
| 22 |
+
///
|
| 23 |
+
/// Note that this data structure is written specifically for use with the
|
| 24 |
+
/// `DataLoader`. Its behavior is tailored to this use case and may not be
|
| 25 |
+
/// applicable to more general uses.
|
| 26 |
+
template <typename T>
|
| 27 |
+
class Queue {
|
| 28 |
+
public:
|
| 29 |
+
/// Pushes a new value to the back of the `Queue` and notifies one thread on
|
| 30 |
+
/// the waiting side about this event.
|
| 31 |
+
void push(T value) {
|
| 32 |
+
{
|
| 33 |
+
std::lock_guard<std::mutex> lock(mutex_);
|
| 34 |
+
queue_.push(std::move(value));
|
| 35 |
+
}
|
| 36 |
+
cv_.notify_one();
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/// Blocks until at least one element is ready to be popped from the front of
|
| 40 |
+
/// the queue. An optional `timeout` in seconds can be used to limit the time
|
| 41 |
+
/// spent waiting for an element. If the wait times out, an exception is
|
| 42 |
+
/// raised.
|
| 43 |
+
T pop(optional<std::chrono::milliseconds> timeout = nullopt) {
|
| 44 |
+
std::unique_lock<std::mutex> lock(mutex_);
|
| 45 |
+
if (timeout) {
|
| 46 |
+
if (!cv_.wait_for(
|
| 47 |
+
lock, *timeout, [this] { return !this->queue_.empty(); })) {
|
| 48 |
+
// clang-format off
|
| 49 |
+
AT_ERROR(
|
| 50 |
+
"Timeout in DataLoader queue while waiting for next batch"
|
| 51 |
+
" (timeout was ", timeout->count(), " ms)");
|
| 52 |
+
// clang-format on
|
| 53 |
+
}
|
| 54 |
+
} else {
|
| 55 |
+
cv_.wait(lock, [this] { return !this->queue_.empty(); });
|
| 56 |
+
}
|
| 57 |
+
AT_ASSERT(!queue_.empty());
|
| 58 |
+
T value = queue_.front();
|
| 59 |
+
queue_.pop();
|
| 60 |
+
lock.unlock();
|
| 61 |
+
return value;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/// Empties the queue and returns the number of elements that were present at
|
| 65 |
+
/// the start of the function. No threads are notified about this event as it
|
| 66 |
+
/// is assumed to be used to drain the queue during shutdown of a
|
| 67 |
+
/// `DataLoader`.
|
| 68 |
+
size_t clear() {
|
| 69 |
+
std::lock_guard<std::mutex> lock(this->mutex_);
|
| 70 |
+
const auto size = queue_.size();
|
| 71 |
+
while (!queue_.empty()) {
|
| 72 |
+
queue_.pop();
|
| 73 |
+
}
|
| 74 |
+
return size;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
private:
|
| 78 |
+
std::queue<T> queue_;
|
| 79 |
+
std::mutex mutex_;
|
| 80 |
+
std::condition_variable cv_;
|
| 81 |
+
};
|
| 82 |
+
} // namespace detail
|
| 83 |
+
} // namespace data
|
| 84 |
+
} // namespace torch
|
data/home/.local/lib/python3.8/site-packages/torch/include/torch/csrc/api/include/torch/data/detail/sequencers.h
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/types.h>
|
| 4 |
+
|
| 5 |
+
#include <algorithm>
|
| 6 |
+
#include <cstddef>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
namespace torch {
|
| 10 |
+
namespace data {
|
| 11 |
+
namespace detail {
|
| 12 |
+
namespace sequencers {
|
| 13 |
+
namespace detail {
|
| 14 |
+
template <typename Result>
|
| 15 |
+
bool buffer_contains_result(const std::vector<optional<Result>>& buffer) {
|
| 16 |
+
return std::any_of(
|
| 17 |
+
buffer.begin(), buffer.end(), [](const optional<Result>& result) {
|
| 18 |
+
return result.has_value();
|
| 19 |
+
});
|
| 20 |
+
}
|
| 21 |
+
} // namespace detail
|
| 22 |
+
|
| 23 |
+
/// A `Sequencer` accepts a function that yields the next result of a
|
| 24 |
+
/// `DataLoader` and then has the opportunity to influence the order in which
|
| 25 |
+
/// these results are returned. The `NoSequencer` does not enforce any
|
| 26 |
+
/// sequencing and returns any result directly. The `OrderedSequencer` instead
|
| 27 |
+
/// buffers results internally to return them in order of their sequence number.
|
| 28 |
+
template <typename Result>
|
| 29 |
+
struct Sequencer {
|
| 30 |
+
using ResultProducer = std::function<optional<Result>()>;
|
| 31 |
+
virtual ~Sequencer() = default;
|
| 32 |
+
virtual optional<Result> next(ResultProducer next_result) = 0;
|
| 33 |
+
};
|
| 34 |
+
|
| 35 |
+
/// A `Sequencer` that does not enforce any ordering. It is effectively the
|
| 36 |
+
/// identity function.
|
| 37 |
+
template <typename Result>
|
| 38 |
+
struct NoSequencer final : public Sequencer<Result> {
|
| 39 |
+
using typename Sequencer<Result>::ResultProducer;
|
| 40 |
+
optional<Result> next(ResultProducer next_result) override {
|
| 41 |
+
return next_result();
|
| 42 |
+
}
|
| 43 |
+
};
|
| 44 |
+
|
| 45 |
+
/// A `Sequencer` that buffers results and returns them in order of their
|
| 46 |
+
/// sequence number. The `OrderedSequencer` maintains an internal, monotonically
|
| 47 |
+
/// incrementing counter for the next sequence number it expects. If it receives
|
| 48 |
+
/// a result with a higher sequence number, it will buffer it for later (when
|
| 49 |
+
/// the sequence number reaches that of this result). Otherwise, if the sequence
|
| 50 |
+
/// numbers match, the result is returned.
|
| 51 |
+
///
|
| 52 |
+
/// Implementation note: The `OrderedSequencer` is implemented with a fixed-size
|
| 53 |
+
/// buffer. Let `m` be the maximum number of jobs in the data loader's queue and
|
| 54 |
+
/// `s` be the current sequence number. Assume `m` jobs are scheduled in the
|
| 55 |
+
/// `DataLoader`. Any new result is stored at index `job.sqn mod m` in the
|
| 56 |
+
/// `OrderedSequencer`. Why are we sure sequence numbers of new jobs will not
|
| 57 |
+
/// collide with sequence numbers of buffered jobs? The `OrderedSequencer` will
|
| 58 |
+
/// not return from `next()` until it receives the result with sqn `s`. This
|
| 59 |
+
/// means no new jobs can be scheduled in the `DataLoader` in the meantime,
|
| 60 |
+
/// which enforces that as long as sqn `s` has not been received, `s + m` (which
|
| 61 |
+
/// would cause a collision in the fixed-size buffer) will not yet be scheduled.
|
| 62 |
+
template <typename Result>
|
| 63 |
+
struct OrderedSequencer : public Sequencer<Result> {
|
| 64 |
+
using typename Sequencer<Result>::ResultProducer;
|
| 65 |
+
|
| 66 |
+
/// Constructs the `OrderedSequencer` with the maximum number of results it
|
| 67 |
+
/// will ever hold at one point in time.
|
| 68 |
+
explicit OrderedSequencer(size_t max_jobs) : buffer_(max_jobs) {}
|
| 69 |
+
|
| 70 |
+
/// Buffers results until the next one in the expected order is received.
|
| 71 |
+
optional<Result> next(ResultProducer next_result) override {
|
| 72 |
+
// If we already have the result for the next sqn, return it.
|
| 73 |
+
if (auto& maybe_result = buffer(next_sequence_number_)) {
|
| 74 |
+
auto result = std::move(*maybe_result);
|
| 75 |
+
buffer(next_sequence_number_++).reset();
|
| 76 |
+
return result;
|
| 77 |
+
}
|
| 78 |
+
// Otherwise wait for the next result.
|
| 79 |
+
while (true) {
|
| 80 |
+
auto result = next_result();
|
| 81 |
+
if (!result) {
|
| 82 |
+
AT_ASSERT(!detail::buffer_contains_result(buffer_));
|
| 83 |
+
break;
|
| 84 |
+
}
|
| 85 |
+
// If it was not nullopt and the sequence numbers match, return it
|
| 86 |
+
// directly and bump the sequence number.
|
| 87 |
+
if (result->sequence_number == next_sequence_number_) {
|
| 88 |
+
++next_sequence_number_;
|
| 89 |
+
return result;
|
| 90 |
+
}
|
| 91 |
+
// Stash the result for later.
|
| 92 |
+
AT_ASSERT(!buffer(result->sequence_number).has_value());
|
| 93 |
+
buffer(result->sequence_number) = std::move(result);
|
| 94 |
+
}
|
| 95 |
+
// The result was an empty optional, so we are done with this epoch.
|
| 96 |
+
return nullopt;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
/// Accesses the buffer at the `index` modulo the buffer size.
|
| 100 |
+
optional<Result>& buffer(size_t index) {
|
| 101 |
+
return buffer_.at(index % buffer_.size());
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
/// The monotonically increasing sequence number we expect.
|
| 105 |
+
size_t next_sequence_number_ = 0;
|
| 106 |
+
|
| 107 |
+
/// A fixed-size buffer (after construction).
|
| 108 |
+
std::vector<optional<Result>> buffer_;
|
| 109 |
+
};
|
| 110 |
+
} // namespace sequencers
|
| 111 |
+
} // namespace detail
|
| 112 |
+
} // namespace data
|
| 113 |
+
} // namespace torch
|